blob: a0075edeb765992d5b90e0b238539e5acfc8e788 [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 Bazanskidd5b03c2024-05-16 18:07:06 +020049 "source.monogon.dev/go/qcow2"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010050 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski66e58952021-10-05 17:06:56 +020051 "source.monogon.dev/metropolis/node"
52 "source.monogon.dev/metropolis/node/core/rpc"
Serge Bazanski5bb8a332022-06-23 17:41:33 +020053 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020054 "source.monogon.dev/metropolis/test/localregistry"
55 "source.monogon.dev/osbase/test/launch"
Serge Bazanski66e58952021-10-05 17:06:56 +020056)
57
Serge Bazanski53458ba2024-06-18 09:56:46 +000058const (
Serge Bazanski20498dd2024-09-30 17:07:08 +000059 // NodeNumberKey is the key of the node label used to carry a node's numerical
Serge Bazanski53458ba2024-06-18 09:56:46 +000060 // index in the test system.
Serge Bazanski20498dd2024-09-30 17:07:08 +000061 NodeNumberKey string = "test-node-number"
Serge Bazanski53458ba2024-06-18 09:56:46 +000062)
63
Leopold20a036e2023-01-15 00:17:19 +010064// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020065type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010066 // Name is a human-readable identifier to be used in debug output.
67 Name string
68
Jan Schära9b060b2024-08-07 10:42:29 +020069 // CPUs is the number of virtual CPUs of the VM.
70 CPUs int
71
72 // ThreadsPerCPU is the number of threads per CPU. This is multiplied by
73 // CPUs to get the total number of threads.
74 ThreadsPerCPU int
75
76 // MemoryMiB is the RAM size in MiB of the VM.
77 MemoryMiB int
78
Jan Schär07003572024-08-26 10:42:16 +020079 // DiskBytes contains the size of the root disk in bytes or zero if the
80 // unmodified image size is used.
81 DiskBytes uint64
82
Serge Bazanski66e58952021-10-05 17:06:56 +020083 // Ports contains the port mapping where to expose the internal ports of the VM to
84 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
85 // ConnectToSocket is set.
86 Ports launch.PortMap
87
Leopold20a036e2023-01-15 00:17:19 +010088 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
89 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020090 // want to test reboot behavior this should be false.
91 AllowReboot bool
92
Leopold20a036e2023-01-15 00:17:19 +010093 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
94 // set, it is instead connected to the given file descriptor/socket. If this is
95 // set, all port maps from the Ports option are ignored. Intended for networking
96 // this instance together with others for running more complex network
97 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020098 ConnectToSocket *os.File
99
Leopoldacfad5b2023-01-15 14:05:25 +0100100 // When PcapDump is set, all traffic is dumped to a pcap file in the
101 // runtime directory (e.g. "net0.pcap" for the first interface).
102 PcapDump bool
103
Leopold20a036e2023-01-15 00:17:19 +0100104 // SerialPort is an io.ReadWriter over which you can communicate with the serial
105 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +0200106 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
107 SerialPort io.ReadWriter
108
109 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
110 // registering into a cluster.
111 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200112
113 // Mac is the node's MAC address.
114 Mac *net.HardwareAddr
115
116 // Runtime keeps the node's QEMU runtime state.
117 Runtime *NodeRuntime
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200118
119 // RunVNC starts a VNC socket for troubleshooting/testing console code. Note:
120 // this will not work in tests, as those use a built-in qemu which does not
121 // implement a VGA device.
122 RunVNC bool
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200123}
124
Leopold20a036e2023-01-15 00:17:19 +0100125// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200126type NodeRuntime struct {
127 // ld points at the node's launch directory storing data such as storage
128 // images, firmware variables or the TPM state.
129 ld string
130 // sd points at the node's socket directory.
131 sd string
132
133 // ctxT is the context QEMU will execute in.
134 ctxT context.Context
135 // CtxC is the QEMU context's cancellation function.
136 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200137}
138
139// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200140var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200141 node.ConsensusPort,
142
143 node.CuratorServicePort,
144 node.DebugServicePort,
145
146 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100147 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200148 node.CuratorServicePort,
149 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200150 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200151}
152
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200153// setupRuntime creates the node's QEMU runtime directory, together with all
154// files required to preserve its state, a level below the chosen path ld. The
155// node's socket directory is similarily created a level below sd. It may
156// return an I/O error.
Jan Schär07003572024-08-26 10:42:16 +0200157func setupRuntime(ld, sd string, diskBytes uint64) (*NodeRuntime, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200158 // Create a temporary directory to keep all the runtime files.
159 stdp, err := os.MkdirTemp(ld, "node_state*")
160 if err != nil {
161 return nil, fmt.Errorf("failed to create the state directory: %w", err)
162 }
163
164 // Initialize the node's storage with a prebuilt image.
Jan Schär07003572024-08-26 10:42:16 +0200165 st, err := os.Stat(xNodeImagePath)
166 if err != nil {
167 return nil, fmt.Errorf("cannot read image file: %w", err)
168 }
169 diskBytes = max(diskBytes, uint64(st.Size()))
170
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200171 di := filepath.Join(stdp, "image.qcow2")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000172 launch.Log("Cluster: generating node QCOW2 snapshot image: %s -> %s", xNodeImagePath, di)
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200173
174 df, err := os.Create(di)
175 if err != nil {
176 return nil, fmt.Errorf("while opening image for writing: %w", err)
177 }
178 defer df.Close()
Jan Schär07003572024-08-26 10:42:16 +0200179 if err := qcow2.Generate(df, qcow2.GenerateWithBackingFile(xNodeImagePath), qcow2.GenerateWithFileSize(diskBytes)); err != nil {
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200180 return nil, fmt.Errorf("while creating copy-on-write node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200181 }
182
183 // Initialize the OVMF firmware variables file.
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000184 dv := filepath.Join(stdp, filepath.Base(xOvmfVarsPath))
185 if err := copyFile(xOvmfVarsPath, dv); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200186 return nil, fmt.Errorf("while copying firmware variables: %w", err)
187 }
188
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200189 // Create the socket directory.
190 sotdp, err := os.MkdirTemp(sd, "node_sock*")
191 if err != nil {
192 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
193 }
194
195 return &NodeRuntime{
196 ld: stdp,
197 sd: sotdp,
198 }, nil
199}
200
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200201// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200202// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200203func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200204 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200205 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanskica8d9512024-09-12 14:20:57 +0200206 r := resolver.New(c.ctxT, resolver.WithLogger(logging.NewFunctionBackend(func(severity logging.Severity, msg string) {
207 launch.Log("Cluster: client resolver: %s: %s", severity, msg)
208 })))
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100209 for _, n := range c.Nodes {
210 r.AddEndpoint(resolver.NodeAtAddressWithDefaultPort(n.ManagementAddress))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200211 }
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100212 authClient, err := grpc.NewClient(resolver.MetropolisControlAddress,
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200213 grpc.WithTransportCredentials(authCreds),
214 grpc.WithResolvers(r),
215 grpc.WithContextDialer(c.DialNode),
216 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200217 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100218 return nil, fmt.Errorf("creating client with owner credentials failed: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200219 }
220 c.authClient = authClient
221 }
222 return c.authClient, nil
223}
224
Serge Bazanski66e58952021-10-05 17:06:56 +0200225// LaunchNode launches a single Metropolis node instance with the given options.
226// The instance runs mostly paravirtualized but with some emulated hardware
227// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200228// writable, and the changes are kept across reboots and shutdowns. ld and sd
229// point to the launch directory and the socket directory, holding the nodes'
230// state files (storage, tpm state, firmware state), and UNIX socket files
231// (swtpm <-> QEMU interplay) respectively. The directories must exist before
232// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
233// if either are not initialized.
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200234func LaunchNode(ctx context.Context, ld, sd string, tpmFactory *TPMFactory, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200235 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
236 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200237 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
238 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
239 // that we open and pass the name of it to QEMU. Not pinning this crashes both
240 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
241 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200242
Jan Schära9b060b2024-08-07 10:42:29 +0200243 if options.CPUs == 0 {
244 options.CPUs = 1
245 }
246 if options.ThreadsPerCPU == 0 {
247 options.ThreadsPerCPU = 1
248 }
249 if options.MemoryMiB == 0 {
250 options.MemoryMiB = 2048
251 }
252
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200253 // If it's the node's first start, set up its runtime directories.
254 if options.Runtime == nil {
Jan Schär07003572024-08-26 10:42:16 +0200255 r, err := setupRuntime(ld, sd, options.DiskBytes)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200256 if err != nil {
257 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200258 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200259 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200260 }
261
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200262 // Replace the node's context with a new one.
263 r := options.Runtime
264 if r.CtxC != nil {
265 r.CtxC()
266 }
267 r.ctxT, r.CtxC = context.WithCancel(ctx)
268
Serge Bazanski66e58952021-10-05 17:06:56 +0200269 var qemuNetType string
270 var qemuNetConfig launch.QemuValue
271 if options.ConnectToSocket != nil {
272 qemuNetType = "socket"
273 qemuNetConfig = launch.QemuValue{
274 "id": {"net0"},
275 "fd": {"3"},
276 }
277 } else {
278 qemuNetType = "user"
279 qemuNetConfig = launch.QemuValue{
280 "id": {"net0"},
281 "net": {"10.42.0.0/24"},
282 "dhcpstart": {"10.42.0.10"},
283 "hostfwd": options.Ports.ToQemuForwards(),
284 }
285 }
286
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200287 // Generate the node's MAC address if it isn't already set in NodeOptions.
288 if options.Mac == nil {
289 mac, err := generateRandomEthernetMAC()
290 if err != nil {
291 return err
292 }
293 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200294 }
295
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200296 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
297 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200298 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200299 qemuArgs := []string{
Jan Schära9b060b2024-08-07 10:42:29 +0200300 "-machine", "q35",
301 "-accel", "kvm",
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200302 "-display", "none",
Jan Schära9b060b2024-08-07 10:42:29 +0200303 "-nodefaults",
304 "-cpu", "host",
305 "-m", fmt.Sprintf("%dM", options.MemoryMiB),
306 "-smp", fmt.Sprintf("cores=%d,threads=%d", options.CPUs, options.ThreadsPerCPU),
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000307 "-drive", "if=pflash,format=raw,readonly=on,file=" + xOvmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200308 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200309 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200310 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200311 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200312 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
313 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
314 "-device", "tpm-tis,tpmdev=tpm0",
315 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200316 "-serial", "stdio",
317 }
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200318 if options.RunVNC {
319 vncSocketPath := filepath.Join(r.sd, "vnc-socket")
320 qemuArgs = append(qemuArgs,
321 "-vnc", "unix:"+vncSocketPath,
322 "-device", "virtio-vga",
323 )
324 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200325
326 if !options.AllowReboot {
327 qemuArgs = append(qemuArgs, "-no-reboot")
328 }
329
330 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200331 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200332 parametersRaw, err := proto.Marshal(options.NodeParameters)
333 if err != nil {
334 return fmt.Errorf("failed to encode node paraeters: %w", err)
335 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200336 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200337 return fmt.Errorf("failed to write node parameters: %w", err)
338 }
339 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
340 }
341
Leopoldacfad5b2023-01-15 14:05:25 +0100342 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200343 qemuNetDump := launch.QemuValue{
344 "id": {"net0"},
345 "netdev": {"net0"},
346 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100347 }
348 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
349 }
350
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200351 // Manufacture TPM if needed.
352 tpmd := filepath.Join(r.ld, "tpm")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000353 err := tpmFactory.Manufacture(ctx, tpmd, &TPMPlatform{
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200354 Manufacturer: "Monogon",
355 Version: "1.0",
356 Model: "TestCluster",
357 })
358 if err != nil {
359 return fmt.Errorf("could not manufacture TPM: %w", err)
360 }
361
Serge Bazanski66e58952021-10-05 17:06:56 +0200362 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200363 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200364
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000365 tpmEmuCmd := exec.CommandContext(tpmCtx, xSwtpmPath, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000366 // Silence warnings from unsafe libtpms build (uses non-constant-time
367 // cryptographic operations).
368 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200369 tpmEmuCmd.Stderr = os.Stderr
370 tpmEmuCmd.Stdout = os.Stdout
371
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100372 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200373 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200374 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200375 return fmt.Errorf("failed to start TPM emulator: %w", err)
376 }
377
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200378 // Wait for the socket to be created by the TPM emulator before launching
379 // QEMU.
380 for {
381 _, err := os.Stat(tpmSocketPath)
382 if err == nil {
383 break
384 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200385 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200386 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200387 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
388 }
389 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200390 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200391 return fmt.Errorf("while waiting for the TPM socket: %w", err)
392 }
393 time.Sleep(time.Millisecond * 100)
394 }
395
Serge Bazanski66e58952021-10-05 17:06:56 +0200396 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200397 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200398 if options.ConnectToSocket != nil {
399 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
400 }
401
402 var stdErrBuf bytes.Buffer
403 systemCmd.Stderr = &stdErrBuf
404 systemCmd.Stdout = options.SerialPort
405
Leopoldaf5086b2023-01-15 14:12:42 +0100406 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
407
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200408 go func() {
409 launch.Log("Node: Starting...")
410 err = systemCmd.Run()
411 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200412
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200413 // Stop TPM emulator and wait for it to exit to properly reap the child process
414 tpmCancel()
415 launch.Log("Node: Waiting for TPM emulator to exit")
416 // Wait returns a SIGKILL error because we just cancelled its context.
417 // We still need to call it to avoid creating zombies.
418 errTpm := tpmEmuCmd.Wait()
419 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200420
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200421 var exerr *exec.ExitError
422 if err != nil && errors.As(err, &exerr) {
423 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
424 if status.Signaled() && status.Signal() == syscall.SIGKILL {
425 // Process was killed externally (most likely by our context being canceled).
426 // This is a normal exit for us, so return nil
427 doneC <- nil
428 return
429 }
430 exerr.Stderr = stdErrBuf.Bytes()
431 newErr := launch.QEMUError(*exerr)
432 launch.Log("Node: %q", stdErrBuf.String())
433 doneC <- &newErr
434 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200435 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200436 doneC <- err
437 }()
438 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200439}
440
441func copyFile(src, dst string) error {
442 in, err := os.Open(src)
443 if err != nil {
444 return fmt.Errorf("when opening source: %w", err)
445 }
446 defer in.Close()
447
448 out, err := os.Create(dst)
449 if err != nil {
450 return fmt.Errorf("when creating destination: %w", err)
451 }
452 defer out.Close()
453
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100454 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200455 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100456 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200457 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100458
459 // Copy the file while preserving its sparseness. The image files are very
460 // sparse (less than 10% allocated), so this is a lot faster.
461 var lastHoleStart int64
462 for {
463 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
464 if err != nil {
465 return fmt.Errorf("when seeking to next data block: %w", err)
466 }
467 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
468 if err != nil {
469 return fmt.Errorf("when seeking to next hole: %w", err)
470 }
471 lastHoleStart = holeStart
472 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
473 return fmt.Errorf("when seeking to current data block: %w", err)
474 }
475 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
476 return fmt.Errorf("when seeking output to next data block: %w", err)
477 }
478 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
479 return fmt.Errorf("when copying file: %w", err)
480 }
481 if endPos == holeStart {
482 // The next hole is at the end of the file, we're done here.
483 break
484 }
485 }
486
Serge Bazanski66e58952021-10-05 17:06:56 +0200487 return out.Close()
488}
489
Serge Bazanskie78a0892021-10-07 17:03:49 +0200490// getNodes wraps around Management.GetNodes to return a list of nodes in a
491// cluster.
492func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200493 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100494 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100495 err := backoff.Retry(func() error {
496 res = nil
497 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200498 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100499 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200500 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100501 for {
502 node, err := srvN.Recv()
503 if err == io.EOF {
504 break
505 }
506 if err != nil {
507 return fmt.Errorf("GetNodes.Recv: %w", err)
508 }
509 res = append(res, node)
510 }
511 return nil
512 }, bo)
513 if err != nil {
514 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200515 }
516 return res, nil
517}
518
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200519// getNode wraps Management.GetNodes. It returns node information matching
520// given node ID.
521func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
522 nodes, err := getNodes(ctx, mgmt)
523 if err != nil {
524 return nil, fmt.Errorf("could not get nodes: %w", err)
525 }
526 for _, n := range nodes {
Jan Schär39d9c242024-09-24 13:49:55 +0200527 if n.Id == id {
528 return n, nil
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200529 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200530 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200531 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200532}
533
Serge Bazanski66e58952021-10-05 17:06:56 +0200534// Gets a random EUI-48 Ethernet MAC address
535func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
536 macBuf := make([]byte, 6)
537 _, err := rand.Read(macBuf)
538 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200539 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200540 }
541
542 // Set U/L bit and clear I/G bit (locally administered individual MAC)
543 // Ref IEEE 802-2014 Section 8.2.2
544 macBuf[0] = (macBuf[0] | 2) & 0xfe
545 mac := net.HardwareAddr(macBuf)
546 return &mac, nil
547}
548
Serge Bazanskibe742842022-04-04 13:18:50 +0200549const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200550
Serge Bazanskibe742842022-04-04 13:18:50 +0200551// ClusterPorts contains all ports handled by Nanoswitch.
552var ClusterPorts = []uint16{
553 // Forwarded to the first node.
554 uint16(node.CuratorServicePort),
555 uint16(node.DebugServicePort),
556 uint16(node.KubernetesAPIPort),
557 uint16(node.KubernetesAPIWrappedPort),
558
559 // SOCKS proxy to the switch network
560 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200561}
562
563// ClusterOptions contains all options for launching a Metropolis cluster.
564type ClusterOptions struct {
565 // The number of nodes this cluster should be started with.
566 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100567
Jan Schära9b060b2024-08-07 10:42:29 +0200568 // Node are default options of all nodes.
569 Node NodeOptions
570
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100571 // If true, node logs will be saved to individual files instead of being printed
572 // out to stderr. The path of these files will be still printed to stdout.
573 //
574 // The files will be located within the launch directory inside TEST_TMPDIR (or
575 // the default tempdir location, if not set).
576 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200577
578 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
579 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
580 // incomplete.
581 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200582
583 // Optional local registry which will be made available to the cluster to
584 // pull images from. This is a more efficient alternative to preseeding all
585 // images used for testing.
586 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200587
588 // InitialClusterConfiguration will be passed to the first node when creating the
589 // cluster, and defines some basic properties of the cluster. If not specified,
590 // the cluster will default to defaults as defined in
591 // metropolis.proto.api.NodeParameters.
592 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200593}
594
595// Cluster is the running Metropolis cluster launched using the LaunchCluster
596// function.
597type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200598 // Owner is the TLS Certificate of the owner of the test cluster. This can be
599 // used to authenticate further clients to the running cluster.
600 Owner tls.Certificate
601 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200602 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200603 Ports launch.PortMap
604
Serge Bazanskibe742842022-04-04 13:18:50 +0200605 // Nodes is a map from Node ID to its runtime information.
606 Nodes map[string]*NodeInCluster
607 // NodeIDs is a list of node IDs that are backing this cluster, in order of
608 // creation.
609 NodeIDs []string
610
Serge Bazanski54e212a2023-06-14 13:45:11 +0200611 // CACertificate is the cluster's CA certificate.
612 CACertificate *x509.Certificate
613
Serge Bazanski66e58952021-10-05 17:06:56 +0200614 // nodesDone is a list of channels populated with the return codes from all the
615 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100616 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200617 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200618 // nodeOpts are the cluster member nodes' mutable launch options, kept here
619 // to facilitate reboots.
620 nodeOpts []NodeOptions
621 // launchDir points at the directory keeping the nodes' state, such as storage
622 // images, firmware variable files, TPM state.
623 launchDir string
624 // socketDir points at the directory keeping UNIX socket files, such as these
625 // used to facilitate communication between QEMU and swtpm. It's different
626 // from launchDir, and anchored nearer the file system root, due to the
627 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100628 socketDir string
629 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200630
Lorenz Brun276a7462023-07-12 21:28:54 +0200631 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200632 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200633 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200634
635 // authClient is a cached authenticated owner connection to a Curator
636 // instance within the cluster.
637 authClient *grpc.ClientConn
638
639 // ctxT is the context individual node contexts are created from.
640 ctxT context.Context
641 // ctxC is used by Close to cancel the context under which the nodes are
642 // running.
643 ctxC context.CancelFunc
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200644
645 tpmFactory *TPMFactory
Serge Bazanskibe742842022-04-04 13:18:50 +0200646}
647
648// NodeInCluster represents information about a node that's part of a Cluster.
649type NodeInCluster struct {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100650 // ID of the node, which can be used to dial this node's services via
651 // NewNodeClient.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200652 ID string
653 Pubkey []byte
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100654 // Address of the node on the network ran by nanoswitch. Not reachable from
655 // the host unless dialed via NewNodeClient or via the nanoswitch SOCKS
656 // proxy (reachable on Cluster.Ports[SOCKSPort]).
Serge Bazanskibe742842022-04-04 13:18:50 +0200657 ManagementAddress string
658}
659
660// firstConnection performs the initial owner credential escrow with a newly
661// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
662// running at 10.1.0.2, which is always the case with the current nanoswitch
663// implementation.
664//
Leopold20a036e2023-01-15 00:17:19 +0100665// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200666// information as NodeInCluster.
667func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
668 // Dial external service.
669 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100670 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200671 if err != nil {
672 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
673 }
674 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
675 return socksDialer.Dial("tcp", addr)
676 }
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100677 initClient, err := grpc.NewClient(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
Serge Bazanskibe742842022-04-04 13:18:50 +0200678 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100679 return nil, nil, fmt.Errorf("creating client with ephemeral credentials failed: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200680 }
681 defer initClient.Close()
682
683 // Retrieve owner certificate - this can take a while because the node is still
684 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100685 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200686 aaa := apb.NewAAAClient(initClient)
687 var cert *tls.Certificate
688 err = backoff.Retry(func() error {
689 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
690 if st, ok := status.FromError(err); ok {
691 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100692 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200693 return err
694 }
695 }
696 return backoff.Permanent(err)
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200697 }, backoff.WithContext(backoff.NewExponentialBackOff(backoff.WithMaxElapsedTime(time.Minute)), ctx))
Serge Bazanskibe742842022-04-04 13:18:50 +0200698 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200699 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200700 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100701 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200702
703 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200704 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100705 authClient, err := grpc.NewClient(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
Serge Bazanskibe742842022-04-04 13:18:50 +0200706 if err != nil {
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +0100707 return nil, nil, fmt.Errorf("creating client with owner credentials failed: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200708 }
709 defer authClient.Close()
710 mgmt := apb.NewManagementClient(authClient)
711
712 var node *NodeInCluster
713 err = backoff.Retry(func() error {
714 nodes, err := getNodes(ctx, mgmt)
715 if err != nil {
716 return fmt.Errorf("retrieving nodes failed: %w", err)
717 }
718 if len(nodes) != 1 {
719 return fmt.Errorf("expected one node, got %d", len(nodes))
720 }
721 n := nodes[0]
722 if n.Status == nil || n.Status.ExternalAddress == "" {
723 return fmt.Errorf("node has no status and/or address")
724 }
725 node = &NodeInCluster{
Jan Schär39d9c242024-09-24 13:49:55 +0200726 ID: n.Id,
Serge Bazanskibe742842022-04-04 13:18:50 +0200727 ManagementAddress: n.Status.ExternalAddress,
728 }
729 return nil
730 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
731 if err != nil {
732 return nil, nil, err
733 }
734
735 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200736}
737
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100738func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200739 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100740 if err != nil {
741 return nil, err
742 }
743 return f, nil
744}
745
Serge Bazanski66e58952021-10-05 17:06:56 +0200746// LaunchCluster launches a cluster of Metropolis node VMs together with a
747// Nanoswitch instance to network them all together.
748//
749// The given context will be used to run all qemu instances in the cluster, and
750// canceling the context or calling Close() will terminate them.
751func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200752 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200753 return nil, errors.New("refusing to start cluster with zero nodes")
754 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200755
Jan Schära9b060b2024-08-07 10:42:29 +0200756 // Prepare the node options. These will be kept as part of Cluster.
757 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
758 // launch. The runtime information can be later used to restart a node.
759 // The 0th node will be initialized first. The rest will follow after it
760 // had bootstrapped the cluster.
761 nodeOpts := make([]NodeOptions, opts.NumNodes)
762 for i := range opts.NumNodes {
763 nodeOpts[i] = opts.Node
764 nodeOpts[i].Name = fmt.Sprintf("node%d", i)
765 nodeOpts[i].SerialPort = newPrefixedStdio(i)
766 }
767 nodeOpts[0].NodeParameters = &apb.NodeParameters{
768 Cluster: &apb.NodeParameters_ClusterBootstrap_{
769 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
770 OwnerPublicKey: InsecurePublicKey,
771 InitialClusterConfiguration: opts.InitialClusterConfiguration,
772 Labels: &cpb.NodeLabels{
773 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +0000774 {Key: NodeNumberKey, Value: "0"},
Jan Schära9b060b2024-08-07 10:42:29 +0200775 },
776 },
777 },
778 },
779 }
780 nodeOpts[0].PcapDump = true
781
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200782 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100783 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200784 if err != nil {
785 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
786 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100787 // Create the metroctl config directory. We keep it in /tmp because in some
788 // scenarios it's end-user visible and we want it short.
789 md, err := os.MkdirTemp("/tmp", "metroctl-*")
790 if err != nil {
791 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
792 }
793
794 // Create the socket directory. We keep it in /tmp because of socket path limits.
795 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200796 if err != nil {
797 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
798 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200799
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200800 // Set up TPM factory.
801 tpmf, err := NewTPMFactory(filepath.Join(ld, "tpm"))
802 if err != nil {
803 return nil, fmt.Errorf("failed to create TPM factory: %w", err)
804 }
805
Serge Bazanski66e58952021-10-05 17:06:56 +0200806 // Prepare links between nodes and nanoswitch.
807 var switchPorts []*os.File
Jan Schära9b060b2024-08-07 10:42:29 +0200808 for i := range opts.NumNodes {
Serge Bazanski66e58952021-10-05 17:06:56 +0200809 switchPort, vmPort, err := launch.NewSocketPair()
810 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200811 return nil, fmt.Errorf("failed to get socketpair: %w", err)
812 }
813 switchPorts = append(switchPorts, switchPort)
Jan Schära9b060b2024-08-07 10:42:29 +0200814 nodeOpts[i].ConnectToSocket = vmPort
Serge Bazanski66e58952021-10-05 17:06:56 +0200815 }
816
Serge Bazanskie78a0892021-10-07 17:03:49 +0200817 // Make a list of channels that will be populated by all running node qemu
818 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200819 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200820 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200821 done[i] = make(chan error, 1)
822 }
823
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100824 if opts.NodeLogsToFiles {
Lorenz Brun4beaf4f2025-01-14 16:10:55 +0100825 nodeLogDir := ld
826 if os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR") != "" {
827 nodeLogDir = os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR")
828 }
Jan Schära9b060b2024-08-07 10:42:29 +0200829 for i := range opts.NumNodes {
Lorenz Brun4beaf4f2025-01-14 16:10:55 +0100830 path := path.Join(nodeLogDir, fmt.Sprintf("node-%d.txt", i))
Jan Schära9b060b2024-08-07 10:42:29 +0200831 port, err := NewSerialFileLogger(path)
832 if err != nil {
833 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
834 }
835 launch.Log("Node %d logs at %s", i, path)
836 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100837 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100838 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200839
840 // Start the first node.
841 ctxT, ctxC := context.WithCancel(ctx)
Jan Schär0b927652024-07-31 18:08:50 +0200842 launch.Log("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200843 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200844 ctxC()
845 return nil, fmt.Errorf("failed to launch first node: %w", err)
846 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200847
Lorenz Brun150f24a2023-07-13 20:11:06 +0200848 localRegistryAddr := net.TCPAddr{
849 IP: net.IPv4(10, 42, 0, 82),
850 Port: 5000,
851 }
852
853 var guestSvcMap launch.GuestServiceMap
854 if opts.LocalRegistry != nil {
855 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
856 if err != nil {
857 ctxC()
858 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
859 }
860 s := http.Server{
861 Handler: opts.LocalRegistry,
862 }
863 go s.Serve(l)
864 go func() {
865 <-ctxT.Done()
866 s.Close()
867 }()
868 guestSvcMap = launch.GuestServiceMap{
869 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
870 }
871 }
872
Serge Bazanskie78a0892021-10-07 17:03:49 +0200873 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200874 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
875 if err != nil {
876 ctxC()
877 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
878 }
879
880 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100881 var serialPort io.ReadWriter
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100882 var err error
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100883 if opts.NodeLogsToFiles {
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100884 loggerPath := path.Join(ld, "nanoswitch.txt")
885 serialPort, err = NewSerialFileLogger(loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100886 if err != nil {
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100887 launch.Fatal("Could not open log file for nanoswitch: %v", err)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100888 }
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100889 launch.Log("Nanoswitch logs at %s", loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100890 } else {
891 serialPort = newPrefixedStdio(99)
892 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200893 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100894 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000895 KernelPath: xKernelPath,
896 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200897 ExtraNetworkInterfaces: switchPorts,
898 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200899 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100900 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100901 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200902 }); err != nil {
903 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100904 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200905 }
906 }
907 }()
908
Serge Bazanskibe742842022-04-04 13:18:50 +0200909 // Build SOCKS dialer.
910 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
911 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200912 if err != nil {
913 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200914 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200915 }
916
Serge Bazanskibe742842022-04-04 13:18:50 +0200917 // Retrieve owner credentials and first node.
918 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200919 if err != nil {
920 ctxC()
921 return nil, err
922 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200923
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100924 // Write credentials to the metroctl directory.
925 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
926 ctxC()
927 return nil, fmt.Errorf("could not write owner key: %w", err)
928 }
929 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
930 ctxC()
931 return nil, fmt.Errorf("could not write owner certificate: %w", err)
932 }
933
Serge Bazanski53458ba2024-06-18 09:56:46 +0000934 launch.Log("Cluster: Node %d is %s", 0, firstNode.ID)
935
936 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200937 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200938 cluster := &Cluster{
939 Owner: *cert,
940 Ports: portMap,
941 Nodes: map[string]*NodeInCluster{
942 firstNode.ID: firstNode,
943 },
944 NodeIDs: []string{
945 firstNode.ID,
946 },
947
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100948 nodesDone: done,
949 nodeOpts: nodeOpts,
950 launchDir: ld,
951 socketDir: sd,
952 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200953
Lorenz Brun276a7462023-07-12 21:28:54 +0200954 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200955
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200956 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200957 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200958
959 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +0200960 }
961
962 // Now start the rest of the nodes and register them into the cluster.
963
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200964 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200965 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200966 if err != nil {
967 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200968 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200969 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200970 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200971
972 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100973 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200974 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
975 if err != nil {
976 ctxC()
977 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
978 }
979 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100980 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200981
982 // Retrieve cluster info (for directory and ca public key) to register further
983 // nodes.
984 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
985 if err != nil {
986 ctxC()
987 return nil, fmt.Errorf("GetClusterInfo: %w", err)
988 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200989 caCert, err := x509.ParseCertificate(resI.CaCertificate)
990 if err != nil {
991 ctxC()
992 return nil, fmt.Errorf("ParseCertificate: %w", err)
993 }
994 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200995
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200996 // Use the retrieved information to configure the rest of the node options.
997 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +0200998 nodeOpts[i].NodeParameters = &apb.NodeParameters{
999 Cluster: &apb.NodeParameters_ClusterRegister_{
1000 ClusterRegister: &apb.NodeParameters_ClusterRegister{
1001 RegisterTicket: ticket,
1002 ClusterDirectory: resI.ClusterDirectory,
1003 CaCertificate: resI.CaCertificate,
1004 Labels: &cpb.NodeLabels{
1005 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +00001006 {Key: NodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +02001007 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001008 },
1009 },
1010 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001011 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001012 }
1013
1014 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001015 for i := 1; i < opts.NumNodes; i++ {
Jan Schär0b927652024-07-31 18:08:50 +02001016 launch.Log("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001017 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001018 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001019 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001020 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001021 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001022
Serge Bazanski53458ba2024-06-18 09:56:46 +00001023 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001024 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001025 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001026 nodeNumberToID := make(map[int]string)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001027 launch.Log("Cluster: waiting for nodes to appear as NEW...")
1028 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001029 for {
1030 nodes, err := getNodes(ctx, mgmt)
1031 if err != nil {
1032 ctxC()
1033 return nil, fmt.Errorf("could not get nodes: %w", err)
1034 }
1035 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001036 if n.State != cpb.NodeState_NODE_STATE_NEW {
1037 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001038 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001039 if seenNodes[n.Id] {
1040 continue
1041 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001042 seenNodes[n.Id] = true
1043 cluster.Nodes[n.Id] = &NodeInCluster{
1044 ID: n.Id,
1045 Pubkey: n.Pubkey,
1046 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001047
Serge Bazanski20498dd2024-09-30 17:07:08 +00001048 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, NodeNumberKey))
Serge Bazanski53458ba2024-06-18 09:56:46 +00001049 if err != nil {
1050 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1051 }
1052 launch.Log("Cluster: Node %d is %s", num, n.Id)
1053 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001054 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001055
1056 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001057 break
1058 }
1059 time.Sleep(1 * time.Second)
1060 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001061 }
1062 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001063
Serge Bazanski53458ba2024-06-18 09:56:46 +00001064 // Build the rest of NodeIDs from map.
1065 for i := 1; i < opts.NumNodes; i++ {
1066 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1067 }
1068
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001069 approvedNodes := make(map[string]bool)
1070 upNodes := make(map[string]bool)
1071 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001072 for {
1073 nodes, err := getNodes(ctx, mgmt)
1074 if err != nil {
1075 ctxC()
1076 return nil, fmt.Errorf("could not get nodes: %w", err)
1077 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001078 for _, node := range nodes {
1079 if !seenNodes[node.Id] {
1080 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001081 continue
1082 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001083
1084 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1085 launch.Log("Cluster: node %s is up", node.Id)
1086 upNodes[node.Id] = true
1087 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001088 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001089 if upNodes[node.Id] {
1090 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001091 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001092
1093 if !approvedNodes[node.Id] {
1094 launch.Log("Cluster: approving node %s", node.Id)
1095 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1096 Pubkey: node.Pubkey,
1097 })
1098 if err != nil {
1099 ctxC()
1100 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1101 }
1102 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001103 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001104 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001105
Jan Schär0b927652024-07-31 18:08:50 +02001106 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001107 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001108 break
1109 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001110 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001111 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001112 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001113
Serge Bazanski05f813b2023-03-16 17:58:39 +01001114 launch.Log("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001115 for i, nodeID := range cluster.NodeIDs {
1116 launch.Log("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001117 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001118 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001119
Serge Bazanskibe742842022-04-04 13:18:50 +02001120 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001121}
1122
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001123// RebootNode reboots the cluster member node matching the given index, and
1124// waits for it to rejoin the cluster. It will use the given context ctx to run
1125// cluster API requests, whereas the resulting QEMU process will be created
1126// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1127func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1128 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001129 return fmt.Errorf("index out of bounds")
1130 }
1131 if c.nodeOpts[idx].Runtime == nil {
1132 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001133 }
1134 id := c.NodeIDs[idx]
1135
1136 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001137 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001138 if err != nil {
1139 return err
1140 }
1141 mgmt := apb.NewManagementClient(curC)
1142
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001143 // Cancel the node's context. This will shut down QEMU.
1144 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001145 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001146 err = <-c.nodesDone[idx]
1147 if err != nil {
1148 return fmt.Errorf("while restarting node: %w", err)
1149 }
1150
1151 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001152 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001153 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 +02001154 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1155 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001156
Serge Bazanskibc969572024-03-21 11:56:13 +01001157 start := time.Now()
1158
1159 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001160 for {
1161 cs, err := getNode(ctx, mgmt, id)
1162 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001163 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001164 return err
1165 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001166 launch.Log("Cluster: node health: %+v", cs.Health)
1167
1168 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001169 if lhb.After(start) && cs.Health == apb.Node_HEALTH_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001170 break
1171 }
1172 time.Sleep(time.Second)
1173 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001174 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001175 return nil
1176}
1177
Serge Bazanski500f6e02024-04-03 12:06:40 +02001178// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1179// given by idx. If the node is already shut down, this is a no-op.
1180func (c *Cluster) ShutdownNode(idx int) error {
1181 if idx < 0 || idx >= len(c.NodeIDs) {
1182 return fmt.Errorf("index out of bounds")
1183 }
1184 // Return if node is already stopped.
1185 select {
1186 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1187 return nil
1188 default:
1189 }
1190 id := c.NodeIDs[idx]
1191
1192 // Cancel the node's context. This will shut down QEMU.
1193 c.nodeOpts[idx].Runtime.CtxC()
1194 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1195 err := <-c.nodesDone[idx]
1196 if err != nil {
1197 return fmt.Errorf("while shutting down node: %w", err)
1198 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001199 launch.Log("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001200 return nil
1201}
1202
1203// StartNode performs a power on of the node given by idx. If the node is already
1204// running, this is a no-op.
1205func (c *Cluster) StartNode(idx int) error {
1206 if idx < 0 || idx >= len(c.NodeIDs) {
1207 return fmt.Errorf("index out of bounds")
1208 }
1209 id := c.NodeIDs[idx]
1210 // Return if node is already running.
1211 select {
1212 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1213 default:
1214 return nil
1215 }
1216
1217 // Start QEMU again.
1218 launch.Log("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001219 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 +02001220 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1221 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001222 launch.Log("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001223 return nil
1224}
1225
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001226// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001227// nodes to stop. It returns an error if stopping the nodes failed, or one of
1228// the nodes failed to fully start in the first place.
1229func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001230 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001231 if c.authClient != nil {
1232 c.authClient.Close()
1233 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001234 c.ctxC()
1235
Leopold20a036e2023-01-15 00:17:19 +01001236 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001237 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001238 for _, c := range c.nodesDone {
1239 err := <-c
1240 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001241 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001242 }
1243 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001244 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001245 os.RemoveAll(c.launchDir)
1246 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001247 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001248 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001249 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001250}
Serge Bazanskibe742842022-04-04 13:18:50 +02001251
1252// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1253// their ID. This is performed by connecting to the cluster nanoswitch via its
1254// SOCKS proxy, and using the cluster node list for name resolution.
1255//
1256// For example:
1257//
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +01001258// grpc.NewClient("passthrough:///metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001259func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1260 host, port, err := net.SplitHostPort(addr)
1261 if err != nil {
1262 return nil, fmt.Errorf("invalid host:port: %w", err)
1263 }
1264 // Already an IP address?
1265 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001266 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001267 }
1268
1269 // Otherwise, expect a node name.
1270 node, ok := c.Nodes[host]
1271 if !ok {
1272 return nil, fmt.Errorf("unknown node %q", host)
1273 }
1274 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001275 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001276}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001277
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001278// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1279// Kubernetes authenticating proxy using the cluster owner identity.
1280// It currently has access to everything (i.e. the cluster-admin role)
1281// via the owner-admin binding.
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001282func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, *rest.Config, error) {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001283 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1284 if err != nil {
1285 // We explicitly pass an Ed25519 private key in, so this can't happen
1286 panic(err)
1287 }
1288
1289 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001290 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001291 Host: host,
1292 TLSClientConfig: rest.TLSClientConfig{
1293 // TODO(q3k): use CA certificate
1294 Insecure: true,
1295 ServerName: "kubernetes.default.svc",
1296 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1297 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1298 },
1299 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1300 return c.DialNode(ctx, address)
1301 },
1302 }
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001303 clientSet, err := kubernetes.NewForConfig(&clientConfig)
1304 if err != nil {
1305 return nil, nil, err
1306 }
1307 return clientSet, &clientConfig, nil
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001308}
1309
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001310// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1311// which are currently Kubernetes controllers, ie. run an apiserver. This list
1312// might be empty if no node is currently configured with the
1313// 'KubernetesController' node.
1314func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1315 curC, err := c.CuratorClient()
1316 if err != nil {
1317 return nil, err
1318 }
1319 mgmt := apb.NewManagementClient(curC)
1320 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1321 Filter: "has(node.roles.kubernetes_controller)",
1322 })
1323 if err != nil {
1324 return nil, err
1325 }
1326 defer srv.CloseSend()
1327 var res []string
1328 for {
1329 n, err := srv.Recv()
1330 if err == io.EOF {
1331 break
1332 }
1333 if err != nil {
1334 return nil, err
1335 }
1336 if n.Status == nil || n.Status.ExternalAddress == "" {
1337 continue
1338 }
1339 res = append(res, n.Status.ExternalAddress)
1340 }
1341 return res, nil
1342}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001343
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001344// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1345// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001346func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1347 // Get an authenticated owner client within the cluster.
1348 curC, err := c.CuratorClient()
1349 if err != nil {
1350 return err
1351 }
1352 mgmt := apb.NewManagementClient(curC)
1353 nodes, err := getNodes(ctx, mgmt)
1354 if err != nil {
1355 return err
1356 }
1357
1358 var unhealthy []string
1359 for _, node := range nodes {
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001360 if node.Health == apb.Node_HEALTH_HEALTHY {
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001361 continue
1362 }
1363 unhealthy = append(unhealthy, node.Id)
1364 }
1365 if len(unhealthy) == 0 {
1366 return nil
1367 }
1368 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1369}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001370
1371// ApproveNode approves a node by ID, waiting for it to become UP.
1372func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1373 curC, err := c.CuratorClient()
1374 if err != nil {
1375 return err
1376 }
1377 mgmt := apb.NewManagementClient(curC)
1378
1379 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1380 Pubkey: c.Nodes[id].Pubkey,
1381 })
1382 if err != nil {
1383 return fmt.Errorf("ApproveNode: %w", err)
1384 }
1385 launch.Log("Cluster: %s: approved, waiting for UP", id)
1386 for {
1387 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1388 if err != nil {
1389 return fmt.Errorf("GetNodes: %w", err)
1390 }
1391 found := false
1392 for {
1393 node, err := nodes.Recv()
1394 if errors.Is(err, io.EOF) {
1395 break
1396 }
1397 if err != nil {
1398 return fmt.Errorf("Nodes.Recv: %w", err)
1399 }
1400 if node.Id != id {
1401 continue
1402 }
1403 if node.State != cpb.NodeState_NODE_STATE_UP {
1404 continue
1405 }
1406 found = true
1407 break
1408 }
1409 nodes.CloseSend()
1410
1411 if found {
1412 break
1413 }
1414 time.Sleep(time.Second)
1415 }
1416 launch.Log("Cluster: %s: UP", id)
1417 return nil
1418}
1419
1420// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1421func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1422 curC, err := c.CuratorClient()
1423 if err != nil {
1424 return err
1425 }
1426 mgmt := apb.NewManagementClient(curC)
1427
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001428 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1429 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1430 Node: &apb.UpdateNodeRolesRequest_Id{
1431 Id: id,
1432 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001433 KubernetesWorker: ptr.To(true),
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001434 })
1435 return err
1436}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001437
Jan Schära9b060b2024-08-07 10:42:29 +02001438// MakeKubernetesController adds the KubernetesController role to a node by ID.
1439func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1440 curC, err := c.CuratorClient()
1441 if err != nil {
1442 return err
1443 }
1444 mgmt := apb.NewManagementClient(curC)
1445
Jan Schära9b060b2024-08-07 10:42:29 +02001446 launch.Log("Cluster: %s: adding KubernetesController", id)
1447 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1448 Node: &apb.UpdateNodeRolesRequest_Id{
1449 Id: id,
1450 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001451 KubernetesController: ptr.To(true),
Jan Schära9b060b2024-08-07 10:42:29 +02001452 })
1453 return err
1454}
1455
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001456// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1457func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1458 curC, err := c.CuratorClient()
1459 if err != nil {
1460 return err
1461 }
1462 mgmt := apb.NewManagementClient(curC)
1463 cur := ipb.NewCuratorClient(curC)
1464
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001465 launch.Log("Cluster: %s: adding ConsensusMember", id)
1466 bo := backoff.NewExponentialBackOff()
1467 bo.MaxElapsedTime = 10 * time.Second
1468
1469 backoff.Retry(func() error {
1470 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1471 Node: &apb.UpdateNodeRolesRequest_Id{
1472 Id: id,
1473 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001474 ConsensusMember: ptr.To(true),
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001475 })
1476 if err != nil {
1477 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1478 }
1479 return err
1480 }, backoff.WithContext(bo, ctx))
1481 if err != nil {
1482 return err
1483 }
1484
1485 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1486
1487 learner := false
1488 for {
1489 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1490 if err != nil {
1491 return fmt.Errorf("GetConsensusStatus: %w", err)
1492 }
1493 for _, member := range res.EtcdMember {
1494 if member.Id != id {
1495 continue
1496 }
1497 switch member.Status {
1498 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1499 if !learner {
1500 learner = true
1501 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1502 }
1503 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1504 launch.Log("Cluster: %s: became a full member", id)
1505 return nil
1506 }
1507 }
1508 time.Sleep(100 * time.Millisecond)
1509 }
1510}