blob: b46cc68ffaa6ff9ee620a074f03404556c7d90af [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 {
Jan Schära9b060b2024-08-07 10:42:29 +0200825 for i := range opts.NumNodes {
826 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i))
827 port, err := NewSerialFileLogger(path)
828 if err != nil {
829 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
830 }
831 launch.Log("Node %d logs at %s", i, path)
832 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100833 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100834 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200835
836 // Start the first node.
837 ctxT, ctxC := context.WithCancel(ctx)
Jan Schär0b927652024-07-31 18:08:50 +0200838 launch.Log("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200839 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200840 ctxC()
841 return nil, fmt.Errorf("failed to launch first node: %w", err)
842 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200843
Lorenz Brun150f24a2023-07-13 20:11:06 +0200844 localRegistryAddr := net.TCPAddr{
845 IP: net.IPv4(10, 42, 0, 82),
846 Port: 5000,
847 }
848
849 var guestSvcMap launch.GuestServiceMap
850 if opts.LocalRegistry != nil {
851 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
852 if err != nil {
853 ctxC()
854 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
855 }
856 s := http.Server{
857 Handler: opts.LocalRegistry,
858 }
859 go s.Serve(l)
860 go func() {
861 <-ctxT.Done()
862 s.Close()
863 }()
864 guestSvcMap = launch.GuestServiceMap{
865 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
866 }
867 }
868
Serge Bazanskie78a0892021-10-07 17:03:49 +0200869 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200870 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
871 if err != nil {
872 ctxC()
873 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
874 }
875
876 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100877 var serialPort io.ReadWriter
878 if opts.NodeLogsToFiles {
879 path := path.Join(ld, "nanoswitch.txt")
880 serialPort, err = NewSerialFileLogger(path)
881 if err != nil {
882 launch.Log("Could not open log file for nanoswitch: %v", err)
883 }
884 launch.Log("Nanoswitch logs at %s", path)
885 } else {
886 serialPort = newPrefixedStdio(99)
887 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200888 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100889 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000890 KernelPath: xKernelPath,
891 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200892 ExtraNetworkInterfaces: switchPorts,
893 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200894 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100895 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100896 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200897 }); err != nil {
898 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100899 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200900 }
901 }
902 }()
903
Serge Bazanskibe742842022-04-04 13:18:50 +0200904 // Build SOCKS dialer.
905 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
906 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200907 if err != nil {
908 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200909 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200910 }
911
Serge Bazanskibe742842022-04-04 13:18:50 +0200912 // Retrieve owner credentials and first node.
913 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200914 if err != nil {
915 ctxC()
916 return nil, err
917 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200918
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100919 // Write credentials to the metroctl directory.
920 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
921 ctxC()
922 return nil, fmt.Errorf("could not write owner key: %w", err)
923 }
924 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
925 ctxC()
926 return nil, fmt.Errorf("could not write owner certificate: %w", err)
927 }
928
Serge Bazanski53458ba2024-06-18 09:56:46 +0000929 launch.Log("Cluster: Node %d is %s", 0, firstNode.ID)
930
931 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200932 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200933 cluster := &Cluster{
934 Owner: *cert,
935 Ports: portMap,
936 Nodes: map[string]*NodeInCluster{
937 firstNode.ID: firstNode,
938 },
939 NodeIDs: []string{
940 firstNode.ID,
941 },
942
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100943 nodesDone: done,
944 nodeOpts: nodeOpts,
945 launchDir: ld,
946 socketDir: sd,
947 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200948
Lorenz Brun276a7462023-07-12 21:28:54 +0200949 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200950
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200951 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200952 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200953
954 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +0200955 }
956
957 // Now start the rest of the nodes and register them into the cluster.
958
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200959 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200960 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200961 if err != nil {
962 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200963 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200964 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200965 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200966
967 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100968 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200969 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
970 if err != nil {
971 ctxC()
972 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
973 }
974 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100975 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200976
977 // Retrieve cluster info (for directory and ca public key) to register further
978 // nodes.
979 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
980 if err != nil {
981 ctxC()
982 return nil, fmt.Errorf("GetClusterInfo: %w", err)
983 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200984 caCert, err := x509.ParseCertificate(resI.CaCertificate)
985 if err != nil {
986 ctxC()
987 return nil, fmt.Errorf("ParseCertificate: %w", err)
988 }
989 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200990
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200991 // Use the retrieved information to configure the rest of the node options.
992 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +0200993 nodeOpts[i].NodeParameters = &apb.NodeParameters{
994 Cluster: &apb.NodeParameters_ClusterRegister_{
995 ClusterRegister: &apb.NodeParameters_ClusterRegister{
996 RegisterTicket: ticket,
997 ClusterDirectory: resI.ClusterDirectory,
998 CaCertificate: resI.CaCertificate,
999 Labels: &cpb.NodeLabels{
1000 Pairs: []*cpb.NodeLabels_Pair{
Serge Bazanski20498dd2024-09-30 17:07:08 +00001001 {Key: NodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +02001002 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001003 },
1004 },
1005 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001006 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001007 }
1008
1009 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001010 for i := 1; i < opts.NumNodes; i++ {
Jan Schär0b927652024-07-31 18:08:50 +02001011 launch.Log("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001012 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001013 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001014 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001015 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001016 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001017
Serge Bazanski53458ba2024-06-18 09:56:46 +00001018 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001019 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001020 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001021 nodeNumberToID := make(map[int]string)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001022 launch.Log("Cluster: waiting for nodes to appear as NEW...")
1023 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001024 for {
1025 nodes, err := getNodes(ctx, mgmt)
1026 if err != nil {
1027 ctxC()
1028 return nil, fmt.Errorf("could not get nodes: %w", err)
1029 }
1030 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001031 if n.State != cpb.NodeState_NODE_STATE_NEW {
1032 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001033 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001034 if seenNodes[n.Id] {
1035 continue
1036 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001037 seenNodes[n.Id] = true
1038 cluster.Nodes[n.Id] = &NodeInCluster{
1039 ID: n.Id,
1040 Pubkey: n.Pubkey,
1041 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001042
Serge Bazanski20498dd2024-09-30 17:07:08 +00001043 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, NodeNumberKey))
Serge Bazanski53458ba2024-06-18 09:56:46 +00001044 if err != nil {
1045 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1046 }
1047 launch.Log("Cluster: Node %d is %s", num, n.Id)
1048 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001049 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001050
1051 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001052 break
1053 }
1054 time.Sleep(1 * time.Second)
1055 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001056 }
1057 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001058
Serge Bazanski53458ba2024-06-18 09:56:46 +00001059 // Build the rest of NodeIDs from map.
1060 for i := 1; i < opts.NumNodes; i++ {
1061 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1062 }
1063
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001064 approvedNodes := make(map[string]bool)
1065 upNodes := make(map[string]bool)
1066 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001067 for {
1068 nodes, err := getNodes(ctx, mgmt)
1069 if err != nil {
1070 ctxC()
1071 return nil, fmt.Errorf("could not get nodes: %w", err)
1072 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001073 for _, node := range nodes {
1074 if !seenNodes[node.Id] {
1075 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001076 continue
1077 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001078
1079 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1080 launch.Log("Cluster: node %s is up", node.Id)
1081 upNodes[node.Id] = true
1082 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001083 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001084 if upNodes[node.Id] {
1085 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001086 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001087
1088 if !approvedNodes[node.Id] {
1089 launch.Log("Cluster: approving node %s", node.Id)
1090 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1091 Pubkey: node.Pubkey,
1092 })
1093 if err != nil {
1094 ctxC()
1095 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1096 }
1097 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001098 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001099 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001100
Jan Schär0b927652024-07-31 18:08:50 +02001101 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001102 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001103 break
1104 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001105 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001106 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001107 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001108
Serge Bazanski05f813b2023-03-16 17:58:39 +01001109 launch.Log("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001110 for i, nodeID := range cluster.NodeIDs {
1111 launch.Log("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001112 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001113 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001114
Serge Bazanskibe742842022-04-04 13:18:50 +02001115 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001116}
1117
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001118// RebootNode reboots the cluster member node matching the given index, and
1119// waits for it to rejoin the cluster. It will use the given context ctx to run
1120// cluster API requests, whereas the resulting QEMU process will be created
1121// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1122func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1123 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001124 return fmt.Errorf("index out of bounds")
1125 }
1126 if c.nodeOpts[idx].Runtime == nil {
1127 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001128 }
1129 id := c.NodeIDs[idx]
1130
1131 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001132 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001133 if err != nil {
1134 return err
1135 }
1136 mgmt := apb.NewManagementClient(curC)
1137
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001138 // Cancel the node's context. This will shut down QEMU.
1139 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001140 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001141 err = <-c.nodesDone[idx]
1142 if err != nil {
1143 return fmt.Errorf("while restarting node: %w", err)
1144 }
1145
1146 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001147 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001148 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 +02001149 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1150 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001151
Serge Bazanskibc969572024-03-21 11:56:13 +01001152 start := time.Now()
1153
1154 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001155 for {
1156 cs, err := getNode(ctx, mgmt, id)
1157 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001158 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001159 return err
1160 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001161 launch.Log("Cluster: node health: %+v", cs.Health)
1162
1163 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1164 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001165 break
1166 }
1167 time.Sleep(time.Second)
1168 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001169 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001170 return nil
1171}
1172
Serge Bazanski500f6e02024-04-03 12:06:40 +02001173// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1174// given by idx. If the node is already shut down, this is a no-op.
1175func (c *Cluster) ShutdownNode(idx int) error {
1176 if idx < 0 || idx >= len(c.NodeIDs) {
1177 return fmt.Errorf("index out of bounds")
1178 }
1179 // Return if node is already stopped.
1180 select {
1181 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1182 return nil
1183 default:
1184 }
1185 id := c.NodeIDs[idx]
1186
1187 // Cancel the node's context. This will shut down QEMU.
1188 c.nodeOpts[idx].Runtime.CtxC()
1189 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1190 err := <-c.nodesDone[idx]
1191 if err != nil {
1192 return fmt.Errorf("while shutting down node: %w", err)
1193 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001194 launch.Log("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001195 return nil
1196}
1197
1198// StartNode performs a power on of the node given by idx. If the node is already
1199// running, this is a no-op.
1200func (c *Cluster) StartNode(idx int) error {
1201 if idx < 0 || idx >= len(c.NodeIDs) {
1202 return fmt.Errorf("index out of bounds")
1203 }
1204 id := c.NodeIDs[idx]
1205 // Return if node is already running.
1206 select {
1207 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1208 default:
1209 return nil
1210 }
1211
1212 // Start QEMU again.
1213 launch.Log("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001214 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 +02001215 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1216 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001217 launch.Log("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001218 return nil
1219}
1220
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001221// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001222// nodes to stop. It returns an error if stopping the nodes failed, or one of
1223// the nodes failed to fully start in the first place.
1224func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001225 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001226 if c.authClient != nil {
1227 c.authClient.Close()
1228 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001229 c.ctxC()
1230
Leopold20a036e2023-01-15 00:17:19 +01001231 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001232 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001233 for _, c := range c.nodesDone {
1234 err := <-c
1235 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001236 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001237 }
1238 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001239 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001240 os.RemoveAll(c.launchDir)
1241 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001242 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001243 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001244 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001245}
Serge Bazanskibe742842022-04-04 13:18:50 +02001246
1247// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1248// their ID. This is performed by connecting to the cluster nanoswitch via its
1249// SOCKS proxy, and using the cluster node list for name resolution.
1250//
1251// For example:
1252//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001253// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001254func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1255 host, port, err := net.SplitHostPort(addr)
1256 if err != nil {
1257 return nil, fmt.Errorf("invalid host:port: %w", err)
1258 }
1259 // Already an IP address?
1260 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001261 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001262 }
1263
1264 // Otherwise, expect a node name.
1265 node, ok := c.Nodes[host]
1266 if !ok {
1267 return nil, fmt.Errorf("unknown node %q", host)
1268 }
1269 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001270 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001271}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001272
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001273// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1274// Kubernetes authenticating proxy using the cluster owner identity.
1275// It currently has access to everything (i.e. the cluster-admin role)
1276// via the owner-admin binding.
1277func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1278 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1279 if err != nil {
1280 // We explicitly pass an Ed25519 private key in, so this can't happen
1281 panic(err)
1282 }
1283
1284 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001285 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001286 Host: host,
1287 TLSClientConfig: rest.TLSClientConfig{
1288 // TODO(q3k): use CA certificate
1289 Insecure: true,
1290 ServerName: "kubernetes.default.svc",
1291 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1292 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1293 },
1294 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1295 return c.DialNode(ctx, address)
1296 },
1297 }
1298 return kubernetes.NewForConfig(&clientConfig)
1299}
1300
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001301// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1302// which are currently Kubernetes controllers, ie. run an apiserver. This list
1303// might be empty if no node is currently configured with the
1304// 'KubernetesController' node.
1305func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1306 curC, err := c.CuratorClient()
1307 if err != nil {
1308 return nil, err
1309 }
1310 mgmt := apb.NewManagementClient(curC)
1311 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1312 Filter: "has(node.roles.kubernetes_controller)",
1313 })
1314 if err != nil {
1315 return nil, err
1316 }
1317 defer srv.CloseSend()
1318 var res []string
1319 for {
1320 n, err := srv.Recv()
1321 if err == io.EOF {
1322 break
1323 }
1324 if err != nil {
1325 return nil, err
1326 }
1327 if n.Status == nil || n.Status.ExternalAddress == "" {
1328 continue
1329 }
1330 res = append(res, n.Status.ExternalAddress)
1331 }
1332 return res, nil
1333}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001334
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001335// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1336// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001337func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1338 // Get an authenticated owner client within the cluster.
1339 curC, err := c.CuratorClient()
1340 if err != nil {
1341 return err
1342 }
1343 mgmt := apb.NewManagementClient(curC)
1344 nodes, err := getNodes(ctx, mgmt)
1345 if err != nil {
1346 return err
1347 }
1348
1349 var unhealthy []string
1350 for _, node := range nodes {
1351 if node.Health == apb.Node_HEALTHY {
1352 continue
1353 }
1354 unhealthy = append(unhealthy, node.Id)
1355 }
1356 if len(unhealthy) == 0 {
1357 return nil
1358 }
1359 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1360}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001361
1362// ApproveNode approves a node by ID, waiting for it to become UP.
1363func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1364 curC, err := c.CuratorClient()
1365 if err != nil {
1366 return err
1367 }
1368 mgmt := apb.NewManagementClient(curC)
1369
1370 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1371 Pubkey: c.Nodes[id].Pubkey,
1372 })
1373 if err != nil {
1374 return fmt.Errorf("ApproveNode: %w", err)
1375 }
1376 launch.Log("Cluster: %s: approved, waiting for UP", id)
1377 for {
1378 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1379 if err != nil {
1380 return fmt.Errorf("GetNodes: %w", err)
1381 }
1382 found := false
1383 for {
1384 node, err := nodes.Recv()
1385 if errors.Is(err, io.EOF) {
1386 break
1387 }
1388 if err != nil {
1389 return fmt.Errorf("Nodes.Recv: %w", err)
1390 }
1391 if node.Id != id {
1392 continue
1393 }
1394 if node.State != cpb.NodeState_NODE_STATE_UP {
1395 continue
1396 }
1397 found = true
1398 break
1399 }
1400 nodes.CloseSend()
1401
1402 if found {
1403 break
1404 }
1405 time.Sleep(time.Second)
1406 }
1407 launch.Log("Cluster: %s: UP", id)
1408 return nil
1409}
1410
1411// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1412func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1413 curC, err := c.CuratorClient()
1414 if err != nil {
1415 return err
1416 }
1417 mgmt := apb.NewManagementClient(curC)
1418
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001419 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1420 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1421 Node: &apb.UpdateNodeRolesRequest_Id{
1422 Id: id,
1423 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001424 KubernetesWorker: ptr.To(true),
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001425 })
1426 return err
1427}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001428
Jan Schära9b060b2024-08-07 10:42:29 +02001429// MakeKubernetesController adds the KubernetesController role to a node by ID.
1430func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1431 curC, err := c.CuratorClient()
1432 if err != nil {
1433 return err
1434 }
1435 mgmt := apb.NewManagementClient(curC)
1436
Jan Schära9b060b2024-08-07 10:42:29 +02001437 launch.Log("Cluster: %s: adding KubernetesController", id)
1438 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1439 Node: &apb.UpdateNodeRolesRequest_Id{
1440 Id: id,
1441 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001442 KubernetesController: ptr.To(true),
Jan Schära9b060b2024-08-07 10:42:29 +02001443 })
1444 return err
1445}
1446
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001447// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1448func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1449 curC, err := c.CuratorClient()
1450 if err != nil {
1451 return err
1452 }
1453 mgmt := apb.NewManagementClient(curC)
1454 cur := ipb.NewCuratorClient(curC)
1455
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001456 launch.Log("Cluster: %s: adding ConsensusMember", id)
1457 bo := backoff.NewExponentialBackOff()
1458 bo.MaxElapsedTime = 10 * time.Second
1459
1460 backoff.Retry(func() error {
1461 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1462 Node: &apb.UpdateNodeRolesRequest_Id{
1463 Id: id,
1464 },
Jan Schärd1a8b642024-12-03 17:40:41 +01001465 ConsensusMember: ptr.To(true),
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001466 })
1467 if err != nil {
1468 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1469 }
1470 return err
1471 }, backoff.WithContext(bo, ctx))
1472 if err != nil {
1473 return err
1474 }
1475
1476 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1477
1478 learner := false
1479 for {
1480 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1481 if err != nil {
1482 return fmt.Errorf("GetConsensusStatus: %w", err)
1483 }
1484 for _, member := range res.EtcdMember {
1485 if member.Id != id {
1486 continue
1487 }
1488 switch member.Status {
1489 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1490 if !learner {
1491 learner = true
1492 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1493 }
1494 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1495 launch.Log("Cluster: %s: became a full member", id)
1496 return nil
1497 }
1498 }
1499 time.Sleep(100 * time.Millisecond)
1500 }
1501}