blob: 20c3c67643b4f3f063e1481fa2675197fe965f1f [file] [log] [blame]
Serge Bazanski66e58952021-10-05 17:06:56 +02001// cluster builds on the launch package and implements launching Metropolis
2// nodes and clusters in a virtualized environment using qemu. It's kept in a
3// separate package as it depends on a Metropolis node image, which might not be
4// required for some use of the launch library.
Tim Windelschmidt9f21f532024-05-07 15:14:20 +02005package launch
Serge Bazanski66e58952021-10-05 17:06:56 +02006
7import (
8 "bytes"
9 "context"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010010 "crypto/ed25519"
Serge Bazanski66e58952021-10-05 17:06:56 +020011 "crypto/rand"
12 "crypto/tls"
Serge Bazanski54e212a2023-06-14 13:45:11 +020013 "crypto/x509"
Serge Bazanskia0bc6d32023-06-28 18:57:40 +020014 "encoding/pem"
Serge Bazanski66e58952021-10-05 17:06:56 +020015 "errors"
16 "fmt"
17 "io"
Serge Bazanski66e58952021-10-05 17:06:56 +020018 "net"
Lorenz Brun150f24a2023-07-13 20:11:06 +020019 "net/http"
Serge Bazanski66e58952021-10-05 17:06:56 +020020 "os"
21 "os/exec"
Leopoldacfad5b2023-01-15 14:05:25 +010022 "path"
Serge Bazanski66e58952021-10-05 17:06:56 +020023 "path/filepath"
Serge Bazanski53458ba2024-06-18 09:56:46 +000024 "strconv"
Serge Bazanski630fb5c2023-04-06 10:50:24 +020025 "strings"
Serge Bazanski66e58952021-10-05 17:06:56 +020026 "syscall"
27 "time"
28
29 "github.com/cenkalti/backoff/v4"
Serge Bazanski66e58952021-10-05 17:06:56 +020030 "go.uber.org/multierr"
Serge Bazanskibe742842022-04-04 13:18:50 +020031 "golang.org/x/net/proxy"
Lorenz Brun87bbf7e2024-03-18 18:22:25 +010032 "golang.org/x/sys/unix"
Serge Bazanski66e58952021-10-05 17:06:56 +020033 "google.golang.org/grpc"
Serge Bazanski636032e2022-01-26 14:21:33 +010034 "google.golang.org/grpc/codes"
35 "google.golang.org/grpc/status"
Serge Bazanski66e58952021-10-05 17:06:56 +020036 "google.golang.org/protobuf/proto"
Serge Bazanskia0bc6d32023-06-28 18:57:40 +020037 "k8s.io/client-go/kubernetes"
38 "k8s.io/client-go/rest"
Jan Schärd1a8b642024-12-03 17:40:41 +010039 "k8s.io/utils/ptr"
Serge Bazanski66e58952021-10-05 17:06:56 +020040
Serge Bazanski37cfcc12024-03-21 11:59:07 +010041 ipb "source.monogon.dev/metropolis/node/core/curator/proto/api"
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +020042 apb "source.monogon.dev/metropolis/proto/api"
43 cpb "source.monogon.dev/metropolis/proto/common"
44
Serge Bazanskica8d9512024-09-12 14:20:57 +020045 "source.monogon.dev/go/logging"
Serge Bazanskidd5b03c2024-05-16 18:07:06 +020046 "source.monogon.dev/go/qcow2"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010047 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski66e58952021-10-05 17:06:56 +020048 "source.monogon.dev/metropolis/node"
49 "source.monogon.dev/metropolis/node/core/rpc"
Serge Bazanski5bb8a332022-06-23 17:41:33 +020050 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020051 "source.monogon.dev/metropolis/test/localregistry"
52 "source.monogon.dev/osbase/test/launch"
Serge Bazanski66e58952021-10-05 17:06:56 +020053)
54
Serge Bazanski53458ba2024-06-18 09:56:46 +000055const (
Serge Bazanski20498dd2024-09-30 17:07:08 +000056 // NodeNumberKey is the key of the node label used to carry a node's numerical
Serge Bazanski53458ba2024-06-18 09:56:46 +000057 // index in the test system.
Serge Bazanski20498dd2024-09-30 17:07:08 +000058 NodeNumberKey string = "test-node-number"
Serge Bazanski53458ba2024-06-18 09:56:46 +000059)
60
Leopold20a036e2023-01-15 00:17:19 +010061// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020062type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010063 // Name is a human-readable identifier to be used in debug output.
64 Name string
65
Jan Schära9b060b2024-08-07 10:42:29 +020066 // CPUs is the number of virtual CPUs of the VM.
67 CPUs int
68
69 // ThreadsPerCPU is the number of threads per CPU. This is multiplied by
70 // CPUs to get the total number of threads.
71 ThreadsPerCPU int
72
73 // MemoryMiB is the RAM size in MiB of the VM.
74 MemoryMiB int
75
Jan Schär07003572024-08-26 10:42:16 +020076 // DiskBytes contains the size of the root disk in bytes or zero if the
77 // unmodified image size is used.
78 DiskBytes uint64
79
Serge Bazanski66e58952021-10-05 17:06:56 +020080 // Ports contains the port mapping where to expose the internal ports of the VM to
81 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
82 // ConnectToSocket is set.
83 Ports launch.PortMap
84
Leopold20a036e2023-01-15 00:17:19 +010085 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
86 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020087 // want to test reboot behavior this should be false.
88 AllowReboot bool
89
Leopold20a036e2023-01-15 00:17:19 +010090 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
91 // set, it is instead connected to the given file descriptor/socket. If this is
92 // set, all port maps from the Ports option are ignored. Intended for networking
93 // this instance together with others for running more complex network
94 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020095 ConnectToSocket *os.File
96
Leopoldacfad5b2023-01-15 14:05:25 +010097 // When PcapDump is set, all traffic is dumped to a pcap file in the
98 // runtime directory (e.g. "net0.pcap" for the first interface).
99 PcapDump bool
100
Leopold20a036e2023-01-15 00:17:19 +0100101 // SerialPort is an io.ReadWriter over which you can communicate with the serial
102 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +0200103 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
104 SerialPort io.ReadWriter
105
106 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
107 // registering into a cluster.
108 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200109
110 // Mac is the node's MAC address.
111 Mac *net.HardwareAddr
112
113 // Runtime keeps the node's QEMU runtime state.
114 Runtime *NodeRuntime
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200115
116 // RunVNC starts a VNC socket for troubleshooting/testing console code. Note:
117 // this will not work in tests, as those use a built-in qemu which does not
118 // implement a VGA device.
119 RunVNC bool
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200120}
121
Leopold20a036e2023-01-15 00:17:19 +0100122// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200123type NodeRuntime struct {
124 // ld points at the node's launch directory storing data such as storage
125 // images, firmware variables or the TPM state.
126 ld string
127 // sd points at the node's socket directory.
128 sd string
129
130 // ctxT is the context QEMU will execute in.
131 ctxT context.Context
132 // CtxC is the QEMU context's cancellation function.
133 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200134}
135
136// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200137var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200138 node.ConsensusPort,
139
140 node.CuratorServicePort,
141 node.DebugServicePort,
142
143 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100144 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200145 node.CuratorServicePort,
146 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200147 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200148}
149
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200150// setupRuntime creates the node's QEMU runtime directory, together with all
151// files required to preserve its state, a level below the chosen path ld. The
152// node's socket directory is similarily created a level below sd. It may
153// return an I/O error.
Jan Schär07003572024-08-26 10:42:16 +0200154func setupRuntime(ld, sd string, diskBytes uint64) (*NodeRuntime, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200155 // Create a temporary directory to keep all the runtime files.
156 stdp, err := os.MkdirTemp(ld, "node_state*")
157 if err != nil {
158 return nil, fmt.Errorf("failed to create the state directory: %w", err)
159 }
160
161 // Initialize the node's storage with a prebuilt image.
Jan Schär07003572024-08-26 10:42:16 +0200162 st, err := os.Stat(xNodeImagePath)
163 if err != nil {
164 return nil, fmt.Errorf("cannot read image file: %w", err)
165 }
166 diskBytes = max(diskBytes, uint64(st.Size()))
167
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200168 di := filepath.Join(stdp, "image.qcow2")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000169 launch.Log("Cluster: generating node QCOW2 snapshot image: %s -> %s", xNodeImagePath, di)
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200170
171 df, err := os.Create(di)
172 if err != nil {
173 return nil, fmt.Errorf("while opening image for writing: %w", err)
174 }
175 defer df.Close()
Jan Schär07003572024-08-26 10:42:16 +0200176 if err := qcow2.Generate(df, qcow2.GenerateWithBackingFile(xNodeImagePath), qcow2.GenerateWithFileSize(diskBytes)); err != nil {
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200177 return nil, fmt.Errorf("while creating copy-on-write node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200178 }
179
180 // Initialize the OVMF firmware variables file.
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000181 dv := filepath.Join(stdp, filepath.Base(xOvmfVarsPath))
182 if err := copyFile(xOvmfVarsPath, dv); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200183 return nil, fmt.Errorf("while copying firmware variables: %w", err)
184 }
185
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200186 // Create the socket directory.
187 sotdp, err := os.MkdirTemp(sd, "node_sock*")
188 if err != nil {
189 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
190 }
191
192 return &NodeRuntime{
193 ld: stdp,
194 sd: sotdp,
195 }, nil
196}
197
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200198// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200199// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200200func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200201 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200202 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanskica8d9512024-09-12 14:20:57 +0200203 r := resolver.New(c.ctxT, resolver.WithLogger(logging.NewFunctionBackend(func(severity logging.Severity, msg string) {
204 launch.Log("Cluster: client resolver: %s: %s", severity, msg)
205 })))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200206 for _, n := range c.NodeIDs {
207 ep, err := resolver.NodeWithDefaultPort(n)
208 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200209 return nil, fmt.Errorf("could not add node %q by DNS: %w", n, err)
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200210 }
211 r.AddEndpoint(ep)
212 }
213 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
214 grpc.WithTransportCredentials(authCreds),
215 grpc.WithResolvers(r),
216 grpc.WithContextDialer(c.DialNode),
217 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200218 if err != nil {
219 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
220 }
221 c.authClient = authClient
222 }
223 return c.authClient, nil
224}
225
Serge Bazanski66e58952021-10-05 17:06:56 +0200226// LaunchNode launches a single Metropolis node instance with the given options.
227// The instance runs mostly paravirtualized but with some emulated hardware
228// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200229// writable, and the changes are kept across reboots and shutdowns. ld and sd
230// point to the launch directory and the socket directory, holding the nodes'
231// state files (storage, tpm state, firmware state), and UNIX socket files
232// (swtpm <-> QEMU interplay) respectively. The directories must exist before
233// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
234// if either are not initialized.
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200235func LaunchNode(ctx context.Context, ld, sd string, tpmFactory *TPMFactory, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200236 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
237 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200238 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
239 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
240 // that we open and pass the name of it to QEMU. Not pinning this crashes both
241 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
242 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200243
Jan Schära9b060b2024-08-07 10:42:29 +0200244 if options.CPUs == 0 {
245 options.CPUs = 1
246 }
247 if options.ThreadsPerCPU == 0 {
248 options.ThreadsPerCPU = 1
249 }
250 if options.MemoryMiB == 0 {
251 options.MemoryMiB = 2048
252 }
253
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200254 // If it's the node's first start, set up its runtime directories.
255 if options.Runtime == nil {
Jan Schär07003572024-08-26 10:42:16 +0200256 r, err := setupRuntime(ld, sd, options.DiskBytes)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200257 if err != nil {
258 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200259 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200260 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200261 }
262
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200263 // Replace the node's context with a new one.
264 r := options.Runtime
265 if r.CtxC != nil {
266 r.CtxC()
267 }
268 r.ctxT, r.CtxC = context.WithCancel(ctx)
269
Serge Bazanski66e58952021-10-05 17:06:56 +0200270 var qemuNetType string
271 var qemuNetConfig launch.QemuValue
272 if options.ConnectToSocket != nil {
273 qemuNetType = "socket"
274 qemuNetConfig = launch.QemuValue{
275 "id": {"net0"},
276 "fd": {"3"},
277 }
278 } else {
279 qemuNetType = "user"
280 qemuNetConfig = launch.QemuValue{
281 "id": {"net0"},
282 "net": {"10.42.0.0/24"},
283 "dhcpstart": {"10.42.0.10"},
284 "hostfwd": options.Ports.ToQemuForwards(),
285 }
286 }
287
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200288 // Generate the node's MAC address if it isn't already set in NodeOptions.
289 if options.Mac == nil {
290 mac, err := generateRandomEthernetMAC()
291 if err != nil {
292 return err
293 }
294 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200295 }
296
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200297 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
298 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200299 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200300 qemuArgs := []string{
Jan Schära9b060b2024-08-07 10:42:29 +0200301 "-machine", "q35",
302 "-accel", "kvm",
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200303 "-display", "none",
Jan Schära9b060b2024-08-07 10:42:29 +0200304 "-nodefaults",
305 "-cpu", "host",
306 "-m", fmt.Sprintf("%dM", options.MemoryMiB),
307 "-smp", fmt.Sprintf("cores=%d,threads=%d", options.CPUs, options.ThreadsPerCPU),
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000308 "-drive", "if=pflash,format=raw,readonly=on,file=" + xOvmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200309 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200310 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200311 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200312 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200313 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
314 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
315 "-device", "tpm-tis,tpmdev=tpm0",
316 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200317 "-serial", "stdio",
318 }
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200319 if options.RunVNC {
320 vncSocketPath := filepath.Join(r.sd, "vnc-socket")
321 qemuArgs = append(qemuArgs,
322 "-vnc", "unix:"+vncSocketPath,
323 "-device", "virtio-vga",
324 )
325 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200326
327 if !options.AllowReboot {
328 qemuArgs = append(qemuArgs, "-no-reboot")
329 }
330
331 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200332 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200333 parametersRaw, err := proto.Marshal(options.NodeParameters)
334 if err != nil {
335 return fmt.Errorf("failed to encode node paraeters: %w", err)
336 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200337 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200338 return fmt.Errorf("failed to write node parameters: %w", err)
339 }
340 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
341 }
342
Leopoldacfad5b2023-01-15 14:05:25 +0100343 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200344 qemuNetDump := launch.QemuValue{
345 "id": {"net0"},
346 "netdev": {"net0"},
347 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100348 }
349 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
350 }
351
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200352 // Manufacture TPM if needed.
353 tpmd := filepath.Join(r.ld, "tpm")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000354 err := tpmFactory.Manufacture(ctx, tpmd, &TPMPlatform{
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200355 Manufacturer: "Monogon",
356 Version: "1.0",
357 Model: "TestCluster",
358 })
359 if err != nil {
360 return fmt.Errorf("could not manufacture TPM: %w", err)
361 }
362
Serge Bazanski66e58952021-10-05 17:06:56 +0200363 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200364 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200365
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000366 tpmEmuCmd := exec.CommandContext(tpmCtx, xSwtpmPath, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000367 // Silence warnings from unsafe libtpms build (uses non-constant-time
368 // cryptographic operations).
369 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200370 tpmEmuCmd.Stderr = os.Stderr
371 tpmEmuCmd.Stdout = os.Stdout
372
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100373 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200374 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200375 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200376 return fmt.Errorf("failed to start TPM emulator: %w", err)
377 }
378
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200379 // Wait for the socket to be created by the TPM emulator before launching
380 // QEMU.
381 for {
382 _, err := os.Stat(tpmSocketPath)
383 if err == nil {
384 break
385 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200386 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200387 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200388 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
389 }
390 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200391 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200392 return fmt.Errorf("while waiting for the TPM socket: %w", err)
393 }
394 time.Sleep(time.Millisecond * 100)
395 }
396
Serge Bazanski66e58952021-10-05 17:06:56 +0200397 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200398 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200399 if options.ConnectToSocket != nil {
400 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
401 }
402
403 var stdErrBuf bytes.Buffer
404 systemCmd.Stderr = &stdErrBuf
405 systemCmd.Stdout = options.SerialPort
406
Leopoldaf5086b2023-01-15 14:12:42 +0100407 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
408
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200409 go func() {
410 launch.Log("Node: Starting...")
411 err = systemCmd.Run()
412 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200413
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200414 // Stop TPM emulator and wait for it to exit to properly reap the child process
415 tpmCancel()
416 launch.Log("Node: Waiting for TPM emulator to exit")
417 // Wait returns a SIGKILL error because we just cancelled its context.
418 // We still need to call it to avoid creating zombies.
419 errTpm := tpmEmuCmd.Wait()
420 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200421
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200422 var exerr *exec.ExitError
423 if err != nil && errors.As(err, &exerr) {
424 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
425 if status.Signaled() && status.Signal() == syscall.SIGKILL {
426 // Process was killed externally (most likely by our context being canceled).
427 // This is a normal exit for us, so return nil
428 doneC <- nil
429 return
430 }
431 exerr.Stderr = stdErrBuf.Bytes()
432 newErr := launch.QEMUError(*exerr)
433 launch.Log("Node: %q", stdErrBuf.String())
434 doneC <- &newErr
435 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200436 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200437 doneC <- err
438 }()
439 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200440}
441
442func copyFile(src, dst string) error {
443 in, err := os.Open(src)
444 if err != nil {
445 return fmt.Errorf("when opening source: %w", err)
446 }
447 defer in.Close()
448
449 out, err := os.Create(dst)
450 if err != nil {
451 return fmt.Errorf("when creating destination: %w", err)
452 }
453 defer out.Close()
454
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100455 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200456 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100457 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200458 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100459
460 // Copy the file while preserving its sparseness. The image files are very
461 // sparse (less than 10% allocated), so this is a lot faster.
462 var lastHoleStart int64
463 for {
464 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
465 if err != nil {
466 return fmt.Errorf("when seeking to next data block: %w", err)
467 }
468 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
469 if err != nil {
470 return fmt.Errorf("when seeking to next hole: %w", err)
471 }
472 lastHoleStart = holeStart
473 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
474 return fmt.Errorf("when seeking to current data block: %w", err)
475 }
476 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
477 return fmt.Errorf("when seeking output to next data block: %w", err)
478 }
479 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
480 return fmt.Errorf("when copying file: %w", err)
481 }
482 if endPos == holeStart {
483 // The next hole is at the end of the file, we're done here.
484 break
485 }
486 }
487
Serge Bazanski66e58952021-10-05 17:06:56 +0200488 return out.Close()
489}
490
Serge Bazanskie78a0892021-10-07 17:03:49 +0200491// getNodes wraps around Management.GetNodes to return a list of nodes in a
492// cluster.
493func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200494 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100495 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100496 err := backoff.Retry(func() error {
497 res = nil
498 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200499 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100500 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200501 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100502 for {
503 node, err := srvN.Recv()
504 if err == io.EOF {
505 break
506 }
507 if err != nil {
508 return fmt.Errorf("GetNodes.Recv: %w", err)
509 }
510 res = append(res, node)
511 }
512 return nil
513 }, bo)
514 if err != nil {
515 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200516 }
517 return res, nil
518}
519
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200520// getNode wraps Management.GetNodes. It returns node information matching
521// given node ID.
522func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
523 nodes, err := getNodes(ctx, mgmt)
524 if err != nil {
525 return nil, fmt.Errorf("could not get nodes: %w", err)
526 }
527 for _, n := range nodes {
Jan Schär39d9c242024-09-24 13:49:55 +0200528 if n.Id == id {
529 return n, nil
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200530 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200531 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200532 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200533}
534
Serge Bazanski66e58952021-10-05 17:06:56 +0200535// Gets a random EUI-48 Ethernet MAC address
536func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
537 macBuf := make([]byte, 6)
538 _, err := rand.Read(macBuf)
539 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200540 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200541 }
542
543 // Set U/L bit and clear I/G bit (locally administered individual MAC)
544 // Ref IEEE 802-2014 Section 8.2.2
545 macBuf[0] = (macBuf[0] | 2) & 0xfe
546 mac := net.HardwareAddr(macBuf)
547 return &mac, nil
548}
549
Serge Bazanskibe742842022-04-04 13:18:50 +0200550const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200551
Serge Bazanskibe742842022-04-04 13:18:50 +0200552// ClusterPorts contains all ports handled by Nanoswitch.
553var ClusterPorts = []uint16{
554 // Forwarded to the first node.
555 uint16(node.CuratorServicePort),
556 uint16(node.DebugServicePort),
557 uint16(node.KubernetesAPIPort),
558 uint16(node.KubernetesAPIWrappedPort),
559
560 // SOCKS proxy to the switch network
561 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200562}
563
564// ClusterOptions contains all options for launching a Metropolis cluster.
565type ClusterOptions struct {
566 // The number of nodes this cluster should be started with.
567 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100568
Jan Schära9b060b2024-08-07 10:42:29 +0200569 // Node are default options of all nodes.
570 Node NodeOptions
571
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100572 // If true, node logs will be saved to individual files instead of being printed
573 // out to stderr. The path of these files will be still printed to stdout.
574 //
575 // The files will be located within the launch directory inside TEST_TMPDIR (or
576 // the default tempdir location, if not set).
577 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200578
579 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
580 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
581 // incomplete.
582 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200583
584 // Optional local registry which will be made available to the cluster to
585 // pull images from. This is a more efficient alternative to preseeding all
586 // images used for testing.
587 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200588
589 // InitialClusterConfiguration will be passed to the first node when creating the
590 // cluster, and defines some basic properties of the cluster. If not specified,
591 // the cluster will default to defaults as defined in
592 // metropolis.proto.api.NodeParameters.
593 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200594}
595
596// Cluster is the running Metropolis cluster launched using the LaunchCluster
597// function.
598type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200599 // Owner is the TLS Certificate of the owner of the test cluster. This can be
600 // used to authenticate further clients to the running cluster.
601 Owner tls.Certificate
602 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200603 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200604 Ports launch.PortMap
605
Serge Bazanskibe742842022-04-04 13:18:50 +0200606 // Nodes is a map from Node ID to its runtime information.
607 Nodes map[string]*NodeInCluster
608 // NodeIDs is a list of node IDs that are backing this cluster, in order of
609 // creation.
610 NodeIDs []string
611
Serge Bazanski54e212a2023-06-14 13:45:11 +0200612 // CACertificate is the cluster's CA certificate.
613 CACertificate *x509.Certificate
614
Serge Bazanski66e58952021-10-05 17:06:56 +0200615 // nodesDone is a list of channels populated with the return codes from all the
616 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100617 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200618 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200619 // nodeOpts are the cluster member nodes' mutable launch options, kept here
620 // to facilitate reboots.
621 nodeOpts []NodeOptions
622 // launchDir points at the directory keeping the nodes' state, such as storage
623 // images, firmware variable files, TPM state.
624 launchDir string
625 // socketDir points at the directory keeping UNIX socket files, such as these
626 // used to facilitate communication between QEMU and swtpm. It's different
627 // from launchDir, and anchored nearer the file system root, due to the
628 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100629 socketDir string
630 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200631
Lorenz Brun276a7462023-07-12 21:28:54 +0200632 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200633 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200634 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200635
636 // authClient is a cached authenticated owner connection to a Curator
637 // instance within the cluster.
638 authClient *grpc.ClientConn
639
640 // ctxT is the context individual node contexts are created from.
641 ctxT context.Context
642 // ctxC is used by Close to cancel the context under which the nodes are
643 // running.
644 ctxC context.CancelFunc
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200645
646 tpmFactory *TPMFactory
Serge Bazanskibe742842022-04-04 13:18:50 +0200647}
648
649// NodeInCluster represents information about a node that's part of a Cluster.
650type NodeInCluster struct {
651 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200652 ID string
653 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200654 // Address of the node on the network ran by nanoswitch. Not reachable from the
655 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
656 // on Cluster.Ports[SOCKSPort]).
657 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 }
677 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
678 if err != nil {
679 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
680 }
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())
Serge Bazanskibe742842022-04-04 13:18:50 +0200705 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
706 if err != nil {
707 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
708 }
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//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001258// grpc.Dial("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}