blob: 49c60dc86d192d0a58473239115f7094e908c01d [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.
5package cluster
6
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 Bazanski630fb5c2023-04-06 10:50:24 +020024 "strings"
Serge Bazanski66e58952021-10-05 17:06:56 +020025 "syscall"
26 "time"
27
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +010028 "github.com/bazelbuild/rules_go/go/runfiles"
Serge Bazanski66e58952021-10-05 17:06:56 +020029 "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"
Serge Bazanski66e58952021-10-05 17:06:56 +020039
Serge Bazanski37cfcc12024-03-21 11:59:07 +010040 ipb "source.monogon.dev/metropolis/node/core/curator/proto/api"
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +020041 apb "source.monogon.dev/metropolis/proto/api"
42 cpb "source.monogon.dev/metropolis/proto/common"
43
Serge Bazanski1f8cad72023-03-20 16:58:10 +010044 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski66e58952021-10-05 17:06:56 +020045 "source.monogon.dev/metropolis/node"
Serge Bazanskie78a0892021-10-07 17:03:49 +020046 "source.monogon.dev/metropolis/node/core/identity"
Serge Bazanski66e58952021-10-05 17:06:56 +020047 "source.monogon.dev/metropolis/node/core/rpc"
Serge Bazanski5bb8a332022-06-23 17:41:33 +020048 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Lorenz Brun150f24a2023-07-13 20:11:06 +020049 "source.monogon.dev/metropolis/pkg/localregistry"
Serge Bazanski66e58952021-10-05 17:06:56 +020050 "source.monogon.dev/metropolis/test/launch"
51)
52
Leopold20a036e2023-01-15 00:17:19 +010053// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020054type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010055 // Name is a human-readable identifier to be used in debug output.
56 Name string
57
Serge Bazanski66e58952021-10-05 17:06:56 +020058 // Ports contains the port mapping where to expose the internal ports of the VM to
59 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
60 // ConnectToSocket is set.
61 Ports launch.PortMap
62
Leopold20a036e2023-01-15 00:17:19 +010063 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
64 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020065 // want to test reboot behavior this should be false.
66 AllowReboot bool
67
Leopold20a036e2023-01-15 00:17:19 +010068 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
69 // set, it is instead connected to the given file descriptor/socket. If this is
70 // set, all port maps from the Ports option are ignored. Intended for networking
71 // this instance together with others for running more complex network
72 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020073 ConnectToSocket *os.File
74
Leopoldacfad5b2023-01-15 14:05:25 +010075 // When PcapDump is set, all traffic is dumped to a pcap file in the
76 // runtime directory (e.g. "net0.pcap" for the first interface).
77 PcapDump bool
78
Leopold20a036e2023-01-15 00:17:19 +010079 // SerialPort is an io.ReadWriter over which you can communicate with the serial
80 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +020081 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
82 SerialPort io.ReadWriter
83
84 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
85 // registering into a cluster.
86 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +020087
88 // Mac is the node's MAC address.
89 Mac *net.HardwareAddr
90
91 // Runtime keeps the node's QEMU runtime state.
92 Runtime *NodeRuntime
93}
94
Leopold20a036e2023-01-15 00:17:19 +010095// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +020096type NodeRuntime struct {
97 // ld points at the node's launch directory storing data such as storage
98 // images, firmware variables or the TPM state.
99 ld string
100 // sd points at the node's socket directory.
101 sd string
102
103 // ctxT is the context QEMU will execute in.
104 ctxT context.Context
105 // CtxC is the QEMU context's cancellation function.
106 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200107}
108
109// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200110var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200111 node.ConsensusPort,
112
113 node.CuratorServicePort,
114 node.DebugServicePort,
115
116 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100117 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200118 node.CuratorServicePort,
119 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200120 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200121}
122
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200123// setupRuntime creates the node's QEMU runtime directory, together with all
124// files required to preserve its state, a level below the chosen path ld. The
125// node's socket directory is similarily created a level below sd. It may
126// return an I/O error.
127func setupRuntime(ld, sd string) (*NodeRuntime, error) {
128 // Create a temporary directory to keep all the runtime files.
129 stdp, err := os.MkdirTemp(ld, "node_state*")
130 if err != nil {
131 return nil, fmt.Errorf("failed to create the state directory: %w", err)
132 }
133
134 // Initialize the node's storage with a prebuilt image.
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100135 si, err := runfiles.Rlocation("_main/metropolis/node/image.img")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200136 if err != nil {
137 return nil, fmt.Errorf("while resolving a path: %w", err)
138 }
139 di := filepath.Join(stdp, filepath.Base(si))
Serge Bazanski05f813b2023-03-16 17:58:39 +0100140 launch.Log("Cluster: copying node image: %s -> %s", si, di)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200141 if err := copyFile(si, di); err != nil {
142 return nil, fmt.Errorf("while copying the node image: %w", err)
143 }
144
145 // Initialize the OVMF firmware variables file.
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100146 sv, err := runfiles.Rlocation("edk2/OVMF_VARS.fd")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200147 if err != nil {
148 return nil, fmt.Errorf("while resolving a path: %w", err)
149 }
150 dv := filepath.Join(stdp, filepath.Base(sv))
151 if err := copyFile(sv, dv); err != nil {
152 return nil, fmt.Errorf("while copying firmware variables: %w", err)
153 }
154
155 // Create the TPM state directory and initialize all files required by swtpm.
156 tpmt := filepath.Join(stdp, "tpm")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200157 if err := os.Mkdir(tpmt, 0o755); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200158 return nil, fmt.Errorf("while creating the TPM directory: %w", err)
159 }
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100160 tpms, err := runfiles.Rlocation("_main/metropolis/node/tpm")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200161 if err != nil {
162 return nil, fmt.Errorf("while resolving a path: %w", err)
163 }
164 tpmf, err := os.ReadDir(tpms)
165 if err != nil {
166 return nil, fmt.Errorf("failed to read TPM directory: %w", err)
167 }
168 for _, file := range tpmf {
169 name := file.Name()
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100170 src, err := runfiles.Rlocation(filepath.Join(tpms, name))
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200171 if err != nil {
172 return nil, fmt.Errorf("while resolving a path: %w", err)
173 }
174 tgt := filepath.Join(tpmt, name)
175 if err := copyFile(src, tgt); err != nil {
176 return nil, fmt.Errorf("while copying TPM state: file %q to %q: %w", src, tgt, err)
177 }
178 }
179
180 // Create the socket directory.
181 sotdp, err := os.MkdirTemp(sd, "node_sock*")
182 if err != nil {
183 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
184 }
185
186 return &NodeRuntime{
187 ld: stdp,
188 sd: sotdp,
189 }, nil
190}
191
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200192// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200193// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200194func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200195 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200196 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanski58ddc092022-06-30 18:23:33 +0200197 r := resolver.New(c.ctxT, resolver.WithLogger(func(f string, args ...interface{}) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100198 launch.Log("Cluster: client resolver: %s", fmt.Sprintf(f, args...))
Serge Bazanski58ddc092022-06-30 18:23:33 +0200199 }))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200200 for _, n := range c.NodeIDs {
201 ep, err := resolver.NodeWithDefaultPort(n)
202 if err != nil {
203 return nil, fmt.Errorf("could not add node %q by DNS: %v", n, err)
204 }
205 r.AddEndpoint(ep)
206 }
207 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
208 grpc.WithTransportCredentials(authCreds),
209 grpc.WithResolvers(r),
210 grpc.WithContextDialer(c.DialNode),
211 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200212 if err != nil {
213 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
214 }
215 c.authClient = authClient
216 }
217 return c.authClient, nil
218}
219
Serge Bazanski66e58952021-10-05 17:06:56 +0200220// LaunchNode launches a single Metropolis node instance with the given options.
221// The instance runs mostly paravirtualized but with some emulated hardware
222// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200223// writable, and the changes are kept across reboots and shutdowns. ld and sd
224// point to the launch directory and the socket directory, holding the nodes'
225// state files (storage, tpm state, firmware state), and UNIX socket files
226// (swtpm <-> QEMU interplay) respectively. The directories must exist before
227// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
228// if either are not initialized.
229func LaunchNode(ctx context.Context, ld, sd string, options *NodeOptions) error {
230 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
231 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200232 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
233 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
234 // that we open and pass the name of it to QEMU. Not pinning this crashes both
235 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
236 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200237
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200238 // If it's the node's first start, set up its runtime directories.
239 if options.Runtime == nil {
240 r, err := setupRuntime(ld, sd)
241 if err != nil {
242 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200243 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200244 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200245 }
246
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200247 // Replace the node's context with a new one.
248 r := options.Runtime
249 if r.CtxC != nil {
250 r.CtxC()
251 }
252 r.ctxT, r.CtxC = context.WithCancel(ctx)
253
Serge Bazanski66e58952021-10-05 17:06:56 +0200254 var qemuNetType string
255 var qemuNetConfig launch.QemuValue
256 if options.ConnectToSocket != nil {
257 qemuNetType = "socket"
258 qemuNetConfig = launch.QemuValue{
259 "id": {"net0"},
260 "fd": {"3"},
261 }
262 } else {
263 qemuNetType = "user"
264 qemuNetConfig = launch.QemuValue{
265 "id": {"net0"},
266 "net": {"10.42.0.0/24"},
267 "dhcpstart": {"10.42.0.10"},
268 "hostfwd": options.Ports.ToQemuForwards(),
269 }
270 }
271
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200272 // Generate the node's MAC address if it isn't already set in NodeOptions.
273 if options.Mac == nil {
274 mac, err := generateRandomEthernetMAC()
275 if err != nil {
276 return err
277 }
278 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200279 }
280
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100281 ovmfCodePath, err := runfiles.Rlocation("edk2/OVMF_CODE.fd")
282 if err != nil {
283 return err
284 }
285
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200286 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
287 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Lorenz Brun1dc60af2023-10-03 15:40:09 +0200288 storagePath := filepath.Join(r.ld, "image.img")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200289 qemuArgs := []string{
290 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults", "-m", "4096",
Serge Bazanski66e58952021-10-05 17:06:56 +0200291 "-cpu", "host", "-smp", "sockets=1,cpus=1,cores=2,threads=2,maxcpus=4",
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100292 "-drive", "if=pflash,format=raw,readonly=on,file=" + ovmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200293 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
294 "-drive", "if=virtio,format=raw,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200295 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200296 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200297 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
298 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
299 "-device", "tpm-tis,tpmdev=tpm0",
300 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200301 "-serial", "stdio",
302 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200303
304 if !options.AllowReboot {
305 qemuArgs = append(qemuArgs, "-no-reboot")
306 }
307
308 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200309 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200310 parametersRaw, err := proto.Marshal(options.NodeParameters)
311 if err != nil {
312 return fmt.Errorf("failed to encode node paraeters: %w", err)
313 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200314 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200315 return fmt.Errorf("failed to write node parameters: %w", err)
316 }
317 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
318 }
319
Leopoldacfad5b2023-01-15 14:05:25 +0100320 if options.PcapDump {
321 var qemuNetDump launch.QemuValue
322 pcapPath := filepath.Join(r.ld, "net0.pcap")
323 if options.PcapDump {
324 qemuNetDump = launch.QemuValue{
325 "id": {"net0"},
326 "netdev": {"net0"},
327 "file": {pcapPath},
328 }
329 }
330 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
331 }
332
Serge Bazanski66e58952021-10-05 17:06:56 +0200333 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200334 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200335 defer tpmCancel()
336
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200337 tpmd := filepath.Join(r.ld, "tpm")
338 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanski66e58952021-10-05 17:06:56 +0200339 tpmEmuCmd.Stderr = os.Stderr
340 tpmEmuCmd.Stdout = os.Stdout
341
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100342 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200343 if err != nil {
344 return fmt.Errorf("failed to start TPM emulator: %w", err)
345 }
346
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200347 // Wait for the socket to be created by the TPM emulator before launching
348 // QEMU.
349 for {
350 _, err := os.Stat(tpmSocketPath)
351 if err == nil {
352 break
353 }
354 if err != nil && !os.IsNotExist(err) {
355 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
356 }
357 if err := tpmCtx.Err(); err != nil {
358 return fmt.Errorf("while waiting for the TPM socket: %w", err)
359 }
360 time.Sleep(time.Millisecond * 100)
361 }
362
Serge Bazanski66e58952021-10-05 17:06:56 +0200363 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200364 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200365 if options.ConnectToSocket != nil {
366 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
367 }
368
369 var stdErrBuf bytes.Buffer
370 systemCmd.Stderr = &stdErrBuf
371 systemCmd.Stdout = options.SerialPort
372
Leopoldaf5086b2023-01-15 14:12:42 +0100373 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
374
Serge Bazanski66e58952021-10-05 17:06:56 +0200375 err = systemCmd.Run()
376
377 // Stop TPM emulator and wait for it to exit to properly reap the child process
378 tpmCancel()
Serge Bazanski05f813b2023-03-16 17:58:39 +0100379 launch.Log("Node: Waiting for TPM emulator to exit")
Serge Bazanski66e58952021-10-05 17:06:56 +0200380 // Wait returns a SIGKILL error because we just cancelled its context.
381 // We still need to call it to avoid creating zombies.
382 _ = tpmEmuCmd.Wait()
Serge Bazanski05f813b2023-03-16 17:58:39 +0100383 launch.Log("Node: TPM emulator done")
Serge Bazanski66e58952021-10-05 17:06:56 +0200384
385 var exerr *exec.ExitError
386 if err != nil && errors.As(err, &exerr) {
387 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
388 if status.Signaled() && status.Signal() == syscall.SIGKILL {
389 // Process was killed externally (most likely by our context being canceled).
390 // This is a normal exit for us, so return nil
391 return nil
392 }
393 exerr.Stderr = stdErrBuf.Bytes()
394 newErr := launch.QEMUError(*exerr)
395 return &newErr
396 }
397 return err
398}
399
400func copyFile(src, dst string) error {
401 in, err := os.Open(src)
402 if err != nil {
403 return fmt.Errorf("when opening source: %w", err)
404 }
405 defer in.Close()
406
407 out, err := os.Create(dst)
408 if err != nil {
409 return fmt.Errorf("when creating destination: %w", err)
410 }
411 defer out.Close()
412
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100413 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200414 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100415 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200416 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100417
418 // Copy the file while preserving its sparseness. The image files are very
419 // sparse (less than 10% allocated), so this is a lot faster.
420 var lastHoleStart int64
421 for {
422 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
423 if err != nil {
424 return fmt.Errorf("when seeking to next data block: %w", err)
425 }
426 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
427 if err != nil {
428 return fmt.Errorf("when seeking to next hole: %w", err)
429 }
430 lastHoleStart = holeStart
431 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
432 return fmt.Errorf("when seeking to current data block: %w", err)
433 }
434 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
435 return fmt.Errorf("when seeking output to next data block: %w", err)
436 }
437 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
438 return fmt.Errorf("when copying file: %w", err)
439 }
440 if endPos == holeStart {
441 // The next hole is at the end of the file, we're done here.
442 break
443 }
444 }
445
Serge Bazanski66e58952021-10-05 17:06:56 +0200446 return out.Close()
447}
448
Serge Bazanskie78a0892021-10-07 17:03:49 +0200449// getNodes wraps around Management.GetNodes to return a list of nodes in a
450// cluster.
451func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200452 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100453 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100454 err := backoff.Retry(func() error {
455 res = nil
456 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200457 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100458 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200459 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100460 for {
461 node, err := srvN.Recv()
462 if err == io.EOF {
463 break
464 }
465 if err != nil {
466 return fmt.Errorf("GetNodes.Recv: %w", err)
467 }
468 res = append(res, node)
469 }
470 return nil
471 }, bo)
472 if err != nil {
473 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200474 }
475 return res, nil
476}
477
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200478// getNode wraps Management.GetNodes. It returns node information matching
479// given node ID.
480func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
481 nodes, err := getNodes(ctx, mgmt)
482 if err != nil {
483 return nil, fmt.Errorf("could not get nodes: %w", err)
484 }
485 for _, n := range nodes {
486 eid := identity.NodeID(n.Pubkey)
487 if eid != id {
488 continue
489 }
490 return n, nil
491 }
492 return nil, fmt.Errorf("no such node.")
493}
494
Serge Bazanski66e58952021-10-05 17:06:56 +0200495// Gets a random EUI-48 Ethernet MAC address
496func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
497 macBuf := make([]byte, 6)
498 _, err := rand.Read(macBuf)
499 if err != nil {
500 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
501 }
502
503 // Set U/L bit and clear I/G bit (locally administered individual MAC)
504 // Ref IEEE 802-2014 Section 8.2.2
505 macBuf[0] = (macBuf[0] | 2) & 0xfe
506 mac := net.HardwareAddr(macBuf)
507 return &mac, nil
508}
509
Serge Bazanskibe742842022-04-04 13:18:50 +0200510const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200511
Serge Bazanskibe742842022-04-04 13:18:50 +0200512// ClusterPorts contains all ports handled by Nanoswitch.
513var ClusterPorts = []uint16{
514 // Forwarded to the first node.
515 uint16(node.CuratorServicePort),
516 uint16(node.DebugServicePort),
517 uint16(node.KubernetesAPIPort),
518 uint16(node.KubernetesAPIWrappedPort),
519
520 // SOCKS proxy to the switch network
521 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200522}
523
524// ClusterOptions contains all options for launching a Metropolis cluster.
525type ClusterOptions struct {
526 // The number of nodes this cluster should be started with.
527 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100528
529 // If true, node logs will be saved to individual files instead of being printed
530 // out to stderr. The path of these files will be still printed to stdout.
531 //
532 // The files will be located within the launch directory inside TEST_TMPDIR (or
533 // the default tempdir location, if not set).
534 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200535
536 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
537 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
538 // incomplete.
539 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200540
541 // Optional local registry which will be made available to the cluster to
542 // pull images from. This is a more efficient alternative to preseeding all
543 // images used for testing.
544 LocalRegistry *localregistry.Server
Serge Bazanski66e58952021-10-05 17:06:56 +0200545}
546
547// Cluster is the running Metropolis cluster launched using the LaunchCluster
548// function.
549type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200550 // Owner is the TLS Certificate of the owner of the test cluster. This can be
551 // used to authenticate further clients to the running cluster.
552 Owner tls.Certificate
553 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200554 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200555 Ports launch.PortMap
556
Serge Bazanskibe742842022-04-04 13:18:50 +0200557 // Nodes is a map from Node ID to its runtime information.
558 Nodes map[string]*NodeInCluster
559 // NodeIDs is a list of node IDs that are backing this cluster, in order of
560 // creation.
561 NodeIDs []string
562
Serge Bazanski54e212a2023-06-14 13:45:11 +0200563 // CACertificate is the cluster's CA certificate.
564 CACertificate *x509.Certificate
565
Serge Bazanski66e58952021-10-05 17:06:56 +0200566 // nodesDone is a list of channels populated with the return codes from all the
567 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100568 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200569 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200570 // nodeOpts are the cluster member nodes' mutable launch options, kept here
571 // to facilitate reboots.
572 nodeOpts []NodeOptions
573 // launchDir points at the directory keeping the nodes' state, such as storage
574 // images, firmware variable files, TPM state.
575 launchDir string
576 // socketDir points at the directory keeping UNIX socket files, such as these
577 // used to facilitate communication between QEMU and swtpm. It's different
578 // from launchDir, and anchored nearer the file system root, due to the
579 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100580 socketDir string
581 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200582
Lorenz Brun276a7462023-07-12 21:28:54 +0200583 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200584 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200585 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200586
587 // authClient is a cached authenticated owner connection to a Curator
588 // instance within the cluster.
589 authClient *grpc.ClientConn
590
591 // ctxT is the context individual node contexts are created from.
592 ctxT context.Context
593 // ctxC is used by Close to cancel the context under which the nodes are
594 // running.
595 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200596}
597
598// NodeInCluster represents information about a node that's part of a Cluster.
599type NodeInCluster struct {
600 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200601 ID string
602 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200603 // Address of the node on the network ran by nanoswitch. Not reachable from the
604 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
605 // on Cluster.Ports[SOCKSPort]).
606 ManagementAddress string
607}
608
609// firstConnection performs the initial owner credential escrow with a newly
610// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
611// running at 10.1.0.2, which is always the case with the current nanoswitch
612// implementation.
613//
Leopold20a036e2023-01-15 00:17:19 +0100614// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200615// information as NodeInCluster.
616func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
617 // Dial external service.
618 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100619 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200620 if err != nil {
621 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
622 }
623 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
624 return socksDialer.Dial("tcp", addr)
625 }
626 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
627 if err != nil {
628 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
629 }
630 defer initClient.Close()
631
632 // Retrieve owner certificate - this can take a while because the node is still
633 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100634 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200635 aaa := apb.NewAAAClient(initClient)
636 var cert *tls.Certificate
637 err = backoff.Retry(func() error {
638 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
639 if st, ok := status.FromError(err); ok {
640 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100641 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200642 return err
643 }
644 }
645 return backoff.Permanent(err)
646 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
647 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200648 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200649 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100650 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200651
652 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200653 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200654 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
655 if err != nil {
656 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
657 }
658 defer authClient.Close()
659 mgmt := apb.NewManagementClient(authClient)
660
661 var node *NodeInCluster
662 err = backoff.Retry(func() error {
663 nodes, err := getNodes(ctx, mgmt)
664 if err != nil {
665 return fmt.Errorf("retrieving nodes failed: %w", err)
666 }
667 if len(nodes) != 1 {
668 return fmt.Errorf("expected one node, got %d", len(nodes))
669 }
670 n := nodes[0]
671 if n.Status == nil || n.Status.ExternalAddress == "" {
672 return fmt.Errorf("node has no status and/or address")
673 }
674 node = &NodeInCluster{
675 ID: identity.NodeID(n.Pubkey),
676 ManagementAddress: n.Status.ExternalAddress,
677 }
678 return nil
679 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
680 if err != nil {
681 return nil, nil, err
682 }
683
684 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200685}
686
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100687func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200688 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100689 if err != nil {
690 return nil, err
691 }
692 return f, nil
693}
694
Serge Bazanski66e58952021-10-05 17:06:56 +0200695// LaunchCluster launches a cluster of Metropolis node VMs together with a
696// Nanoswitch instance to network them all together.
697//
698// The given context will be used to run all qemu instances in the cluster, and
699// canceling the context or calling Close() will terminate them.
700func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200701 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200702 return nil, errors.New("refusing to start cluster with zero nodes")
703 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200704
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200705 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100706 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200707 if err != nil {
708 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
709 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100710 // Create the metroctl config directory. We keep it in /tmp because in some
711 // scenarios it's end-user visible and we want it short.
712 md, err := os.MkdirTemp("/tmp", "metroctl-*")
713 if err != nil {
714 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
715 }
716
717 // Create the socket directory. We keep it in /tmp because of socket path limits.
718 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200719 if err != nil {
720 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
721 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200722
723 // Prepare links between nodes and nanoswitch.
724 var switchPorts []*os.File
725 var vmPorts []*os.File
726 for i := 0; i < opts.NumNodes; i++ {
727 switchPort, vmPort, err := launch.NewSocketPair()
728 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200729 return nil, fmt.Errorf("failed to get socketpair: %w", err)
730 }
731 switchPorts = append(switchPorts, switchPort)
732 vmPorts = append(vmPorts, vmPort)
733 }
734
Serge Bazanskie78a0892021-10-07 17:03:49 +0200735 // Make a list of channels that will be populated by all running node qemu
736 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200737 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200738 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200739 done[i] = make(chan error, 1)
740 }
741
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200742 // Prepare the node options. These will be kept as part of Cluster.
743 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
744 // launch. The runtime information can be later used to restart a node.
745 // The 0th node will be initialized first. The rest will follow after it
746 // had bootstrapped the cluster.
747 nodeOpts := make([]NodeOptions, opts.NumNodes)
748 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100749 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200750 ConnectToSocket: vmPorts[0],
751 NodeParameters: &apb.NodeParameters{
752 Cluster: &apb.NodeParameters_ClusterBootstrap_{
753 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
754 OwnerPublicKey: InsecurePublicKey,
Serge Bazanski66e58952021-10-05 17:06:56 +0200755 },
756 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200757 },
758 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100759 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200760 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100761 if opts.NodeLogsToFiles {
762 path := path.Join(ld, "node-1.txt")
763 port, err := NewSerialFileLogger(path)
764 if err != nil {
765 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
766 }
767 launch.Log("Node 1 logs at %s", path)
768 nodeOpts[0].SerialPort = port
769 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200770
771 // Start the first node.
772 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100773 launch.Log("Cluster: Starting node %d...", 1)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200774 go func() {
775 err := LaunchNode(ctxT, ld, sd, &nodeOpts[0])
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200776 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100777 launch.Log("Node %d finished with an error: %v", 1, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200778 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200779 done[0] <- err
780 }()
781
Lorenz Brun150f24a2023-07-13 20:11:06 +0200782 localRegistryAddr := net.TCPAddr{
783 IP: net.IPv4(10, 42, 0, 82),
784 Port: 5000,
785 }
786
787 var guestSvcMap launch.GuestServiceMap
788 if opts.LocalRegistry != nil {
789 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
790 if err != nil {
791 ctxC()
792 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
793 }
794 s := http.Server{
795 Handler: opts.LocalRegistry,
796 }
797 go s.Serve(l)
798 go func() {
799 <-ctxT.Done()
800 s.Close()
801 }()
802 guestSvcMap = launch.GuestServiceMap{
803 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
804 }
805 }
806
Serge Bazanskie78a0892021-10-07 17:03:49 +0200807 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200808 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
809 if err != nil {
810 ctxC()
811 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
812 }
813
814 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100815 var serialPort io.ReadWriter
816 if opts.NodeLogsToFiles {
817 path := path.Join(ld, "nanoswitch.txt")
818 serialPort, err = NewSerialFileLogger(path)
819 if err != nil {
820 launch.Log("Could not open log file for nanoswitch: %v", err)
821 }
822 launch.Log("Nanoswitch logs at %s", path)
823 } else {
824 serialPort = newPrefixedStdio(99)
825 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200826 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100827 Name: "nanoswitch",
Serge Bazanski66e58952021-10-05 17:06:56 +0200828 KernelPath: "metropolis/test/ktest/vmlinux",
Lorenz Brun62f1d362023-11-14 16:18:24 +0100829 InitramfsPath: "metropolis/test/nanoswitch/initramfs.cpio.zst",
Serge Bazanski66e58952021-10-05 17:06:56 +0200830 ExtraNetworkInterfaces: switchPorts,
831 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200832 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100833 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100834 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200835 }); err != nil {
836 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100837 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200838 }
839 }
840 }()
841
Serge Bazanskibe742842022-04-04 13:18:50 +0200842 // Build SOCKS dialer.
843 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
844 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200845 if err != nil {
846 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200847 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200848 }
849
Serge Bazanskibe742842022-04-04 13:18:50 +0200850 // Retrieve owner credentials and first node.
851 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200852 if err != nil {
853 ctxC()
854 return nil, err
855 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200856
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100857 // Write credentials to the metroctl directory.
858 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
859 ctxC()
860 return nil, fmt.Errorf("could not write owner key: %w", err)
861 }
862 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
863 ctxC()
864 return nil, fmt.Errorf("could not write owner certificate: %w", err)
865 }
866
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200867 // Set up a partially initialized cluster instance, to be filled in in the
868 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200869 cluster := &Cluster{
870 Owner: *cert,
871 Ports: portMap,
872 Nodes: map[string]*NodeInCluster{
873 firstNode.ID: firstNode,
874 },
875 NodeIDs: []string{
876 firstNode.ID,
877 },
878
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100879 nodesDone: done,
880 nodeOpts: nodeOpts,
881 launchDir: ld,
882 socketDir: sd,
883 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200884
Lorenz Brun276a7462023-07-12 21:28:54 +0200885 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200886
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200887 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200888 ctxC: ctxC,
889 }
890
891 // Now start the rest of the nodes and register them into the cluster.
892
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200893 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200894 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200895 if err != nil {
896 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200897 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200898 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200899 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200900
901 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100902 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200903 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
904 if err != nil {
905 ctxC()
906 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
907 }
908 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100909 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200910
911 // Retrieve cluster info (for directory and ca public key) to register further
912 // nodes.
913 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
914 if err != nil {
915 ctxC()
916 return nil, fmt.Errorf("GetClusterInfo: %w", err)
917 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200918 caCert, err := x509.ParseCertificate(resI.CaCertificate)
919 if err != nil {
920 ctxC()
921 return nil, fmt.Errorf("ParseCertificate: %w", err)
922 }
923 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200924
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200925 // Use the retrieved information to configure the rest of the node options.
926 for i := 1; i < opts.NumNodes; i++ {
927 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100928 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200929 ConnectToSocket: vmPorts[i],
930 NodeParameters: &apb.NodeParameters{
931 Cluster: &apb.NodeParameters_ClusterRegister_{
932 ClusterRegister: &apb.NodeParameters_ClusterRegister{
933 RegisterTicket: ticket,
934 ClusterDirectory: resI.ClusterDirectory,
935 CaCertificate: resI.CaCertificate,
936 },
937 },
938 },
939 SerialPort: newPrefixedStdio(i),
940 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100941 if opts.NodeLogsToFiles {
942 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
943 port, err := NewSerialFileLogger(path)
944 if err != nil {
945 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
946 }
947 launch.Log("Node %d logs at %s", i+1, path)
948 nodeOpts[i].SerialPort = port
949 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200950 }
951
952 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200953 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100954 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200955 go func(i int) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200956 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i])
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200957 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100958 launch.Log("Node %d finished with an error: %v", i, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200959 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200960 done[i] <- err
961 }(i)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200962 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200963
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200964 seenNodes := make(map[string]bool)
965 launch.Log("Cluster: waiting for nodes to appear as NEW...")
966 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200967 for {
968 nodes, err := getNodes(ctx, mgmt)
969 if err != nil {
970 ctxC()
971 return nil, fmt.Errorf("could not get nodes: %w", err)
972 }
973 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200974 if n.State != cpb.NodeState_NODE_STATE_NEW {
975 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200976 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100977 if seenNodes[n.Id] {
978 continue
979 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200980 seenNodes[n.Id] = true
981 cluster.Nodes[n.Id] = &NodeInCluster{
982 ID: n.Id,
983 Pubkey: n.Pubkey,
984 }
985 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200986 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200987
988 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200989 break
990 }
991 time.Sleep(1 * time.Second)
992 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200993 }
994 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200995
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200996 approvedNodes := make(map[string]bool)
997 upNodes := make(map[string]bool)
998 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200999 for {
1000 nodes, err := getNodes(ctx, mgmt)
1001 if err != nil {
1002 ctxC()
1003 return nil, fmt.Errorf("could not get nodes: %w", err)
1004 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001005 for _, node := range nodes {
1006 if !seenNodes[node.Id] {
1007 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001008 continue
1009 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001010
1011 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1012 launch.Log("Cluster: node %s is up", node.Id)
1013 upNodes[node.Id] = true
1014 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001015 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001016 if upNodes[node.Id] {
1017 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001018 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001019
1020 if !approvedNodes[node.Id] {
1021 launch.Log("Cluster: approving node %s", node.Id)
1022 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1023 Pubkey: node.Pubkey,
1024 })
1025 if err != nil {
1026 ctxC()
1027 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1028 }
1029 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001030 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001031 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001032
1033 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1034 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001035 break
1036 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001037 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001038 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001039 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001040
Serge Bazanski05f813b2023-03-16 17:58:39 +01001041 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001042 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001043 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001044 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001045 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001046
Serge Bazanskibe742842022-04-04 13:18:50 +02001047 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001048}
1049
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001050// RebootNode reboots the cluster member node matching the given index, and
1051// waits for it to rejoin the cluster. It will use the given context ctx to run
1052// cluster API requests, whereas the resulting QEMU process will be created
1053// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1054func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1055 if idx < 0 || idx >= len(c.NodeIDs) {
1056 return fmt.Errorf("index out of bounds.")
1057 }
1058 id := c.NodeIDs[idx]
1059
1060 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001061 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001062 if err != nil {
1063 return err
1064 }
1065 mgmt := apb.NewManagementClient(curC)
1066
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001067 // Cancel the node's context. This will shut down QEMU.
1068 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001069 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001070 err = <-c.nodesDone[idx]
1071 if err != nil {
1072 return fmt.Errorf("while restarting node: %w", err)
1073 }
1074
1075 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001076 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001077 go func(n int) {
1078 err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[n])
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001079 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001080 launch.Log("Node %d finished with an error: %v", n, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001081 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001082 c.nodesDone[n] <- err
1083 }(idx)
1084
Serge Bazanskibc969572024-03-21 11:56:13 +01001085 start := time.Now()
1086
1087 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001088 for {
1089 cs, err := getNode(ctx, mgmt, id)
1090 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001091 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001092 return err
1093 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001094 launch.Log("Cluster: node health: %+v", cs.Health)
1095
1096 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1097 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001098 break
1099 }
1100 time.Sleep(time.Second)
1101 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001102 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001103 return nil
1104}
1105
1106// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001107// nodes to stop. It returns an error if stopping the nodes failed, or one of
1108// the nodes failed to fully start in the first place.
1109func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001110 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001111 if c.authClient != nil {
1112 c.authClient.Close()
1113 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001114 c.ctxC()
1115
Leopold20a036e2023-01-15 00:17:19 +01001116 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001117 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001118 for _, c := range c.nodesDone {
1119 err := <-c
1120 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001121 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001122 }
1123 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001124 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001125 os.RemoveAll(c.launchDir)
1126 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001127 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001128 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001129 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001130}
Serge Bazanskibe742842022-04-04 13:18:50 +02001131
1132// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1133// their ID. This is performed by connecting to the cluster nanoswitch via its
1134// SOCKS proxy, and using the cluster node list for name resolution.
1135//
1136// For example:
1137//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001138// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001139func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1140 host, port, err := net.SplitHostPort(addr)
1141 if err != nil {
1142 return nil, fmt.Errorf("invalid host:port: %w", err)
1143 }
1144 // Already an IP address?
1145 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001146 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001147 }
1148
1149 // Otherwise, expect a node name.
1150 node, ok := c.Nodes[host]
1151 if !ok {
1152 return nil, fmt.Errorf("unknown node %q", host)
1153 }
1154 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001155 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001156}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001157
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001158// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1159// Kubernetes authenticating proxy using the cluster owner identity.
1160// It currently has access to everything (i.e. the cluster-admin role)
1161// via the owner-admin binding.
1162func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1163 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1164 if err != nil {
1165 // We explicitly pass an Ed25519 private key in, so this can't happen
1166 panic(err)
1167 }
1168
1169 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001170 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001171 Host: host,
1172 TLSClientConfig: rest.TLSClientConfig{
1173 // TODO(q3k): use CA certificate
1174 Insecure: true,
1175 ServerName: "kubernetes.default.svc",
1176 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1177 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1178 },
1179 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1180 return c.DialNode(ctx, address)
1181 },
1182 }
1183 return kubernetes.NewForConfig(&clientConfig)
1184}
1185
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001186// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1187// which are currently Kubernetes controllers, ie. run an apiserver. This list
1188// might be empty if no node is currently configured with the
1189// 'KubernetesController' node.
1190func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1191 curC, err := c.CuratorClient()
1192 if err != nil {
1193 return nil, err
1194 }
1195 mgmt := apb.NewManagementClient(curC)
1196 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1197 Filter: "has(node.roles.kubernetes_controller)",
1198 })
1199 if err != nil {
1200 return nil, err
1201 }
1202 defer srv.CloseSend()
1203 var res []string
1204 for {
1205 n, err := srv.Recv()
1206 if err == io.EOF {
1207 break
1208 }
1209 if err != nil {
1210 return nil, err
1211 }
1212 if n.Status == nil || n.Status.ExternalAddress == "" {
1213 continue
1214 }
1215 res = append(res, n.Status.ExternalAddress)
1216 }
1217 return res, nil
1218}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001219
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001220// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1221// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001222func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1223 // Get an authenticated owner client within the cluster.
1224 curC, err := c.CuratorClient()
1225 if err != nil {
1226 return err
1227 }
1228 mgmt := apb.NewManagementClient(curC)
1229 nodes, err := getNodes(ctx, mgmt)
1230 if err != nil {
1231 return err
1232 }
1233
1234 var unhealthy []string
1235 for _, node := range nodes {
1236 if node.Health == apb.Node_HEALTHY {
1237 continue
1238 }
1239 unhealthy = append(unhealthy, node.Id)
1240 }
1241 if len(unhealthy) == 0 {
1242 return nil
1243 }
1244 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1245}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001246
1247// ApproveNode approves a node by ID, waiting for it to become UP.
1248func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1249 curC, err := c.CuratorClient()
1250 if err != nil {
1251 return err
1252 }
1253 mgmt := apb.NewManagementClient(curC)
1254
1255 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1256 Pubkey: c.Nodes[id].Pubkey,
1257 })
1258 if err != nil {
1259 return fmt.Errorf("ApproveNode: %w", err)
1260 }
1261 launch.Log("Cluster: %s: approved, waiting for UP", id)
1262 for {
1263 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1264 if err != nil {
1265 return fmt.Errorf("GetNodes: %w", err)
1266 }
1267 found := false
1268 for {
1269 node, err := nodes.Recv()
1270 if errors.Is(err, io.EOF) {
1271 break
1272 }
1273 if err != nil {
1274 return fmt.Errorf("Nodes.Recv: %w", err)
1275 }
1276 if node.Id != id {
1277 continue
1278 }
1279 if node.State != cpb.NodeState_NODE_STATE_UP {
1280 continue
1281 }
1282 found = true
1283 break
1284 }
1285 nodes.CloseSend()
1286
1287 if found {
1288 break
1289 }
1290 time.Sleep(time.Second)
1291 }
1292 launch.Log("Cluster: %s: UP", id)
1293 return nil
1294}
1295
1296// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1297func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1298 curC, err := c.CuratorClient()
1299 if err != nil {
1300 return err
1301 }
1302 mgmt := apb.NewManagementClient(curC)
1303
1304 tr := true
1305 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1306 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1307 Node: &apb.UpdateNodeRolesRequest_Id{
1308 Id: id,
1309 },
1310 KubernetesWorker: &tr,
1311 })
1312 return err
1313}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001314
1315// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1316func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1317 curC, err := c.CuratorClient()
1318 if err != nil {
1319 return err
1320 }
1321 mgmt := apb.NewManagementClient(curC)
1322 cur := ipb.NewCuratorClient(curC)
1323
1324 tr := true
1325 launch.Log("Cluster: %s: adding ConsensusMember", id)
1326 bo := backoff.NewExponentialBackOff()
1327 bo.MaxElapsedTime = 10 * time.Second
1328
1329 backoff.Retry(func() error {
1330 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1331 Node: &apb.UpdateNodeRolesRequest_Id{
1332 Id: id,
1333 },
1334 ConsensusMember: &tr,
1335 })
1336 if err != nil {
1337 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1338 }
1339 return err
1340 }, backoff.WithContext(bo, ctx))
1341 if err != nil {
1342 return err
1343 }
1344
1345 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1346
1347 learner := false
1348 for {
1349 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1350 if err != nil {
1351 return fmt.Errorf("GetConsensusStatus: %w", err)
1352 }
1353 for _, member := range res.EtcdMember {
1354 if member.Id != id {
1355 continue
1356 }
1357 switch member.Status {
1358 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1359 if !learner {
1360 learner = true
1361 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1362 }
1363 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1364 launch.Log("Cluster: %s: became a full member", id)
1365 return nil
1366 }
1367 }
1368 time.Sleep(100 * time.Millisecond)
1369 }
1370}