blob: d8eb8cd64103c4c1f15407f679c418c854fadb2d [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"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010055 "source.monogon.dev/osbase/test/qemu"
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.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +010086 Ports qemu.PortMap
Serge Bazanski66e58952021-10-05 17:06:56 +020087
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 Windelschmidtd0cdb572025-03-27 17:18:39 +0100172 logf("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) {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100207 logf("Cluster: client resolver: %s: %s", severity, msg)
Serge Bazanskica8d9512024-09-12 14:20:57 +0200208 })))
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
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100270 var qemuNetConfig qemu.QemuValue
Serge Bazanski66e58952021-10-05 17:06:56 +0200271 if options.ConnectToSocket != nil {
272 qemuNetType = "socket"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100273 qemuNetConfig = qemu.QemuValue{
Serge Bazanski66e58952021-10-05 17:06:56 +0200274 "id": {"net0"},
275 "fd": {"3"},
276 }
277 } else {
278 qemuNetType = "user"
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100279 qemuNetConfig = qemu.QemuValue{
Serge Bazanski66e58952021-10-05 17:06:56 +0200280 "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 Windelschmidtd0cdb572025-03-27 17:18:39 +0100343 qemuNetDump := qemu.QemuValue{
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200344 "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
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100406 qemu.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
Leopoldaf5086b2023-01-15 14:12:42 +0100407
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200408 go func() {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100409 logf("Node: Starting...")
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200410 err = systemCmd.Run()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100411 logf("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()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100415 logf("Node: Waiting for TPM emulator to exit")
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200416 // 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()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100419 logf("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()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100431 newErr := qemu.QEMUError(*exerr)
432 logf("Node: %q", stdErrBuf.String())
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200433 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).
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100603 Ports qemu.PortMap
Serge Bazanski66e58952021-10-05 17:06:56 +0200604
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.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100685 logf("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 {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100692 logf("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 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100701 logf("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 }
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200787
788 nodeLogDir := ld
789 if os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR") != "" {
790 nodeLogDir = os.Getenv("TEST_UNDECLARED_OUTPUTS_DIR")
791 }
792
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100793 // Create the metroctl config directory. We keep it in /tmp because in some
794 // scenarios it's end-user visible and we want it short.
795 md, err := os.MkdirTemp("/tmp", "metroctl-*")
796 if err != nil {
797 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
798 }
799
800 // Create the socket directory. We keep it in /tmp because of socket path limits.
801 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200802 if err != nil {
803 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
804 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200805
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200806 // Set up TPM factory.
807 tpmf, err := NewTPMFactory(filepath.Join(ld, "tpm"))
808 if err != nil {
809 return nil, fmt.Errorf("failed to create TPM factory: %w", err)
810 }
811
Serge Bazanski66e58952021-10-05 17:06:56 +0200812 // Prepare links between nodes and nanoswitch.
813 var switchPorts []*os.File
Jan Schära9b060b2024-08-07 10:42:29 +0200814 for i := range opts.NumNodes {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100815 switchPort, vmPort, err := qemu.NewSocketPair()
Serge Bazanski66e58952021-10-05 17:06:56 +0200816 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200817 return nil, fmt.Errorf("failed to get socketpair: %w", err)
818 }
819 switchPorts = append(switchPorts, switchPort)
Jan Schära9b060b2024-08-07 10:42:29 +0200820 nodeOpts[i].ConnectToSocket = vmPort
Serge Bazanski66e58952021-10-05 17:06:56 +0200821 }
822
Serge Bazanskie78a0892021-10-07 17:03:49 +0200823 // Make a list of channels that will be populated by all running node qemu
824 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200825 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200826 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200827 done[i] = make(chan error, 1)
828 }
829
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100830 if opts.NodeLogsToFiles {
Jan Schära9b060b2024-08-07 10:42:29 +0200831 for i := range opts.NumNodes {
Lorenz Brun4beaf4f2025-01-14 16:10:55 +0100832 path := path.Join(nodeLogDir, fmt.Sprintf("node-%d.txt", i))
Jan Schära9b060b2024-08-07 10:42:29 +0200833 port, err := NewSerialFileLogger(path)
834 if err != nil {
835 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
836 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100837 logf("Node %d logs at %s", i, path)
Jan Schära9b060b2024-08-07 10:42:29 +0200838 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100839 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100840 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200841
842 // Start the first node.
843 ctxT, ctxC := context.WithCancel(ctx)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100844 logf("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200845 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200846 ctxC()
847 return nil, fmt.Errorf("failed to launch first node: %w", err)
848 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200849
Lorenz Brun150f24a2023-07-13 20:11:06 +0200850 localRegistryAddr := net.TCPAddr{
851 IP: net.IPv4(10, 42, 0, 82),
852 Port: 5000,
853 }
854
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100855 var guestSvcMap qemu.GuestServiceMap
Lorenz Brun150f24a2023-07-13 20:11:06 +0200856 if opts.LocalRegistry != nil {
857 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
858 if err != nil {
859 ctxC()
860 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
861 }
862 s := http.Server{
863 Handler: opts.LocalRegistry,
864 }
865 go s.Serve(l)
866 go func() {
867 <-ctxT.Done()
868 s.Close()
869 }()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100870 guestSvcMap = qemu.GuestServiceMap{
Lorenz Brun150f24a2023-07-13 20:11:06 +0200871 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
872 }
873 }
874
Serge Bazanskie78a0892021-10-07 17:03:49 +0200875 // Launch nanoswitch.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100876 portMap, err := qemu.ConflictFreePortMap(ClusterPorts)
Serge Bazanski66e58952021-10-05 17:06:56 +0200877 if err != nil {
878 ctxC()
879 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
880 }
881
882 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100883 var serialPort io.ReadWriter
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100884 var err error
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100885 if opts.NodeLogsToFiles {
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200886
887 loggerPath := path.Join(nodeLogDir, "nanoswitch.txt")
Tim Windelschmidta5b00bd2024-12-09 22:52:31 +0100888 serialPort, err = NewSerialFileLogger(loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100889 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100890 logf("Could not open log file for nanoswitch: %v", err)
891 os.Exit(1)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100892 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100893 logf("Nanoswitch logs at %s", loggerPath)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100894 } else {
895 serialPort = newPrefixedStdio(99)
896 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100897 if err := qemu.RunMicroVM(ctxT, &qemu.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100898 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000899 KernelPath: xKernelPath,
900 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200901 ExtraNetworkInterfaces: switchPorts,
902 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200903 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100904 SerialPort: serialPort,
Tim Windelschmidt1fe3f942025-04-01 14:22:11 +0200905 PcapDump: path.Join(nodeLogDir, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200906 }); err != nil {
907 if !errors.Is(err, ctxT.Err()) {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100908 logf("Failed to launch nanoswitch: %v", err)
909 os.Exit(1)
Serge Bazanski66e58952021-10-05 17:06:56 +0200910 }
911 }
912 }()
913
Serge Bazanskibe742842022-04-04 13:18:50 +0200914 // Build SOCKS dialer.
915 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
916 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200917 if err != nil {
918 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200919 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200920 }
921
Serge Bazanskibe742842022-04-04 13:18:50 +0200922 // Retrieve owner credentials and first node.
923 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200924 if err != nil {
925 ctxC()
926 return nil, err
927 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200928
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100929 // Write credentials to the metroctl directory.
930 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
931 ctxC()
932 return nil, fmt.Errorf("could not write owner key: %w", err)
933 }
934 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
935 ctxC()
936 return nil, fmt.Errorf("could not write owner certificate: %w", err)
937 }
938
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100939 logf("Cluster: Node %d is %s", 0, firstNode.ID)
Serge Bazanski53458ba2024-06-18 09:56:46 +0000940
941 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200942 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200943 cluster := &Cluster{
944 Owner: *cert,
945 Ports: portMap,
946 Nodes: map[string]*NodeInCluster{
947 firstNode.ID: firstNode,
948 },
949 NodeIDs: []string{
950 firstNode.ID,
951 },
952
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100953 nodesDone: done,
954 nodeOpts: nodeOpts,
955 launchDir: ld,
956 socketDir: sd,
957 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200958
Lorenz Brun276a7462023-07-12 21:28:54 +0200959 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200960
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200961 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200962 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200963
964 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +0200965 }
966
967 // Now start the rest of the nodes and register them into the cluster.
968
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200969 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200970 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200971 if err != nil {
972 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200973 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200974 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200975 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200976
977 // Retrieve register ticket to register further nodes.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100978 logf("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200979 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
980 if err != nil {
981 ctxC()
982 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
983 }
984 ticket := resT.Ticket
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +0100985 logf("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200986
987 // Retrieve cluster info (for directory and ca public key) to register further
988 // nodes.
989 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
990 if err != nil {
991 ctxC()
992 return nil, fmt.Errorf("GetClusterInfo: %w", err)
993 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200994 caCert, err := x509.ParseCertificate(resI.CaCertificate)
995 if err != nil {
996 ctxC()
997 return nil, fmt.Errorf("ParseCertificate: %w", err)
998 }
999 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +02001000
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001001 // Use the retrieved information to configure the rest of the node options.
1002 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +02001003 nodeOpts[i].NodeParameters = &apb.NodeParameters{
1004 Cluster: &apb.NodeParameters_ClusterRegister_{
1005 ClusterRegister: &apb.NodeParameters_ClusterRegister{
1006 RegisterTicket: ticket,
1007 ClusterDirectory: resI.ClusterDirectory,
1008 CaCertificate: resI.CaCertificate,
1009 Labels: &cpb.NodeLabels{
1010 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +00001011 {Key: NodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +02001012 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001013 },
1014 },
1015 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001016 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001017 }
1018
1019 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001020 for i := 1; i < opts.NumNodes; i++ {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001021 logf("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001022 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001023 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001024 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001025 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001026 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001027
Serge Bazanski53458ba2024-06-18 09:56:46 +00001028 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001029 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001030 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001031 nodeNumberToID := make(map[int]string)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001032 logf("Cluster: waiting for nodes to appear as NEW...")
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001033 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001034 for {
1035 nodes, err := getNodes(ctx, mgmt)
1036 if err != nil {
1037 ctxC()
1038 return nil, fmt.Errorf("could not get nodes: %w", err)
1039 }
1040 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001041 if n.State != cpb.NodeState_NODE_STATE_NEW {
1042 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001043 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001044 if seenNodes[n.Id] {
1045 continue
1046 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001047 seenNodes[n.Id] = true
1048 cluster.Nodes[n.Id] = &NodeInCluster{
1049 ID: n.Id,
1050 Pubkey: n.Pubkey,
1051 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001052
Serge Bazanski20498dd2024-09-30 17:07:08 +00001053 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, NodeNumberKey))
Serge Bazanski53458ba2024-06-18 09:56:46 +00001054 if err != nil {
1055 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1056 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001057 logf("Cluster: Node %d is %s", num, n.Id)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001058 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001059 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001060
1061 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001062 break
1063 }
1064 time.Sleep(1 * time.Second)
1065 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001066 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001067 logf("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001068
Serge Bazanski53458ba2024-06-18 09:56:46 +00001069 // Build the rest of NodeIDs from map.
1070 for i := 1; i < opts.NumNodes; i++ {
1071 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1072 }
1073
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001074 approvedNodes := make(map[string]bool)
1075 upNodes := make(map[string]bool)
1076 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001077 for {
1078 nodes, err := getNodes(ctx, mgmt)
1079 if err != nil {
1080 ctxC()
1081 return nil, fmt.Errorf("could not get nodes: %w", err)
1082 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001083 for _, node := range nodes {
1084 if !seenNodes[node.Id] {
1085 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001086 continue
1087 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001088
1089 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001090 logf("Cluster: node %s is up", node.Id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001091 upNodes[node.Id] = true
1092 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001093 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001094 if upNodes[node.Id] {
1095 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001096 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001097
1098 if !approvedNodes[node.Id] {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001099 logf("Cluster: approving node %s", node.Id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001100 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1101 Pubkey: node.Pubkey,
1102 })
1103 if err != nil {
1104 ctxC()
1105 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1106 }
1107 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001108 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001109 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001110
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001111 logf("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001112 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001113 break
1114 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001115 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001116 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001117 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001118
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001119 logf("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001120 for i, nodeID := range cluster.NodeIDs {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001121 logf("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001122 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001123 logf("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001124
Serge Bazanskibe742842022-04-04 13:18:50 +02001125 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001126}
1127
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001128// RebootNode reboots the cluster member node matching the given index, and
1129// waits for it to rejoin the cluster. It will use the given context ctx to run
1130// cluster API requests, whereas the resulting QEMU process will be created
1131// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1132func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1133 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001134 return fmt.Errorf("index out of bounds")
1135 }
1136 if c.nodeOpts[idx].Runtime == nil {
1137 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001138 }
1139 id := c.NodeIDs[idx]
1140
1141 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001142 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001143 if err != nil {
1144 return err
1145 }
1146 mgmt := apb.NewManagementClient(curC)
1147
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001148 // Cancel the node's context. This will shut down QEMU.
1149 c.nodeOpts[idx].Runtime.CtxC()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001150 logf("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001151 err = <-c.nodesDone[idx]
1152 if err != nil {
1153 return fmt.Errorf("while restarting node: %w", err)
1154 }
1155
1156 // Start QEMU again.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001157 logf("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001158 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 +02001159 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1160 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001161
Serge Bazanskibc969572024-03-21 11:56:13 +01001162 start := time.Now()
1163
1164 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001165 for {
1166 cs, err := getNode(ctx, mgmt, id)
1167 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001168 logf("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001169 return err
1170 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001171 logf("Cluster: node health: %+v", cs.Health)
Serge Bazanskibc969572024-03-21 11:56:13 +01001172
1173 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001174 if lhb.After(start) && cs.Health == apb.Node_HEALTH_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001175 break
1176 }
1177 time.Sleep(time.Second)
1178 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001179 logf("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001180 return nil
1181}
1182
Serge Bazanski500f6e02024-04-03 12:06:40 +02001183// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1184// given by idx. If the node is already shut down, this is a no-op.
1185func (c *Cluster) ShutdownNode(idx int) error {
1186 if idx < 0 || idx >= len(c.NodeIDs) {
1187 return fmt.Errorf("index out of bounds")
1188 }
1189 // Return if node is already stopped.
1190 select {
1191 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1192 return nil
1193 default:
1194 }
1195 id := c.NodeIDs[idx]
1196
1197 // Cancel the node's context. This will shut down QEMU.
1198 c.nodeOpts[idx].Runtime.CtxC()
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001199 logf("Cluster: waiting for node %d (%s) to stop.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001200 err := <-c.nodesDone[idx]
1201 if err != nil {
1202 return fmt.Errorf("while shutting down node: %w", err)
1203 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001204 logf("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001205 return nil
1206}
1207
1208// StartNode performs a power on of the node given by idx. If the node is already
1209// running, this is a no-op.
1210func (c *Cluster) StartNode(idx int) error {
1211 if idx < 0 || idx >= len(c.NodeIDs) {
1212 return fmt.Errorf("index out of bounds")
1213 }
1214 id := c.NodeIDs[idx]
1215 // Return if node is already running.
1216 select {
1217 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1218 default:
1219 return nil
1220 }
1221
1222 // Start QEMU again.
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001223 logf("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001224 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 +02001225 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1226 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001227 logf("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001228 return nil
1229}
1230
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001231// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001232// nodes to stop. It returns an error if stopping the nodes failed, or one of
1233// the nodes failed to fully start in the first place.
1234func (c *Cluster) Close() error {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001235 logf("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001236 if c.authClient != nil {
1237 c.authClient.Close()
1238 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001239 c.ctxC()
1240
Leopold20a036e2023-01-15 00:17:19 +01001241 var errs []error
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001242 logf("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001243 for _, c := range c.nodesDone {
1244 err := <-c
1245 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001246 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001247 }
1248 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001249 logf("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001250 os.RemoveAll(c.launchDir)
1251 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001252 os.RemoveAll(c.metroctlDir)
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001253 logf("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001254 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001255}
Serge Bazanskibe742842022-04-04 13:18:50 +02001256
1257// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1258// their ID. This is performed by connecting to the cluster nanoswitch via its
1259// SOCKS proxy, and using the cluster node list for name resolution.
1260//
1261// For example:
1262//
Tim Windelschmidt9bd9bd42025-02-14 17:08:52 +01001263// grpc.NewClient("passthrough:///metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001264func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1265 host, port, err := net.SplitHostPort(addr)
1266 if err != nil {
1267 return nil, fmt.Errorf("invalid host:port: %w", err)
1268 }
1269 // Already an IP address?
1270 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001271 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001272 }
1273
1274 // Otherwise, expect a node name.
1275 node, ok := c.Nodes[host]
1276 if !ok {
1277 return nil, fmt.Errorf("unknown node %q", host)
1278 }
1279 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001280 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001281}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001282
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001283// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1284// Kubernetes authenticating proxy using the cluster owner identity.
1285// It currently has access to everything (i.e. the cluster-admin role)
1286// via the owner-admin binding.
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001287func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, *rest.Config, error) {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001288 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1289 if err != nil {
1290 // We explicitly pass an Ed25519 private key in, so this can't happen
1291 panic(err)
1292 }
1293
1294 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001295 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001296 Host: host,
1297 TLSClientConfig: rest.TLSClientConfig{
1298 // TODO(q3k): use CA certificate
1299 Insecure: true,
1300 ServerName: "kubernetes.default.svc",
1301 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1302 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1303 },
1304 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1305 return c.DialNode(ctx, address)
1306 },
1307 }
Lorenz Brun8f1254d2025-01-28 14:10:05 +01001308 clientSet, err := kubernetes.NewForConfig(&clientConfig)
1309 if err != nil {
1310 return nil, nil, err
1311 }
1312 return clientSet, &clientConfig, nil
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001313}
1314
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001315// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1316// which are currently Kubernetes controllers, ie. run an apiserver. This list
1317// might be empty if no node is currently configured with the
1318// 'KubernetesController' node.
1319func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1320 curC, err := c.CuratorClient()
1321 if err != nil {
1322 return nil, err
1323 }
1324 mgmt := apb.NewManagementClient(curC)
1325 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1326 Filter: "has(node.roles.kubernetes_controller)",
1327 })
1328 if err != nil {
1329 return nil, err
1330 }
1331 defer srv.CloseSend()
1332 var res []string
1333 for {
1334 n, err := srv.Recv()
1335 if err == io.EOF {
1336 break
1337 }
1338 if err != nil {
1339 return nil, err
1340 }
1341 if n.Status == nil || n.Status.ExternalAddress == "" {
1342 continue
1343 }
1344 res = append(res, n.Status.ExternalAddress)
1345 }
1346 return res, nil
1347}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001348
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001349// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1350// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001351func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1352 // Get an authenticated owner client within the cluster.
1353 curC, err := c.CuratorClient()
1354 if err != nil {
1355 return err
1356 }
1357 mgmt := apb.NewManagementClient(curC)
1358 nodes, err := getNodes(ctx, mgmt)
1359 if err != nil {
1360 return err
1361 }
1362
1363 var unhealthy []string
1364 for _, node := range nodes {
Tim Windelschmidta10d0cb2025-01-13 14:44:15 +01001365 if node.Health == apb.Node_HEALTH_HEALTHY {
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001366 continue
1367 }
1368 unhealthy = append(unhealthy, node.Id)
1369 }
1370 if len(unhealthy) == 0 {
1371 return nil
1372 }
1373 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1374}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001375
1376// ApproveNode approves a node by ID, waiting for it to become UP.
1377func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1378 curC, err := c.CuratorClient()
1379 if err != nil {
1380 return err
1381 }
1382 mgmt := apb.NewManagementClient(curC)
1383
1384 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1385 Pubkey: c.Nodes[id].Pubkey,
1386 })
1387 if err != nil {
1388 return fmt.Errorf("ApproveNode: %w", err)
1389 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001390 logf("Cluster: %s: approved, waiting for UP", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001391 for {
1392 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1393 if err != nil {
1394 return fmt.Errorf("GetNodes: %w", err)
1395 }
1396 found := false
1397 for {
1398 node, err := nodes.Recv()
1399 if errors.Is(err, io.EOF) {
1400 break
1401 }
1402 if err != nil {
1403 return fmt.Errorf("Nodes.Recv: %w", err)
1404 }
1405 if node.Id != id {
1406 continue
1407 }
1408 if node.State != cpb.NodeState_NODE_STATE_UP {
1409 continue
1410 }
1411 found = true
1412 break
1413 }
1414 nodes.CloseSend()
1415
1416 if found {
1417 break
1418 }
1419 time.Sleep(time.Second)
1420 }
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001421 logf("Cluster: %s: UP", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001422 return nil
1423}
1424
1425// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1426func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1427 curC, err := c.CuratorClient()
1428 if err != nil {
1429 return err
1430 }
1431 mgmt := apb.NewManagementClient(curC)
1432
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001433 logf("Cluster: %s: adding KubernetesWorker", id)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001434 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1435 Node: &apb.UpdateNodeRolesRequest_Id{
1436 Id: id,
1437 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001438 KubernetesWorker: ptr.To(true),
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001439 })
1440 return err
1441}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001442
Jan Schära9b060b2024-08-07 10:42:29 +02001443// MakeKubernetesController adds the KubernetesController role to a node by ID.
1444func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1445 curC, err := c.CuratorClient()
1446 if err != nil {
1447 return err
1448 }
1449 mgmt := apb.NewManagementClient(curC)
1450
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001451 logf("Cluster: %s: adding KubernetesController", id)
Jan Schära9b060b2024-08-07 10:42:29 +02001452 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1453 Node: &apb.UpdateNodeRolesRequest_Id{
1454 Id: id,
1455 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001456 KubernetesController: ptr.To(true),
Jan Schära9b060b2024-08-07 10:42:29 +02001457 })
1458 return err
1459}
1460
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001461// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1462func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1463 curC, err := c.CuratorClient()
1464 if err != nil {
1465 return err
1466 }
1467 mgmt := apb.NewManagementClient(curC)
1468 cur := ipb.NewCuratorClient(curC)
1469
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001470 logf("Cluster: %s: adding ConsensusMember", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001471 bo := backoff.NewExponentialBackOff()
1472 bo.MaxElapsedTime = 10 * time.Second
1473
1474 backoff.Retry(func() error {
1475 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1476 Node: &apb.UpdateNodeRolesRequest_Id{
1477 Id: id,
1478 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001479 ConsensusMember: ptr.To(true),
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001480 })
1481 if err != nil {
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001482 logf("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001483 }
1484 return err
1485 }, backoff.WithContext(bo, ctx))
1486 if err != nil {
1487 return err
1488 }
1489
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001490 logf("Cluster: %s: waiting for learner/full members...", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001491
1492 learner := false
1493 for {
1494 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1495 if err != nil {
1496 return fmt.Errorf("GetConsensusStatus: %w", err)
1497 }
1498 for _, member := range res.EtcdMember {
1499 if member.Id != id {
1500 continue
1501 }
1502 switch member.Status {
1503 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1504 if !learner {
1505 learner = true
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001506 logf("Cluster: %s: became a learner, waiting for full member...", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001507 }
1508 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
Tim Windelschmidtd0cdb572025-03-27 17:18:39 +01001509 logf("Cluster: %s: became a full member", id)
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001510 return nil
1511 }
1512 }
1513 time.Sleep(100 * time.Millisecond)
1514 }
1515}