blob: eadd7efc28c8613cb46edc1924ea7bb64d7f4d35 [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 {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200321 qemuNetDump := launch.QemuValue{
322 "id": {"net0"},
323 "netdev": {"net0"},
324 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100325 }
326 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
327 }
328
Serge Bazanski66e58952021-10-05 17:06:56 +0200329 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200330 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200331 defer tpmCancel()
332
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200333 tpmd := filepath.Join(r.ld, "tpm")
334 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanski66e58952021-10-05 17:06:56 +0200335 tpmEmuCmd.Stderr = os.Stderr
336 tpmEmuCmd.Stdout = os.Stdout
337
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100338 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200339 if err != nil {
340 return fmt.Errorf("failed to start TPM emulator: %w", err)
341 }
342
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200343 // Wait for the socket to be created by the TPM emulator before launching
344 // QEMU.
345 for {
346 _, err := os.Stat(tpmSocketPath)
347 if err == nil {
348 break
349 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200350 if !os.IsNotExist(err) {
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200351 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
352 }
353 if err := tpmCtx.Err(); err != nil {
354 return fmt.Errorf("while waiting for the TPM socket: %w", err)
355 }
356 time.Sleep(time.Millisecond * 100)
357 }
358
Serge Bazanski66e58952021-10-05 17:06:56 +0200359 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200360 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200361 if options.ConnectToSocket != nil {
362 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
363 }
364
365 var stdErrBuf bytes.Buffer
366 systemCmd.Stderr = &stdErrBuf
367 systemCmd.Stdout = options.SerialPort
368
Leopoldaf5086b2023-01-15 14:12:42 +0100369 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
370
Serge Bazanski66e58952021-10-05 17:06:56 +0200371 err = systemCmd.Run()
372
373 // Stop TPM emulator and wait for it to exit to properly reap the child process
374 tpmCancel()
Serge Bazanski05f813b2023-03-16 17:58:39 +0100375 launch.Log("Node: Waiting for TPM emulator to exit")
Serge Bazanski66e58952021-10-05 17:06:56 +0200376 // Wait returns a SIGKILL error because we just cancelled its context.
377 // We still need to call it to avoid creating zombies.
378 _ = tpmEmuCmd.Wait()
Serge Bazanski05f813b2023-03-16 17:58:39 +0100379 launch.Log("Node: TPM emulator done")
Serge Bazanski66e58952021-10-05 17:06:56 +0200380
381 var exerr *exec.ExitError
382 if err != nil && errors.As(err, &exerr) {
383 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
384 if status.Signaled() && status.Signal() == syscall.SIGKILL {
385 // Process was killed externally (most likely by our context being canceled).
386 // This is a normal exit for us, so return nil
387 return nil
388 }
389 exerr.Stderr = stdErrBuf.Bytes()
390 newErr := launch.QEMUError(*exerr)
391 return &newErr
392 }
393 return err
394}
395
396func copyFile(src, dst string) error {
397 in, err := os.Open(src)
398 if err != nil {
399 return fmt.Errorf("when opening source: %w", err)
400 }
401 defer in.Close()
402
403 out, err := os.Create(dst)
404 if err != nil {
405 return fmt.Errorf("when creating destination: %w", err)
406 }
407 defer out.Close()
408
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100409 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200410 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100411 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200412 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100413
414 // Copy the file while preserving its sparseness. The image files are very
415 // sparse (less than 10% allocated), so this is a lot faster.
416 var lastHoleStart int64
417 for {
418 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
419 if err != nil {
420 return fmt.Errorf("when seeking to next data block: %w", err)
421 }
422 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
423 if err != nil {
424 return fmt.Errorf("when seeking to next hole: %w", err)
425 }
426 lastHoleStart = holeStart
427 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
428 return fmt.Errorf("when seeking to current data block: %w", err)
429 }
430 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
431 return fmt.Errorf("when seeking output to next data block: %w", err)
432 }
433 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
434 return fmt.Errorf("when copying file: %w", err)
435 }
436 if endPos == holeStart {
437 // The next hole is at the end of the file, we're done here.
438 break
439 }
440 }
441
Serge Bazanski66e58952021-10-05 17:06:56 +0200442 return out.Close()
443}
444
Serge Bazanskie78a0892021-10-07 17:03:49 +0200445// getNodes wraps around Management.GetNodes to return a list of nodes in a
446// cluster.
447func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200448 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100449 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100450 err := backoff.Retry(func() error {
451 res = nil
452 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200453 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100454 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200455 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100456 for {
457 node, err := srvN.Recv()
458 if err == io.EOF {
459 break
460 }
461 if err != nil {
462 return fmt.Errorf("GetNodes.Recv: %w", err)
463 }
464 res = append(res, node)
465 }
466 return nil
467 }, bo)
468 if err != nil {
469 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200470 }
471 return res, nil
472}
473
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200474// getNode wraps Management.GetNodes. It returns node information matching
475// given node ID.
476func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
477 nodes, err := getNodes(ctx, mgmt)
478 if err != nil {
479 return nil, fmt.Errorf("could not get nodes: %w", err)
480 }
481 for _, n := range nodes {
482 eid := identity.NodeID(n.Pubkey)
483 if eid != id {
484 continue
485 }
486 return n, nil
487 }
488 return nil, fmt.Errorf("no such node.")
489}
490
Serge Bazanski66e58952021-10-05 17:06:56 +0200491// Gets a random EUI-48 Ethernet MAC address
492func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
493 macBuf := make([]byte, 6)
494 _, err := rand.Read(macBuf)
495 if err != nil {
496 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
497 }
498
499 // Set U/L bit and clear I/G bit (locally administered individual MAC)
500 // Ref IEEE 802-2014 Section 8.2.2
501 macBuf[0] = (macBuf[0] | 2) & 0xfe
502 mac := net.HardwareAddr(macBuf)
503 return &mac, nil
504}
505
Serge Bazanskibe742842022-04-04 13:18:50 +0200506const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200507
Serge Bazanskibe742842022-04-04 13:18:50 +0200508// ClusterPorts contains all ports handled by Nanoswitch.
509var ClusterPorts = []uint16{
510 // Forwarded to the first node.
511 uint16(node.CuratorServicePort),
512 uint16(node.DebugServicePort),
513 uint16(node.KubernetesAPIPort),
514 uint16(node.KubernetesAPIWrappedPort),
515
516 // SOCKS proxy to the switch network
517 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200518}
519
520// ClusterOptions contains all options for launching a Metropolis cluster.
521type ClusterOptions struct {
522 // The number of nodes this cluster should be started with.
523 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100524
525 // If true, node logs will be saved to individual files instead of being printed
526 // out to stderr. The path of these files will be still printed to stdout.
527 //
528 // The files will be located within the launch directory inside TEST_TMPDIR (or
529 // the default tempdir location, if not set).
530 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200531
532 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
533 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
534 // incomplete.
535 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200536
537 // Optional local registry which will be made available to the cluster to
538 // pull images from. This is a more efficient alternative to preseeding all
539 // images used for testing.
540 LocalRegistry *localregistry.Server
Serge Bazanski66e58952021-10-05 17:06:56 +0200541}
542
543// Cluster is the running Metropolis cluster launched using the LaunchCluster
544// function.
545type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200546 // Owner is the TLS Certificate of the owner of the test cluster. This can be
547 // used to authenticate further clients to the running cluster.
548 Owner tls.Certificate
549 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200550 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200551 Ports launch.PortMap
552
Serge Bazanskibe742842022-04-04 13:18:50 +0200553 // Nodes is a map from Node ID to its runtime information.
554 Nodes map[string]*NodeInCluster
555 // NodeIDs is a list of node IDs that are backing this cluster, in order of
556 // creation.
557 NodeIDs []string
558
Serge Bazanski54e212a2023-06-14 13:45:11 +0200559 // CACertificate is the cluster's CA certificate.
560 CACertificate *x509.Certificate
561
Serge Bazanski66e58952021-10-05 17:06:56 +0200562 // nodesDone is a list of channels populated with the return codes from all the
563 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100564 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200565 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200566 // nodeOpts are the cluster member nodes' mutable launch options, kept here
567 // to facilitate reboots.
568 nodeOpts []NodeOptions
569 // launchDir points at the directory keeping the nodes' state, such as storage
570 // images, firmware variable files, TPM state.
571 launchDir string
572 // socketDir points at the directory keeping UNIX socket files, such as these
573 // used to facilitate communication between QEMU and swtpm. It's different
574 // from launchDir, and anchored nearer the file system root, due to the
575 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100576 socketDir string
577 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200578
Lorenz Brun276a7462023-07-12 21:28:54 +0200579 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200580 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200581 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200582
583 // authClient is a cached authenticated owner connection to a Curator
584 // instance within the cluster.
585 authClient *grpc.ClientConn
586
587 // ctxT is the context individual node contexts are created from.
588 ctxT context.Context
589 // ctxC is used by Close to cancel the context under which the nodes are
590 // running.
591 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200592}
593
594// NodeInCluster represents information about a node that's part of a Cluster.
595type NodeInCluster struct {
596 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200597 ID string
598 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200599 // Address of the node on the network ran by nanoswitch. Not reachable from the
600 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
601 // on Cluster.Ports[SOCKSPort]).
602 ManagementAddress string
603}
604
605// firstConnection performs the initial owner credential escrow with a newly
606// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
607// running at 10.1.0.2, which is always the case with the current nanoswitch
608// implementation.
609//
Leopold20a036e2023-01-15 00:17:19 +0100610// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200611// information as NodeInCluster.
612func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
613 // Dial external service.
614 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100615 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200616 if err != nil {
617 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
618 }
619 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
620 return socksDialer.Dial("tcp", addr)
621 }
622 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
623 if err != nil {
624 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
625 }
626 defer initClient.Close()
627
628 // Retrieve owner certificate - this can take a while because the node is still
629 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100630 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200631 aaa := apb.NewAAAClient(initClient)
632 var cert *tls.Certificate
633 err = backoff.Retry(func() error {
634 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
635 if st, ok := status.FromError(err); ok {
636 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100637 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200638 return err
639 }
640 }
641 return backoff.Permanent(err)
642 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
643 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200644 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200645 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100646 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200647
648 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200649 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200650 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
651 if err != nil {
652 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
653 }
654 defer authClient.Close()
655 mgmt := apb.NewManagementClient(authClient)
656
657 var node *NodeInCluster
658 err = backoff.Retry(func() error {
659 nodes, err := getNodes(ctx, mgmt)
660 if err != nil {
661 return fmt.Errorf("retrieving nodes failed: %w", err)
662 }
663 if len(nodes) != 1 {
664 return fmt.Errorf("expected one node, got %d", len(nodes))
665 }
666 n := nodes[0]
667 if n.Status == nil || n.Status.ExternalAddress == "" {
668 return fmt.Errorf("node has no status and/or address")
669 }
670 node = &NodeInCluster{
671 ID: identity.NodeID(n.Pubkey),
672 ManagementAddress: n.Status.ExternalAddress,
673 }
674 return nil
675 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
676 if err != nil {
677 return nil, nil, err
678 }
679
680 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200681}
682
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100683func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200684 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100685 if err != nil {
686 return nil, err
687 }
688 return f, nil
689}
690
Serge Bazanski66e58952021-10-05 17:06:56 +0200691// LaunchCluster launches a cluster of Metropolis node VMs together with a
692// Nanoswitch instance to network them all together.
693//
694// The given context will be used to run all qemu instances in the cluster, and
695// canceling the context or calling Close() will terminate them.
696func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200697 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200698 return nil, errors.New("refusing to start cluster with zero nodes")
699 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200700
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200701 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100702 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200703 if err != nil {
704 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
705 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100706 // Create the metroctl config directory. We keep it in /tmp because in some
707 // scenarios it's end-user visible and we want it short.
708 md, err := os.MkdirTemp("/tmp", "metroctl-*")
709 if err != nil {
710 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
711 }
712
713 // Create the socket directory. We keep it in /tmp because of socket path limits.
714 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200715 if err != nil {
716 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
717 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200718
719 // Prepare links between nodes and nanoswitch.
720 var switchPorts []*os.File
721 var vmPorts []*os.File
722 for i := 0; i < opts.NumNodes; i++ {
723 switchPort, vmPort, err := launch.NewSocketPair()
724 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200725 return nil, fmt.Errorf("failed to get socketpair: %w", err)
726 }
727 switchPorts = append(switchPorts, switchPort)
728 vmPorts = append(vmPorts, vmPort)
729 }
730
Serge Bazanskie78a0892021-10-07 17:03:49 +0200731 // Make a list of channels that will be populated by all running node qemu
732 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200733 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200734 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200735 done[i] = make(chan error, 1)
736 }
737
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200738 // Prepare the node options. These will be kept as part of Cluster.
739 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
740 // launch. The runtime information can be later used to restart a node.
741 // The 0th node will be initialized first. The rest will follow after it
742 // had bootstrapped the cluster.
743 nodeOpts := make([]NodeOptions, opts.NumNodes)
744 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100745 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200746 ConnectToSocket: vmPorts[0],
747 NodeParameters: &apb.NodeParameters{
748 Cluster: &apb.NodeParameters_ClusterBootstrap_{
749 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
750 OwnerPublicKey: InsecurePublicKey,
Serge Bazanski66e58952021-10-05 17:06:56 +0200751 },
752 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200753 },
754 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100755 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200756 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100757 if opts.NodeLogsToFiles {
758 path := path.Join(ld, "node-1.txt")
759 port, err := NewSerialFileLogger(path)
760 if err != nil {
761 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
762 }
763 launch.Log("Node 1 logs at %s", path)
764 nodeOpts[0].SerialPort = port
765 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200766
767 // Start the first node.
768 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100769 launch.Log("Cluster: Starting node %d...", 1)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200770 go func() {
771 err := LaunchNode(ctxT, ld, sd, &nodeOpts[0])
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200772 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100773 launch.Log("Node %d finished with an error: %v", 1, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200774 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200775 done[0] <- err
776 }()
777
Lorenz Brun150f24a2023-07-13 20:11:06 +0200778 localRegistryAddr := net.TCPAddr{
779 IP: net.IPv4(10, 42, 0, 82),
780 Port: 5000,
781 }
782
783 var guestSvcMap launch.GuestServiceMap
784 if opts.LocalRegistry != nil {
785 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
786 if err != nil {
787 ctxC()
788 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
789 }
790 s := http.Server{
791 Handler: opts.LocalRegistry,
792 }
793 go s.Serve(l)
794 go func() {
795 <-ctxT.Done()
796 s.Close()
797 }()
798 guestSvcMap = launch.GuestServiceMap{
799 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
800 }
801 }
802
Serge Bazanskie78a0892021-10-07 17:03:49 +0200803 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200804 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
805 if err != nil {
806 ctxC()
807 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
808 }
809
810 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100811 var serialPort io.ReadWriter
812 if opts.NodeLogsToFiles {
813 path := path.Join(ld, "nanoswitch.txt")
814 serialPort, err = NewSerialFileLogger(path)
815 if err != nil {
816 launch.Log("Could not open log file for nanoswitch: %v", err)
817 }
818 launch.Log("Nanoswitch logs at %s", path)
819 } else {
820 serialPort = newPrefixedStdio(99)
821 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200822 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100823 Name: "nanoswitch",
Serge Bazanski66e58952021-10-05 17:06:56 +0200824 KernelPath: "metropolis/test/ktest/vmlinux",
Lorenz Brun62f1d362023-11-14 16:18:24 +0100825 InitramfsPath: "metropolis/test/nanoswitch/initramfs.cpio.zst",
Serge Bazanski66e58952021-10-05 17:06:56 +0200826 ExtraNetworkInterfaces: switchPorts,
827 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200828 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100829 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100830 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200831 }); err != nil {
832 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100833 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200834 }
835 }
836 }()
837
Serge Bazanskibe742842022-04-04 13:18:50 +0200838 // Build SOCKS dialer.
839 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
840 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200841 if err != nil {
842 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200843 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200844 }
845
Serge Bazanskibe742842022-04-04 13:18:50 +0200846 // Retrieve owner credentials and first node.
847 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200848 if err != nil {
849 ctxC()
850 return nil, err
851 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200852
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100853 // Write credentials to the metroctl directory.
854 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
855 ctxC()
856 return nil, fmt.Errorf("could not write owner key: %w", err)
857 }
858 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
859 ctxC()
860 return nil, fmt.Errorf("could not write owner certificate: %w", err)
861 }
862
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200863 // Set up a partially initialized cluster instance, to be filled in in the
864 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200865 cluster := &Cluster{
866 Owner: *cert,
867 Ports: portMap,
868 Nodes: map[string]*NodeInCluster{
869 firstNode.ID: firstNode,
870 },
871 NodeIDs: []string{
872 firstNode.ID,
873 },
874
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100875 nodesDone: done,
876 nodeOpts: nodeOpts,
877 launchDir: ld,
878 socketDir: sd,
879 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200880
Lorenz Brun276a7462023-07-12 21:28:54 +0200881 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200882
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200883 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200884 ctxC: ctxC,
885 }
886
887 // Now start the rest of the nodes and register them into the cluster.
888
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200889 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200890 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200891 if err != nil {
892 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200893 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200894 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200895 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200896
897 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100898 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200899 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
900 if err != nil {
901 ctxC()
902 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
903 }
904 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100905 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200906
907 // Retrieve cluster info (for directory and ca public key) to register further
908 // nodes.
909 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
910 if err != nil {
911 ctxC()
912 return nil, fmt.Errorf("GetClusterInfo: %w", err)
913 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200914 caCert, err := x509.ParseCertificate(resI.CaCertificate)
915 if err != nil {
916 ctxC()
917 return nil, fmt.Errorf("ParseCertificate: %w", err)
918 }
919 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200920
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200921 // Use the retrieved information to configure the rest of the node options.
922 for i := 1; i < opts.NumNodes; i++ {
923 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100924 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200925 ConnectToSocket: vmPorts[i],
926 NodeParameters: &apb.NodeParameters{
927 Cluster: &apb.NodeParameters_ClusterRegister_{
928 ClusterRegister: &apb.NodeParameters_ClusterRegister{
929 RegisterTicket: ticket,
930 ClusterDirectory: resI.ClusterDirectory,
931 CaCertificate: resI.CaCertificate,
932 },
933 },
934 },
935 SerialPort: newPrefixedStdio(i),
936 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100937 if opts.NodeLogsToFiles {
938 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
939 port, err := NewSerialFileLogger(path)
940 if err != nil {
941 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
942 }
943 launch.Log("Node %d logs at %s", i+1, path)
944 nodeOpts[i].SerialPort = port
945 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200946 }
947
948 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200949 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100950 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200951 go func(i int) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200952 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i])
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200953 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100954 launch.Log("Node %d finished with an error: %v", i, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200955 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200956 done[i] <- err
957 }(i)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200958 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200959
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200960 seenNodes := make(map[string]bool)
961 launch.Log("Cluster: waiting for nodes to appear as NEW...")
962 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200963 for {
964 nodes, err := getNodes(ctx, mgmt)
965 if err != nil {
966 ctxC()
967 return nil, fmt.Errorf("could not get nodes: %w", err)
968 }
969 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200970 if n.State != cpb.NodeState_NODE_STATE_NEW {
971 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200972 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100973 if seenNodes[n.Id] {
974 continue
975 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200976 seenNodes[n.Id] = true
977 cluster.Nodes[n.Id] = &NodeInCluster{
978 ID: n.Id,
979 Pubkey: n.Pubkey,
980 }
981 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200982 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200983
984 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200985 break
986 }
987 time.Sleep(1 * time.Second)
988 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200989 }
990 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200991
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200992 approvedNodes := make(map[string]bool)
993 upNodes := make(map[string]bool)
994 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200995 for {
996 nodes, err := getNodes(ctx, mgmt)
997 if err != nil {
998 ctxC()
999 return nil, fmt.Errorf("could not get nodes: %w", err)
1000 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001001 for _, node := range nodes {
1002 if !seenNodes[node.Id] {
1003 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001004 continue
1005 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001006
1007 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1008 launch.Log("Cluster: node %s is up", node.Id)
1009 upNodes[node.Id] = true
1010 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001011 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001012 if upNodes[node.Id] {
1013 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001014 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001015
1016 if !approvedNodes[node.Id] {
1017 launch.Log("Cluster: approving node %s", node.Id)
1018 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1019 Pubkey: node.Pubkey,
1020 })
1021 if err != nil {
1022 ctxC()
1023 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1024 }
1025 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001026 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001027 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001028
1029 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1030 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001031 break
1032 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001033 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001034 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001035 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001036
Serge Bazanski05f813b2023-03-16 17:58:39 +01001037 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001038 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001039 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001040 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001041 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001042
Serge Bazanskibe742842022-04-04 13:18:50 +02001043 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001044}
1045
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001046// RebootNode reboots the cluster member node matching the given index, and
1047// waits for it to rejoin the cluster. It will use the given context ctx to run
1048// cluster API requests, whereas the resulting QEMU process will be created
1049// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1050func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1051 if idx < 0 || idx >= len(c.NodeIDs) {
1052 return fmt.Errorf("index out of bounds.")
1053 }
1054 id := c.NodeIDs[idx]
1055
1056 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001057 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001058 if err != nil {
1059 return err
1060 }
1061 mgmt := apb.NewManagementClient(curC)
1062
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001063 // Cancel the node's context. This will shut down QEMU.
1064 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001065 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001066 err = <-c.nodesDone[idx]
1067 if err != nil {
1068 return fmt.Errorf("while restarting node: %w", err)
1069 }
1070
1071 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001072 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001073 go func(n int) {
1074 err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[n])
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001075 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001076 launch.Log("Node %d finished with an error: %v", n, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001077 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001078 c.nodesDone[n] <- err
1079 }(idx)
1080
Serge Bazanskibc969572024-03-21 11:56:13 +01001081 start := time.Now()
1082
1083 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001084 for {
1085 cs, err := getNode(ctx, mgmt, id)
1086 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001087 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001088 return err
1089 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001090 launch.Log("Cluster: node health: %+v", cs.Health)
1091
1092 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1093 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001094 break
1095 }
1096 time.Sleep(time.Second)
1097 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001098 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001099 return nil
1100}
1101
1102// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001103// nodes to stop. It returns an error if stopping the nodes failed, or one of
1104// the nodes failed to fully start in the first place.
1105func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001106 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001107 if c.authClient != nil {
1108 c.authClient.Close()
1109 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001110 c.ctxC()
1111
Leopold20a036e2023-01-15 00:17:19 +01001112 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001113 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001114 for _, c := range c.nodesDone {
1115 err := <-c
1116 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001117 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001118 }
1119 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001120 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001121 os.RemoveAll(c.launchDir)
1122 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001123 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001124 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001125 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001126}
Serge Bazanskibe742842022-04-04 13:18:50 +02001127
1128// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1129// their ID. This is performed by connecting to the cluster nanoswitch via its
1130// SOCKS proxy, and using the cluster node list for name resolution.
1131//
1132// For example:
1133//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001134// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001135func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1136 host, port, err := net.SplitHostPort(addr)
1137 if err != nil {
1138 return nil, fmt.Errorf("invalid host:port: %w", err)
1139 }
1140 // Already an IP address?
1141 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001142 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001143 }
1144
1145 // Otherwise, expect a node name.
1146 node, ok := c.Nodes[host]
1147 if !ok {
1148 return nil, fmt.Errorf("unknown node %q", host)
1149 }
1150 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001151 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001152}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001153
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001154// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1155// Kubernetes authenticating proxy using the cluster owner identity.
1156// It currently has access to everything (i.e. the cluster-admin role)
1157// via the owner-admin binding.
1158func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1159 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1160 if err != nil {
1161 // We explicitly pass an Ed25519 private key in, so this can't happen
1162 panic(err)
1163 }
1164
1165 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001166 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001167 Host: host,
1168 TLSClientConfig: rest.TLSClientConfig{
1169 // TODO(q3k): use CA certificate
1170 Insecure: true,
1171 ServerName: "kubernetes.default.svc",
1172 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1173 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1174 },
1175 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1176 return c.DialNode(ctx, address)
1177 },
1178 }
1179 return kubernetes.NewForConfig(&clientConfig)
1180}
1181
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001182// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1183// which are currently Kubernetes controllers, ie. run an apiserver. This list
1184// might be empty if no node is currently configured with the
1185// 'KubernetesController' node.
1186func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1187 curC, err := c.CuratorClient()
1188 if err != nil {
1189 return nil, err
1190 }
1191 mgmt := apb.NewManagementClient(curC)
1192 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1193 Filter: "has(node.roles.kubernetes_controller)",
1194 })
1195 if err != nil {
1196 return nil, err
1197 }
1198 defer srv.CloseSend()
1199 var res []string
1200 for {
1201 n, err := srv.Recv()
1202 if err == io.EOF {
1203 break
1204 }
1205 if err != nil {
1206 return nil, err
1207 }
1208 if n.Status == nil || n.Status.ExternalAddress == "" {
1209 continue
1210 }
1211 res = append(res, n.Status.ExternalAddress)
1212 }
1213 return res, nil
1214}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001215
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001216// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1217// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001218func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1219 // Get an authenticated owner client within the cluster.
1220 curC, err := c.CuratorClient()
1221 if err != nil {
1222 return err
1223 }
1224 mgmt := apb.NewManagementClient(curC)
1225 nodes, err := getNodes(ctx, mgmt)
1226 if err != nil {
1227 return err
1228 }
1229
1230 var unhealthy []string
1231 for _, node := range nodes {
1232 if node.Health == apb.Node_HEALTHY {
1233 continue
1234 }
1235 unhealthy = append(unhealthy, node.Id)
1236 }
1237 if len(unhealthy) == 0 {
1238 return nil
1239 }
1240 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1241}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001242
1243// ApproveNode approves a node by ID, waiting for it to become UP.
1244func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1245 curC, err := c.CuratorClient()
1246 if err != nil {
1247 return err
1248 }
1249 mgmt := apb.NewManagementClient(curC)
1250
1251 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1252 Pubkey: c.Nodes[id].Pubkey,
1253 })
1254 if err != nil {
1255 return fmt.Errorf("ApproveNode: %w", err)
1256 }
1257 launch.Log("Cluster: %s: approved, waiting for UP", id)
1258 for {
1259 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1260 if err != nil {
1261 return fmt.Errorf("GetNodes: %w", err)
1262 }
1263 found := false
1264 for {
1265 node, err := nodes.Recv()
1266 if errors.Is(err, io.EOF) {
1267 break
1268 }
1269 if err != nil {
1270 return fmt.Errorf("Nodes.Recv: %w", err)
1271 }
1272 if node.Id != id {
1273 continue
1274 }
1275 if node.State != cpb.NodeState_NODE_STATE_UP {
1276 continue
1277 }
1278 found = true
1279 break
1280 }
1281 nodes.CloseSend()
1282
1283 if found {
1284 break
1285 }
1286 time.Sleep(time.Second)
1287 }
1288 launch.Log("Cluster: %s: UP", id)
1289 return nil
1290}
1291
1292// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1293func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1294 curC, err := c.CuratorClient()
1295 if err != nil {
1296 return err
1297 }
1298 mgmt := apb.NewManagementClient(curC)
1299
1300 tr := true
1301 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1302 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1303 Node: &apb.UpdateNodeRolesRequest_Id{
1304 Id: id,
1305 },
1306 KubernetesWorker: &tr,
1307 })
1308 return err
1309}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001310
1311// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1312func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1313 curC, err := c.CuratorClient()
1314 if err != nil {
1315 return err
1316 }
1317 mgmt := apb.NewManagementClient(curC)
1318 cur := ipb.NewCuratorClient(curC)
1319
1320 tr := true
1321 launch.Log("Cluster: %s: adding ConsensusMember", id)
1322 bo := backoff.NewExponentialBackOff()
1323 bo.MaxElapsedTime = 10 * time.Second
1324
1325 backoff.Retry(func() error {
1326 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1327 Node: &apb.UpdateNodeRolesRequest_Id{
1328 Id: id,
1329 },
1330 ConsensusMember: &tr,
1331 })
1332 if err != nil {
1333 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1334 }
1335 return err
1336 }, backoff.WithContext(bo, ctx))
1337 if err != nil {
1338 return err
1339 }
1340
1341 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1342
1343 learner := false
1344 for {
1345 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1346 if err != nil {
1347 return fmt.Errorf("GetConsensusStatus: %w", err)
1348 }
1349 for _, member := range res.EtcdMember {
1350 if member.Id != id {
1351 continue
1352 }
1353 switch member.Status {
1354 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1355 if !learner {
1356 learner = true
1357 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1358 }
1359 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1360 launch.Log("Cluster: %s: became a full member", id)
1361 return nil
1362 }
1363 }
1364 time.Sleep(100 * time.Millisecond)
1365 }
1366}