blob: f1b4166650dbd47fb10bb689dd8a518e56371561 [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 Bazanskie84726b2024-04-17 16:32:32 +0200822 kernelPath, err := runfiles.Rlocation("_main/metropolis/test/ktest/vmlinux")
823 if err != nil {
824 launch.Fatal("Failed to resolved nanoswitch kernel: %v", err)
825 }
826 initramfsPath, err := runfiles.Rlocation("_main/metropolis/test/nanoswitch/initramfs.cpio.zst")
827 if err != nil {
828 launch.Fatal("Failed to resolved nanoswitch initramfs: %v", err)
829 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200830 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100831 Name: "nanoswitch",
Serge Bazanskie84726b2024-04-17 16:32:32 +0200832 KernelPath: kernelPath,
833 InitramfsPath: initramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200834 ExtraNetworkInterfaces: switchPorts,
835 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200836 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100837 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100838 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200839 }); err != nil {
840 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100841 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200842 }
843 }
844 }()
845
Serge Bazanskibe742842022-04-04 13:18:50 +0200846 // Build SOCKS dialer.
847 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
848 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200849 if err != nil {
850 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200851 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200852 }
853
Serge Bazanskibe742842022-04-04 13:18:50 +0200854 // Retrieve owner credentials and first node.
855 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200856 if err != nil {
857 ctxC()
858 return nil, err
859 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200860
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100861 // Write credentials to the metroctl directory.
862 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
863 ctxC()
864 return nil, fmt.Errorf("could not write owner key: %w", err)
865 }
866 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
867 ctxC()
868 return nil, fmt.Errorf("could not write owner certificate: %w", err)
869 }
870
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200871 // Set up a partially initialized cluster instance, to be filled in in the
872 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200873 cluster := &Cluster{
874 Owner: *cert,
875 Ports: portMap,
876 Nodes: map[string]*NodeInCluster{
877 firstNode.ID: firstNode,
878 },
879 NodeIDs: []string{
880 firstNode.ID,
881 },
882
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100883 nodesDone: done,
884 nodeOpts: nodeOpts,
885 launchDir: ld,
886 socketDir: sd,
887 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200888
Lorenz Brun276a7462023-07-12 21:28:54 +0200889 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200890
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200891 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200892 ctxC: ctxC,
893 }
894
895 // Now start the rest of the nodes and register them into the cluster.
896
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200897 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200898 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200899 if err != nil {
900 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200901 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200902 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200903 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200904
905 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100906 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200907 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
908 if err != nil {
909 ctxC()
910 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
911 }
912 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100913 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200914
915 // Retrieve cluster info (for directory and ca public key) to register further
916 // nodes.
917 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
918 if err != nil {
919 ctxC()
920 return nil, fmt.Errorf("GetClusterInfo: %w", err)
921 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200922 caCert, err := x509.ParseCertificate(resI.CaCertificate)
923 if err != nil {
924 ctxC()
925 return nil, fmt.Errorf("ParseCertificate: %w", err)
926 }
927 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200928
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200929 // Use the retrieved information to configure the rest of the node options.
930 for i := 1; i < opts.NumNodes; i++ {
931 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100932 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200933 ConnectToSocket: vmPorts[i],
934 NodeParameters: &apb.NodeParameters{
935 Cluster: &apb.NodeParameters_ClusterRegister_{
936 ClusterRegister: &apb.NodeParameters_ClusterRegister{
937 RegisterTicket: ticket,
938 ClusterDirectory: resI.ClusterDirectory,
939 CaCertificate: resI.CaCertificate,
940 },
941 },
942 },
943 SerialPort: newPrefixedStdio(i),
944 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100945 if opts.NodeLogsToFiles {
946 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
947 port, err := NewSerialFileLogger(path)
948 if err != nil {
949 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
950 }
951 launch.Log("Node %d logs at %s", i+1, path)
952 nodeOpts[i].SerialPort = port
953 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200954 }
955
956 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200957 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100958 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200959 go func(i int) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200960 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i])
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200961 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100962 launch.Log("Node %d finished with an error: %v", i, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +0200963 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200964 done[i] <- err
965 }(i)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200966 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200967
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200968 seenNodes := make(map[string]bool)
969 launch.Log("Cluster: waiting for nodes to appear as NEW...")
970 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200971 for {
972 nodes, err := getNodes(ctx, mgmt)
973 if err != nil {
974 ctxC()
975 return nil, fmt.Errorf("could not get nodes: %w", err)
976 }
977 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200978 if n.State != cpb.NodeState_NODE_STATE_NEW {
979 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200980 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100981 if seenNodes[n.Id] {
982 continue
983 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200984 seenNodes[n.Id] = true
985 cluster.Nodes[n.Id] = &NodeInCluster{
986 ID: n.Id,
987 Pubkey: n.Pubkey,
988 }
989 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200990 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200991
992 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200993 break
994 }
995 time.Sleep(1 * time.Second)
996 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200997 }
998 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200999
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001000 approvedNodes := make(map[string]bool)
1001 upNodes := make(map[string]bool)
1002 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001003 for {
1004 nodes, err := getNodes(ctx, mgmt)
1005 if err != nil {
1006 ctxC()
1007 return nil, fmt.Errorf("could not get nodes: %w", err)
1008 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001009 for _, node := range nodes {
1010 if !seenNodes[node.Id] {
1011 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001012 continue
1013 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001014
1015 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1016 launch.Log("Cluster: node %s is up", node.Id)
1017 upNodes[node.Id] = true
1018 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001019 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001020 if upNodes[node.Id] {
1021 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001022 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001023
1024 if !approvedNodes[node.Id] {
1025 launch.Log("Cluster: approving node %s", node.Id)
1026 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1027 Pubkey: node.Pubkey,
1028 })
1029 if err != nil {
1030 ctxC()
1031 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1032 }
1033 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001034 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001035 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001036
1037 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1038 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001039 break
1040 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001041 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001042 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001043 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001044
Serge Bazanski05f813b2023-03-16 17:58:39 +01001045 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001046 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001047 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001048 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001049 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001050
Serge Bazanskibe742842022-04-04 13:18:50 +02001051 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001052}
1053
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001054// RebootNode reboots the cluster member node matching the given index, and
1055// waits for it to rejoin the cluster. It will use the given context ctx to run
1056// cluster API requests, whereas the resulting QEMU process will be created
1057// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1058func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1059 if idx < 0 || idx >= len(c.NodeIDs) {
1060 return fmt.Errorf("index out of bounds.")
1061 }
1062 id := c.NodeIDs[idx]
1063
1064 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001065 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001066 if err != nil {
1067 return err
1068 }
1069 mgmt := apb.NewManagementClient(curC)
1070
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001071 // Cancel the node's context. This will shut down QEMU.
1072 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001073 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001074 err = <-c.nodesDone[idx]
1075 if err != nil {
1076 return fmt.Errorf("while restarting node: %w", err)
1077 }
1078
1079 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001080 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001081 go func(n int) {
1082 err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[n])
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001083 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001084 launch.Log("Node %d finished with an error: %v", n, err)
Mateusz Zalega08cb4642022-05-25 17:35:59 +02001085 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001086 c.nodesDone[n] <- err
1087 }(idx)
1088
Serge Bazanskibc969572024-03-21 11:56:13 +01001089 start := time.Now()
1090
1091 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001092 for {
1093 cs, err := getNode(ctx, mgmt, id)
1094 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001095 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001096 return err
1097 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001098 launch.Log("Cluster: node health: %+v", cs.Health)
1099
1100 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1101 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001102 break
1103 }
1104 time.Sleep(time.Second)
1105 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001106 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001107 return nil
1108}
1109
1110// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001111// nodes to stop. It returns an error if stopping the nodes failed, or one of
1112// the nodes failed to fully start in the first place.
1113func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001114 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001115 if c.authClient != nil {
1116 c.authClient.Close()
1117 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001118 c.ctxC()
1119
Leopold20a036e2023-01-15 00:17:19 +01001120 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001121 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001122 for _, c := range c.nodesDone {
1123 err := <-c
1124 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001125 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001126 }
1127 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001128 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001129 os.RemoveAll(c.launchDir)
1130 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001131 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001132 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001133 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001134}
Serge Bazanskibe742842022-04-04 13:18:50 +02001135
1136// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1137// their ID. This is performed by connecting to the cluster nanoswitch via its
1138// SOCKS proxy, and using the cluster node list for name resolution.
1139//
1140// For example:
1141//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001142// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001143func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1144 host, port, err := net.SplitHostPort(addr)
1145 if err != nil {
1146 return nil, fmt.Errorf("invalid host:port: %w", err)
1147 }
1148 // Already an IP address?
1149 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001150 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001151 }
1152
1153 // Otherwise, expect a node name.
1154 node, ok := c.Nodes[host]
1155 if !ok {
1156 return nil, fmt.Errorf("unknown node %q", host)
1157 }
1158 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001159 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001160}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001161
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001162// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1163// Kubernetes authenticating proxy using the cluster owner identity.
1164// It currently has access to everything (i.e. the cluster-admin role)
1165// via the owner-admin binding.
1166func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1167 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1168 if err != nil {
1169 // We explicitly pass an Ed25519 private key in, so this can't happen
1170 panic(err)
1171 }
1172
1173 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001174 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001175 Host: host,
1176 TLSClientConfig: rest.TLSClientConfig{
1177 // TODO(q3k): use CA certificate
1178 Insecure: true,
1179 ServerName: "kubernetes.default.svc",
1180 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1181 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1182 },
1183 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1184 return c.DialNode(ctx, address)
1185 },
1186 }
1187 return kubernetes.NewForConfig(&clientConfig)
1188}
1189
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001190// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1191// which are currently Kubernetes controllers, ie. run an apiserver. This list
1192// might be empty if no node is currently configured with the
1193// 'KubernetesController' node.
1194func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1195 curC, err := c.CuratorClient()
1196 if err != nil {
1197 return nil, err
1198 }
1199 mgmt := apb.NewManagementClient(curC)
1200 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1201 Filter: "has(node.roles.kubernetes_controller)",
1202 })
1203 if err != nil {
1204 return nil, err
1205 }
1206 defer srv.CloseSend()
1207 var res []string
1208 for {
1209 n, err := srv.Recv()
1210 if err == io.EOF {
1211 break
1212 }
1213 if err != nil {
1214 return nil, err
1215 }
1216 if n.Status == nil || n.Status.ExternalAddress == "" {
1217 continue
1218 }
1219 res = append(res, n.Status.ExternalAddress)
1220 }
1221 return res, nil
1222}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001223
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001224// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1225// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001226func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1227 // Get an authenticated owner client within the cluster.
1228 curC, err := c.CuratorClient()
1229 if err != nil {
1230 return err
1231 }
1232 mgmt := apb.NewManagementClient(curC)
1233 nodes, err := getNodes(ctx, mgmt)
1234 if err != nil {
1235 return err
1236 }
1237
1238 var unhealthy []string
1239 for _, node := range nodes {
1240 if node.Health == apb.Node_HEALTHY {
1241 continue
1242 }
1243 unhealthy = append(unhealthy, node.Id)
1244 }
1245 if len(unhealthy) == 0 {
1246 return nil
1247 }
1248 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1249}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001250
1251// ApproveNode approves a node by ID, waiting for it to become UP.
1252func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1253 curC, err := c.CuratorClient()
1254 if err != nil {
1255 return err
1256 }
1257 mgmt := apb.NewManagementClient(curC)
1258
1259 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1260 Pubkey: c.Nodes[id].Pubkey,
1261 })
1262 if err != nil {
1263 return fmt.Errorf("ApproveNode: %w", err)
1264 }
1265 launch.Log("Cluster: %s: approved, waiting for UP", id)
1266 for {
1267 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1268 if err != nil {
1269 return fmt.Errorf("GetNodes: %w", err)
1270 }
1271 found := false
1272 for {
1273 node, err := nodes.Recv()
1274 if errors.Is(err, io.EOF) {
1275 break
1276 }
1277 if err != nil {
1278 return fmt.Errorf("Nodes.Recv: %w", err)
1279 }
1280 if node.Id != id {
1281 continue
1282 }
1283 if node.State != cpb.NodeState_NODE_STATE_UP {
1284 continue
1285 }
1286 found = true
1287 break
1288 }
1289 nodes.CloseSend()
1290
1291 if found {
1292 break
1293 }
1294 time.Sleep(time.Second)
1295 }
1296 launch.Log("Cluster: %s: UP", id)
1297 return nil
1298}
1299
1300// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1301func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1302 curC, err := c.CuratorClient()
1303 if err != nil {
1304 return err
1305 }
1306 mgmt := apb.NewManagementClient(curC)
1307
1308 tr := true
1309 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1310 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1311 Node: &apb.UpdateNodeRolesRequest_Id{
1312 Id: id,
1313 },
1314 KubernetesWorker: &tr,
1315 })
1316 return err
1317}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001318
1319// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1320func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1321 curC, err := c.CuratorClient()
1322 if err != nil {
1323 return err
1324 }
1325 mgmt := apb.NewManagementClient(curC)
1326 cur := ipb.NewCuratorClient(curC)
1327
1328 tr := true
1329 launch.Log("Cluster: %s: adding ConsensusMember", id)
1330 bo := backoff.NewExponentialBackOff()
1331 bo.MaxElapsedTime = 10 * time.Second
1332
1333 backoff.Retry(func() error {
1334 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1335 Node: &apb.UpdateNodeRolesRequest_Id{
1336 Id: id,
1337 },
1338 ConsensusMember: &tr,
1339 })
1340 if err != nil {
1341 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1342 }
1343 return err
1344 }, backoff.WithContext(bo, ctx))
1345 if err != nil {
1346 return err
1347 }
1348
1349 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1350
1351 learner := false
1352 for {
1353 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1354 if err != nil {
1355 return fmt.Errorf("GetConsensusStatus: %w", err)
1356 }
1357 for _, member := range res.EtcdMember {
1358 if member.Id != id {
1359 continue
1360 }
1361 switch member.Status {
1362 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1363 if !learner {
1364 learner = true
1365 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1366 }
1367 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1368 launch.Log("Cluster: %s: became a full member", id)
1369 return nil
1370 }
1371 }
1372 time.Sleep(100 * time.Millisecond)
1373 }
1374}