blob: ca9becdb9cc27236c25b51deac5ac84a394239eb [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.
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200229func LaunchNode(ctx context.Context, ld, sd string, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200230 // 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
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200332 tpmd := filepath.Join(r.ld, "tpm")
333 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanski66e58952021-10-05 17:06:56 +0200334 tpmEmuCmd.Stderr = os.Stderr
335 tpmEmuCmd.Stdout = os.Stdout
336
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100337 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200338 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200339 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200340 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) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200351 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200352 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
353 }
354 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200355 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200356 return fmt.Errorf("while waiting for the TPM socket: %w", err)
357 }
358 time.Sleep(time.Millisecond * 100)
359 }
360
Serge Bazanski66e58952021-10-05 17:06:56 +0200361 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200362 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200363 if options.ConnectToSocket != nil {
364 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
365 }
366
367 var stdErrBuf bytes.Buffer
368 systemCmd.Stderr = &stdErrBuf
369 systemCmd.Stdout = options.SerialPort
370
Leopoldaf5086b2023-01-15 14:12:42 +0100371 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
372
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200373 go func() {
374 launch.Log("Node: Starting...")
375 err = systemCmd.Run()
376 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200377
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200378 // Stop TPM emulator and wait for it to exit to properly reap the child process
379 tpmCancel()
380 launch.Log("Node: Waiting for TPM emulator to exit")
381 // Wait returns a SIGKILL error because we just cancelled its context.
382 // We still need to call it to avoid creating zombies.
383 errTpm := tpmEmuCmd.Wait()
384 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200385
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200386 var exerr *exec.ExitError
387 if err != nil && errors.As(err, &exerr) {
388 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
389 if status.Signaled() && status.Signal() == syscall.SIGKILL {
390 // Process was killed externally (most likely by our context being canceled).
391 // This is a normal exit for us, so return nil
392 doneC <- nil
393 return
394 }
395 exerr.Stderr = stdErrBuf.Bytes()
396 newErr := launch.QEMUError(*exerr)
397 launch.Log("Node: %q", stdErrBuf.String())
398 doneC <- &newErr
399 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200400 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200401 doneC <- err
402 }()
403 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200404}
405
406func copyFile(src, dst string) error {
407 in, err := os.Open(src)
408 if err != nil {
409 return fmt.Errorf("when opening source: %w", err)
410 }
411 defer in.Close()
412
413 out, err := os.Create(dst)
414 if err != nil {
415 return fmt.Errorf("when creating destination: %w", err)
416 }
417 defer out.Close()
418
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100419 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200420 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100421 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200422 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100423
424 // Copy the file while preserving its sparseness. The image files are very
425 // sparse (less than 10% allocated), so this is a lot faster.
426 var lastHoleStart int64
427 for {
428 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
429 if err != nil {
430 return fmt.Errorf("when seeking to next data block: %w", err)
431 }
432 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
433 if err != nil {
434 return fmt.Errorf("when seeking to next hole: %w", err)
435 }
436 lastHoleStart = holeStart
437 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
438 return fmt.Errorf("when seeking to current data block: %w", err)
439 }
440 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
441 return fmt.Errorf("when seeking output to next data block: %w", err)
442 }
443 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
444 return fmt.Errorf("when copying file: %w", err)
445 }
446 if endPos == holeStart {
447 // The next hole is at the end of the file, we're done here.
448 break
449 }
450 }
451
Serge Bazanski66e58952021-10-05 17:06:56 +0200452 return out.Close()
453}
454
Serge Bazanskie78a0892021-10-07 17:03:49 +0200455// getNodes wraps around Management.GetNodes to return a list of nodes in a
456// cluster.
457func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200458 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100459 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100460 err := backoff.Retry(func() error {
461 res = nil
462 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200463 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100464 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200465 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100466 for {
467 node, err := srvN.Recv()
468 if err == io.EOF {
469 break
470 }
471 if err != nil {
472 return fmt.Errorf("GetNodes.Recv: %w", err)
473 }
474 res = append(res, node)
475 }
476 return nil
477 }, bo)
478 if err != nil {
479 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200480 }
481 return res, nil
482}
483
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200484// getNode wraps Management.GetNodes. It returns node information matching
485// given node ID.
486func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
487 nodes, err := getNodes(ctx, mgmt)
488 if err != nil {
489 return nil, fmt.Errorf("could not get nodes: %w", err)
490 }
491 for _, n := range nodes {
492 eid := identity.NodeID(n.Pubkey)
493 if eid != id {
494 continue
495 }
496 return n, nil
497 }
498 return nil, fmt.Errorf("no such node.")
499}
500
Serge Bazanski66e58952021-10-05 17:06:56 +0200501// Gets a random EUI-48 Ethernet MAC address
502func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
503 macBuf := make([]byte, 6)
504 _, err := rand.Read(macBuf)
505 if err != nil {
506 return nil, fmt.Errorf("failed to read randomness for MAC: %v", err)
507 }
508
509 // Set U/L bit and clear I/G bit (locally administered individual MAC)
510 // Ref IEEE 802-2014 Section 8.2.2
511 macBuf[0] = (macBuf[0] | 2) & 0xfe
512 mac := net.HardwareAddr(macBuf)
513 return &mac, nil
514}
515
Serge Bazanskibe742842022-04-04 13:18:50 +0200516const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200517
Serge Bazanskibe742842022-04-04 13:18:50 +0200518// ClusterPorts contains all ports handled by Nanoswitch.
519var ClusterPorts = []uint16{
520 // Forwarded to the first node.
521 uint16(node.CuratorServicePort),
522 uint16(node.DebugServicePort),
523 uint16(node.KubernetesAPIPort),
524 uint16(node.KubernetesAPIWrappedPort),
525
526 // SOCKS proxy to the switch network
527 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200528}
529
530// ClusterOptions contains all options for launching a Metropolis cluster.
531type ClusterOptions struct {
532 // The number of nodes this cluster should be started with.
533 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100534
535 // If true, node logs will be saved to individual files instead of being printed
536 // out to stderr. The path of these files will be still printed to stdout.
537 //
538 // The files will be located within the launch directory inside TEST_TMPDIR (or
539 // the default tempdir location, if not set).
540 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200541
542 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
543 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
544 // incomplete.
545 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200546
547 // Optional local registry which will be made available to the cluster to
548 // pull images from. This is a more efficient alternative to preseeding all
549 // images used for testing.
550 LocalRegistry *localregistry.Server
Serge Bazanski66e58952021-10-05 17:06:56 +0200551}
552
553// Cluster is the running Metropolis cluster launched using the LaunchCluster
554// function.
555type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200556 // Owner is the TLS Certificate of the owner of the test cluster. This can be
557 // used to authenticate further clients to the running cluster.
558 Owner tls.Certificate
559 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200560 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200561 Ports launch.PortMap
562
Serge Bazanskibe742842022-04-04 13:18:50 +0200563 // Nodes is a map from Node ID to its runtime information.
564 Nodes map[string]*NodeInCluster
565 // NodeIDs is a list of node IDs that are backing this cluster, in order of
566 // creation.
567 NodeIDs []string
568
Serge Bazanski54e212a2023-06-14 13:45:11 +0200569 // CACertificate is the cluster's CA certificate.
570 CACertificate *x509.Certificate
571
Serge Bazanski66e58952021-10-05 17:06:56 +0200572 // nodesDone is a list of channels populated with the return codes from all the
573 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100574 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200575 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200576 // nodeOpts are the cluster member nodes' mutable launch options, kept here
577 // to facilitate reboots.
578 nodeOpts []NodeOptions
579 // launchDir points at the directory keeping the nodes' state, such as storage
580 // images, firmware variable files, TPM state.
581 launchDir string
582 // socketDir points at the directory keeping UNIX socket files, such as these
583 // used to facilitate communication between QEMU and swtpm. It's different
584 // from launchDir, and anchored nearer the file system root, due to the
585 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100586 socketDir string
587 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200588
Lorenz Brun276a7462023-07-12 21:28:54 +0200589 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200590 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200591 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200592
593 // authClient is a cached authenticated owner connection to a Curator
594 // instance within the cluster.
595 authClient *grpc.ClientConn
596
597 // ctxT is the context individual node contexts are created from.
598 ctxT context.Context
599 // ctxC is used by Close to cancel the context under which the nodes are
600 // running.
601 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200602}
603
604// NodeInCluster represents information about a node that's part of a Cluster.
605type NodeInCluster struct {
606 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200607 ID string
608 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200609 // Address of the node on the network ran by nanoswitch. Not reachable from the
610 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
611 // on Cluster.Ports[SOCKSPort]).
612 ManagementAddress string
613}
614
615// firstConnection performs the initial owner credential escrow with a newly
616// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
617// running at 10.1.0.2, which is always the case with the current nanoswitch
618// implementation.
619//
Leopold20a036e2023-01-15 00:17:19 +0100620// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200621// information as NodeInCluster.
622func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
623 // Dial external service.
624 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100625 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200626 if err != nil {
627 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
628 }
629 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
630 return socksDialer.Dial("tcp", addr)
631 }
632 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
633 if err != nil {
634 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
635 }
636 defer initClient.Close()
637
638 // Retrieve owner certificate - this can take a while because the node is still
639 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100640 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200641 aaa := apb.NewAAAClient(initClient)
642 var cert *tls.Certificate
643 err = backoff.Retry(func() error {
644 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
645 if st, ok := status.FromError(err); ok {
646 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100647 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200648 return err
649 }
650 }
651 return backoff.Permanent(err)
652 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
653 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200654 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200655 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100656 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200657
658 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200659 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200660 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
661 if err != nil {
662 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
663 }
664 defer authClient.Close()
665 mgmt := apb.NewManagementClient(authClient)
666
667 var node *NodeInCluster
668 err = backoff.Retry(func() error {
669 nodes, err := getNodes(ctx, mgmt)
670 if err != nil {
671 return fmt.Errorf("retrieving nodes failed: %w", err)
672 }
673 if len(nodes) != 1 {
674 return fmt.Errorf("expected one node, got %d", len(nodes))
675 }
676 n := nodes[0]
677 if n.Status == nil || n.Status.ExternalAddress == "" {
678 return fmt.Errorf("node has no status and/or address")
679 }
680 node = &NodeInCluster{
681 ID: identity.NodeID(n.Pubkey),
682 ManagementAddress: n.Status.ExternalAddress,
683 }
684 return nil
685 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
686 if err != nil {
687 return nil, nil, err
688 }
689
690 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200691}
692
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100693func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200694 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100695 if err != nil {
696 return nil, err
697 }
698 return f, nil
699}
700
Serge Bazanski66e58952021-10-05 17:06:56 +0200701// LaunchCluster launches a cluster of Metropolis node VMs together with a
702// Nanoswitch instance to network them all together.
703//
704// The given context will be used to run all qemu instances in the cluster, and
705// canceling the context or calling Close() will terminate them.
706func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200707 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200708 return nil, errors.New("refusing to start cluster with zero nodes")
709 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200710
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200711 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100712 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200713 if err != nil {
714 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
715 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100716 // Create the metroctl config directory. We keep it in /tmp because in some
717 // scenarios it's end-user visible and we want it short.
718 md, err := os.MkdirTemp("/tmp", "metroctl-*")
719 if err != nil {
720 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
721 }
722
723 // Create the socket directory. We keep it in /tmp because of socket path limits.
724 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200725 if err != nil {
726 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
727 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200728
729 // Prepare links between nodes and nanoswitch.
730 var switchPorts []*os.File
731 var vmPorts []*os.File
732 for i := 0; i < opts.NumNodes; i++ {
733 switchPort, vmPort, err := launch.NewSocketPair()
734 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200735 return nil, fmt.Errorf("failed to get socketpair: %w", err)
736 }
737 switchPorts = append(switchPorts, switchPort)
738 vmPorts = append(vmPorts, vmPort)
739 }
740
Serge Bazanskie78a0892021-10-07 17:03:49 +0200741 // Make a list of channels that will be populated by all running node qemu
742 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200743 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200744 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200745 done[i] = make(chan error, 1)
746 }
747
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200748 // Prepare the node options. These will be kept as part of Cluster.
749 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
750 // launch. The runtime information can be later used to restart a node.
751 // The 0th node will be initialized first. The rest will follow after it
752 // had bootstrapped the cluster.
753 nodeOpts := make([]NodeOptions, opts.NumNodes)
754 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100755 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200756 ConnectToSocket: vmPorts[0],
757 NodeParameters: &apb.NodeParameters{
758 Cluster: &apb.NodeParameters_ClusterBootstrap_{
759 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
760 OwnerPublicKey: InsecurePublicKey,
Serge Bazanski66e58952021-10-05 17:06:56 +0200761 },
762 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200763 },
764 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100765 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200766 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100767 if opts.NodeLogsToFiles {
768 path := path.Join(ld, "node-1.txt")
769 port, err := NewSerialFileLogger(path)
770 if err != nil {
771 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
772 }
773 launch.Log("Node 1 logs at %s", path)
774 nodeOpts[0].SerialPort = port
775 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200776
777 // Start the first node.
778 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100779 launch.Log("Cluster: Starting node %d...", 1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200780 if err := LaunchNode(ctxT, ld, sd, &nodeOpts[0], done[0]); err != nil {
781 ctxC()
782 return nil, fmt.Errorf("failed to launch first node: %w", err)
783 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200784
Lorenz Brun150f24a2023-07-13 20:11:06 +0200785 localRegistryAddr := net.TCPAddr{
786 IP: net.IPv4(10, 42, 0, 82),
787 Port: 5000,
788 }
789
790 var guestSvcMap launch.GuestServiceMap
791 if opts.LocalRegistry != nil {
792 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
793 if err != nil {
794 ctxC()
795 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
796 }
797 s := http.Server{
798 Handler: opts.LocalRegistry,
799 }
800 go s.Serve(l)
801 go func() {
802 <-ctxT.Done()
803 s.Close()
804 }()
805 guestSvcMap = launch.GuestServiceMap{
806 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
807 }
808 }
809
Serge Bazanskie78a0892021-10-07 17:03:49 +0200810 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200811 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
812 if err != nil {
813 ctxC()
814 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
815 }
816
817 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100818 var serialPort io.ReadWriter
819 if opts.NodeLogsToFiles {
820 path := path.Join(ld, "nanoswitch.txt")
821 serialPort, err = NewSerialFileLogger(path)
822 if err != nil {
823 launch.Log("Could not open log file for nanoswitch: %v", err)
824 }
825 launch.Log("Nanoswitch logs at %s", path)
826 } else {
827 serialPort = newPrefixedStdio(99)
828 }
Serge Bazanskie84726b2024-04-17 16:32:32 +0200829 kernelPath, err := runfiles.Rlocation("_main/metropolis/test/ktest/vmlinux")
830 if err != nil {
831 launch.Fatal("Failed to resolved nanoswitch kernel: %v", err)
832 }
833 initramfsPath, err := runfiles.Rlocation("_main/metropolis/test/nanoswitch/initramfs.cpio.zst")
834 if err != nil {
835 launch.Fatal("Failed to resolved nanoswitch initramfs: %v", err)
836 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200837 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100838 Name: "nanoswitch",
Serge Bazanskie84726b2024-04-17 16:32:32 +0200839 KernelPath: kernelPath,
840 InitramfsPath: initramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200841 ExtraNetworkInterfaces: switchPorts,
842 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200843 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100844 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100845 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200846 }); err != nil {
847 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100848 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200849 }
850 }
851 }()
852
Serge Bazanskibe742842022-04-04 13:18:50 +0200853 // Build SOCKS dialer.
854 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
855 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200856 if err != nil {
857 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200858 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200859 }
860
Serge Bazanskibe742842022-04-04 13:18:50 +0200861 // Retrieve owner credentials and first node.
862 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200863 if err != nil {
864 ctxC()
865 return nil, err
866 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200867
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100868 // Write credentials to the metroctl directory.
869 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
870 ctxC()
871 return nil, fmt.Errorf("could not write owner key: %w", err)
872 }
873 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
874 ctxC()
875 return nil, fmt.Errorf("could not write owner certificate: %w", err)
876 }
877
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200878 // Set up a partially initialized cluster instance, to be filled in in the
879 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200880 cluster := &Cluster{
881 Owner: *cert,
882 Ports: portMap,
883 Nodes: map[string]*NodeInCluster{
884 firstNode.ID: firstNode,
885 },
886 NodeIDs: []string{
887 firstNode.ID,
888 },
889
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100890 nodesDone: done,
891 nodeOpts: nodeOpts,
892 launchDir: ld,
893 socketDir: sd,
894 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200895
Lorenz Brun276a7462023-07-12 21:28:54 +0200896 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200897
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200898 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200899 ctxC: ctxC,
900 }
901
902 // Now start the rest of the nodes and register them into the cluster.
903
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200904 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200905 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200906 if err != nil {
907 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200908 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200909 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200910 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200911
912 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100913 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200914 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
915 if err != nil {
916 ctxC()
917 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
918 }
919 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100920 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200921
922 // Retrieve cluster info (for directory and ca public key) to register further
923 // nodes.
924 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
925 if err != nil {
926 ctxC()
927 return nil, fmt.Errorf("GetClusterInfo: %w", err)
928 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200929 caCert, err := x509.ParseCertificate(resI.CaCertificate)
930 if err != nil {
931 ctxC()
932 return nil, fmt.Errorf("ParseCertificate: %w", err)
933 }
934 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200935
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200936 // Use the retrieved information to configure the rest of the node options.
937 for i := 1; i < opts.NumNodes; i++ {
938 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100939 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200940 ConnectToSocket: vmPorts[i],
941 NodeParameters: &apb.NodeParameters{
942 Cluster: &apb.NodeParameters_ClusterRegister_{
943 ClusterRegister: &apb.NodeParameters_ClusterRegister{
944 RegisterTicket: ticket,
945 ClusterDirectory: resI.ClusterDirectory,
946 CaCertificate: resI.CaCertificate,
947 },
948 },
949 },
950 SerialPort: newPrefixedStdio(i),
951 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100952 if opts.NodeLogsToFiles {
953 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
954 port, err := NewSerialFileLogger(path)
955 if err != nil {
956 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
957 }
958 launch.Log("Node %d logs at %s", i+1, path)
959 nodeOpts[i].SerialPort = port
960 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200961 }
962
963 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200964 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100965 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200966 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i], done[i])
967 if err != nil {
968 return nil, fmt.Errorf("failed to launch node %d: %w", i+1, err)
969 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200970 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200971
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200972 seenNodes := make(map[string]bool)
973 launch.Log("Cluster: waiting for nodes to appear as NEW...")
974 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200975 for {
976 nodes, err := getNodes(ctx, mgmt)
977 if err != nil {
978 ctxC()
979 return nil, fmt.Errorf("could not get nodes: %w", err)
980 }
981 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200982 if n.State != cpb.NodeState_NODE_STATE_NEW {
983 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200984 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100985 if seenNodes[n.Id] {
986 continue
987 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200988 seenNodes[n.Id] = true
989 cluster.Nodes[n.Id] = &NodeInCluster{
990 ID: n.Id,
991 Pubkey: n.Pubkey,
992 }
993 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200994 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200995
996 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200997 break
998 }
999 time.Sleep(1 * time.Second)
1000 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001001 }
1002 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001003
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001004 approvedNodes := make(map[string]bool)
1005 upNodes := make(map[string]bool)
1006 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001007 for {
1008 nodes, err := getNodes(ctx, mgmt)
1009 if err != nil {
1010 ctxC()
1011 return nil, fmt.Errorf("could not get nodes: %w", err)
1012 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001013 for _, node := range nodes {
1014 if !seenNodes[node.Id] {
1015 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001016 continue
1017 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001018
1019 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1020 launch.Log("Cluster: node %s is up", node.Id)
1021 upNodes[node.Id] = true
1022 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001023 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001024 if upNodes[node.Id] {
1025 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001026 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001027
1028 if !approvedNodes[node.Id] {
1029 launch.Log("Cluster: approving node %s", node.Id)
1030 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1031 Pubkey: node.Pubkey,
1032 })
1033 if err != nil {
1034 ctxC()
1035 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1036 }
1037 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001038 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001039 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001040
1041 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1042 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001043 break
1044 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001045 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001046 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001047 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001048
Serge Bazanski05f813b2023-03-16 17:58:39 +01001049 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001050 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001051 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001052 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001053 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001054
Serge Bazanskibe742842022-04-04 13:18:50 +02001055 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001056}
1057
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001058// RebootNode reboots the cluster member node matching the given index, and
1059// waits for it to rejoin the cluster. It will use the given context ctx to run
1060// cluster API requests, whereas the resulting QEMU process will be created
1061// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1062func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1063 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001064 return fmt.Errorf("index out of bounds")
1065 }
1066 if c.nodeOpts[idx].Runtime == nil {
1067 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001068 }
1069 id := c.NodeIDs[idx]
1070
1071 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001072 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001073 if err != nil {
1074 return err
1075 }
1076 mgmt := apb.NewManagementClient(curC)
1077
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001078 // Cancel the node's context. This will shut down QEMU.
1079 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001080 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001081 err = <-c.nodesDone[idx]
1082 if err != nil {
1083 return fmt.Errorf("while restarting node: %w", err)
1084 }
1085
1086 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001087 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001088 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1089 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1090 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001091
Serge Bazanskibc969572024-03-21 11:56:13 +01001092 start := time.Now()
1093
1094 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001095 for {
1096 cs, err := getNode(ctx, mgmt, id)
1097 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001098 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001099 return err
1100 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001101 launch.Log("Cluster: node health: %+v", cs.Health)
1102
1103 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1104 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001105 break
1106 }
1107 time.Sleep(time.Second)
1108 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001109 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001110 return nil
1111}
1112
1113// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001114// nodes to stop. It returns an error if stopping the nodes failed, or one of
1115// the nodes failed to fully start in the first place.
1116func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001117 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001118 if c.authClient != nil {
1119 c.authClient.Close()
1120 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001121 c.ctxC()
1122
Leopold20a036e2023-01-15 00:17:19 +01001123 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001124 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001125 for _, c := range c.nodesDone {
1126 err := <-c
1127 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001128 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001129 }
1130 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001131 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001132 os.RemoveAll(c.launchDir)
1133 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001134 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001135 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001136 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001137}
Serge Bazanskibe742842022-04-04 13:18:50 +02001138
1139// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1140// their ID. This is performed by connecting to the cluster nanoswitch via its
1141// SOCKS proxy, and using the cluster node list for name resolution.
1142//
1143// For example:
1144//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001145// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001146func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1147 host, port, err := net.SplitHostPort(addr)
1148 if err != nil {
1149 return nil, fmt.Errorf("invalid host:port: %w", err)
1150 }
1151 // Already an IP address?
1152 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001153 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001154 }
1155
1156 // Otherwise, expect a node name.
1157 node, ok := c.Nodes[host]
1158 if !ok {
1159 return nil, fmt.Errorf("unknown node %q", host)
1160 }
1161 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001162 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001163}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001164
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001165// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1166// Kubernetes authenticating proxy using the cluster owner identity.
1167// It currently has access to everything (i.e. the cluster-admin role)
1168// via the owner-admin binding.
1169func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1170 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1171 if err != nil {
1172 // We explicitly pass an Ed25519 private key in, so this can't happen
1173 panic(err)
1174 }
1175
1176 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001177 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001178 Host: host,
1179 TLSClientConfig: rest.TLSClientConfig{
1180 // TODO(q3k): use CA certificate
1181 Insecure: true,
1182 ServerName: "kubernetes.default.svc",
1183 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1184 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1185 },
1186 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1187 return c.DialNode(ctx, address)
1188 },
1189 }
1190 return kubernetes.NewForConfig(&clientConfig)
1191}
1192
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001193// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1194// which are currently Kubernetes controllers, ie. run an apiserver. This list
1195// might be empty if no node is currently configured with the
1196// 'KubernetesController' node.
1197func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1198 curC, err := c.CuratorClient()
1199 if err != nil {
1200 return nil, err
1201 }
1202 mgmt := apb.NewManagementClient(curC)
1203 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1204 Filter: "has(node.roles.kubernetes_controller)",
1205 })
1206 if err != nil {
1207 return nil, err
1208 }
1209 defer srv.CloseSend()
1210 var res []string
1211 for {
1212 n, err := srv.Recv()
1213 if err == io.EOF {
1214 break
1215 }
1216 if err != nil {
1217 return nil, err
1218 }
1219 if n.Status == nil || n.Status.ExternalAddress == "" {
1220 continue
1221 }
1222 res = append(res, n.Status.ExternalAddress)
1223 }
1224 return res, nil
1225}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001226
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001227// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1228// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001229func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1230 // Get an authenticated owner client within the cluster.
1231 curC, err := c.CuratorClient()
1232 if err != nil {
1233 return err
1234 }
1235 mgmt := apb.NewManagementClient(curC)
1236 nodes, err := getNodes(ctx, mgmt)
1237 if err != nil {
1238 return err
1239 }
1240
1241 var unhealthy []string
1242 for _, node := range nodes {
1243 if node.Health == apb.Node_HEALTHY {
1244 continue
1245 }
1246 unhealthy = append(unhealthy, node.Id)
1247 }
1248 if len(unhealthy) == 0 {
1249 return nil
1250 }
1251 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1252}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001253
1254// ApproveNode approves a node by ID, waiting for it to become UP.
1255func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1256 curC, err := c.CuratorClient()
1257 if err != nil {
1258 return err
1259 }
1260 mgmt := apb.NewManagementClient(curC)
1261
1262 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1263 Pubkey: c.Nodes[id].Pubkey,
1264 })
1265 if err != nil {
1266 return fmt.Errorf("ApproveNode: %w", err)
1267 }
1268 launch.Log("Cluster: %s: approved, waiting for UP", id)
1269 for {
1270 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1271 if err != nil {
1272 return fmt.Errorf("GetNodes: %w", err)
1273 }
1274 found := false
1275 for {
1276 node, err := nodes.Recv()
1277 if errors.Is(err, io.EOF) {
1278 break
1279 }
1280 if err != nil {
1281 return fmt.Errorf("Nodes.Recv: %w", err)
1282 }
1283 if node.Id != id {
1284 continue
1285 }
1286 if node.State != cpb.NodeState_NODE_STATE_UP {
1287 continue
1288 }
1289 found = true
1290 break
1291 }
1292 nodes.CloseSend()
1293
1294 if found {
1295 break
1296 }
1297 time.Sleep(time.Second)
1298 }
1299 launch.Log("Cluster: %s: UP", id)
1300 return nil
1301}
1302
1303// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1304func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1305 curC, err := c.CuratorClient()
1306 if err != nil {
1307 return err
1308 }
1309 mgmt := apb.NewManagementClient(curC)
1310
1311 tr := true
1312 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1313 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1314 Node: &apb.UpdateNodeRolesRequest_Id{
1315 Id: id,
1316 },
1317 KubernetesWorker: &tr,
1318 })
1319 return err
1320}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001321
1322// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1323func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1324 curC, err := c.CuratorClient()
1325 if err != nil {
1326 return err
1327 }
1328 mgmt := apb.NewManagementClient(curC)
1329 cur := ipb.NewCuratorClient(curC)
1330
1331 tr := true
1332 launch.Log("Cluster: %s: adding ConsensusMember", id)
1333 bo := backoff.NewExponentialBackOff()
1334 bo.MaxElapsedTime = 10 * time.Second
1335
1336 backoff.Retry(func() error {
1337 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1338 Node: &apb.UpdateNodeRolesRequest_Id{
1339 Id: id,
1340 },
1341 ConsensusMember: &tr,
1342 })
1343 if err != nil {
1344 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1345 }
1346 return err
1347 }, backoff.WithContext(bo, ctx))
1348 if err != nil {
1349 return err
1350 }
1351
1352 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1353
1354 learner := false
1355 for {
1356 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1357 if err != nil {
1358 return fmt.Errorf("GetConsensusStatus: %w", err)
1359 }
1360 for _, member := range res.EtcdMember {
1361 if member.Id != id {
1362 continue
1363 }
1364 switch member.Status {
1365 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1366 if !learner {
1367 learner = true
1368 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1369 }
1370 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1371 launch.Log("Cluster: %s: became a full member", id)
1372 return nil
1373 }
1374 }
1375 time.Sleep(100 * time.Millisecond)
1376 }
1377}