blob: e7a49a26d2aa01e2274a59e9886cf76312a001bf [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 Bazanskidd5b03c2024-05-16 18:07:06 +020044 "source.monogon.dev/go/qcow2"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010045 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski66e58952021-10-05 17:06:56 +020046 "source.monogon.dev/metropolis/node"
Serge Bazanskie78a0892021-10-07 17:03:49 +020047 "source.monogon.dev/metropolis/node/core/identity"
Serge Bazanski66e58952021-10-05 17:06:56 +020048 "source.monogon.dev/metropolis/node/core/rpc"
Serge Bazanski5bb8a332022-06-23 17:41:33 +020049 "source.monogon.dev/metropolis/node/core/rpc/resolver"
Lorenz Brun150f24a2023-07-13 20:11:06 +020050 "source.monogon.dev/metropolis/pkg/localregistry"
Serge Bazanski66e58952021-10-05 17:06:56 +020051 "source.monogon.dev/metropolis/test/launch"
52)
53
Leopold20a036e2023-01-15 00:17:19 +010054// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020055type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010056 // Name is a human-readable identifier to be used in debug output.
57 Name string
58
Serge Bazanski66e58952021-10-05 17:06:56 +020059 // Ports contains the port mapping where to expose the internal ports of the VM to
60 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
61 // ConnectToSocket is set.
62 Ports launch.PortMap
63
Leopold20a036e2023-01-15 00:17:19 +010064 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
65 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020066 // want to test reboot behavior this should be false.
67 AllowReboot bool
68
Leopold20a036e2023-01-15 00:17:19 +010069 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
70 // set, it is instead connected to the given file descriptor/socket. If this is
71 // set, all port maps from the Ports option are ignored. Intended for networking
72 // this instance together with others for running more complex network
73 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020074 ConnectToSocket *os.File
75
Leopoldacfad5b2023-01-15 14:05:25 +010076 // When PcapDump is set, all traffic is dumped to a pcap file in the
77 // runtime directory (e.g. "net0.pcap" for the first interface).
78 PcapDump bool
79
Leopold20a036e2023-01-15 00:17:19 +010080 // SerialPort is an io.ReadWriter over which you can communicate with the serial
81 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +020082 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
83 SerialPort io.ReadWriter
84
85 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
86 // registering into a cluster.
87 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +020088
89 // Mac is the node's MAC address.
90 Mac *net.HardwareAddr
91
92 // Runtime keeps the node's QEMU runtime state.
93 Runtime *NodeRuntime
94}
95
Leopold20a036e2023-01-15 00:17:19 +010096// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +020097type NodeRuntime struct {
98 // ld points at the node's launch directory storing data such as storage
99 // images, firmware variables or the TPM state.
100 ld string
101 // sd points at the node's socket directory.
102 sd string
103
104 // ctxT is the context QEMU will execute in.
105 ctxT context.Context
106 // CtxC is the QEMU context's cancellation function.
107 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200108}
109
110// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200111var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200112 node.ConsensusPort,
113
114 node.CuratorServicePort,
115 node.DebugServicePort,
116
117 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100118 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200119 node.CuratorServicePort,
120 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200121 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200122}
123
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200124// setupRuntime creates the node's QEMU runtime directory, together with all
125// files required to preserve its state, a level below the chosen path ld. The
126// node's socket directory is similarily created a level below sd. It may
127// return an I/O error.
128func setupRuntime(ld, sd string) (*NodeRuntime, error) {
129 // Create a temporary directory to keep all the runtime files.
130 stdp, err := os.MkdirTemp(ld, "node_state*")
131 if err != nil {
132 return nil, fmt.Errorf("failed to create the state directory: %w", err)
133 }
134
135 // Initialize the node's storage with a prebuilt image.
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100136 si, err := runfiles.Rlocation("_main/metropolis/node/image.img")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200137 if err != nil {
138 return nil, fmt.Errorf("while resolving a path: %w", err)
139 }
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200140
141 di := filepath.Join(stdp, "image.qcow2")
142 launch.Log("Cluster: generating node QCOW2 snapshot image: %s -> %s", si, di)
143
144 df, err := os.Create(di)
145 if err != nil {
146 return nil, fmt.Errorf("while opening image for writing: %w", err)
147 }
148 defer df.Close()
149 if err := qcow2.Generate(df, qcow2.GenerateWithBackingFile(si)); err != nil {
150 return nil, fmt.Errorf("while creating copy-on-write node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200151 }
152
153 // Initialize the OVMF firmware variables file.
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100154 sv, err := runfiles.Rlocation("edk2/OVMF_VARS.fd")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200155 if err != nil {
156 return nil, fmt.Errorf("while resolving a path: %w", err)
157 }
158 dv := filepath.Join(stdp, filepath.Base(sv))
159 if err := copyFile(sv, dv); err != nil {
160 return nil, fmt.Errorf("while copying firmware variables: %w", err)
161 }
162
163 // Create the TPM state directory and initialize all files required by swtpm.
164 tpmt := filepath.Join(stdp, "tpm")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200165 if err := os.Mkdir(tpmt, 0o755); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200166 return nil, fmt.Errorf("while creating the TPM directory: %w", err)
167 }
Serge Bazanskid02c6c72024-05-22 18:19:00 +0200168 for _, name := range []string{"issuercert.pem", "signkey.pem", "tpm2-00.permall"} {
169 src, err := runfiles.Rlocation(filepath.Join("_main/metropolis/node/tpm", name))
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200170 if err != nil {
171 return nil, fmt.Errorf("while resolving a path: %w", err)
172 }
173 tgt := filepath.Join(tpmt, name)
174 if err := copyFile(src, tgt); err != nil {
175 return nil, fmt.Errorf("while copying TPM state: file %q to %q: %w", src, tgt, err)
176 }
177 }
178
179 // Create the socket directory.
180 sotdp, err := os.MkdirTemp(sd, "node_sock*")
181 if err != nil {
182 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
183 }
184
185 return &NodeRuntime{
186 ld: stdp,
187 sd: sotdp,
188 }, nil
189}
190
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200191// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200192// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200193func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200194 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200195 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanski58ddc092022-06-30 18:23:33 +0200196 r := resolver.New(c.ctxT, resolver.WithLogger(func(f string, args ...interface{}) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100197 launch.Log("Cluster: client resolver: %s", fmt.Sprintf(f, args...))
Serge Bazanski58ddc092022-06-30 18:23:33 +0200198 }))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200199 for _, n := range c.NodeIDs {
200 ep, err := resolver.NodeWithDefaultPort(n)
201 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200202 return nil, fmt.Errorf("could not add node %q by DNS: %w", n, err)
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200203 }
204 r.AddEndpoint(ep)
205 }
206 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
207 grpc.WithTransportCredentials(authCreds),
208 grpc.WithResolvers(r),
209 grpc.WithContextDialer(c.DialNode),
210 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200211 if err != nil {
212 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
213 }
214 c.authClient = authClient
215 }
216 return c.authClient, nil
217}
218
Serge Bazanski66e58952021-10-05 17:06:56 +0200219// LaunchNode launches a single Metropolis node instance with the given options.
220// The instance runs mostly paravirtualized but with some emulated hardware
221// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200222// writable, and the changes are kept across reboots and shutdowns. ld and sd
223// point to the launch directory and the socket directory, holding the nodes'
224// state files (storage, tpm state, firmware state), and UNIX socket files
225// (swtpm <-> QEMU interplay) respectively. The directories must exist before
226// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
227// if either are not initialized.
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200228func LaunchNode(ctx context.Context, ld, sd string, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200229 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
230 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200231 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
232 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
233 // that we open and pass the name of it to QEMU. Not pinning this crashes both
234 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
235 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200236
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200237 // If it's the node's first start, set up its runtime directories.
238 if options.Runtime == nil {
239 r, err := setupRuntime(ld, sd)
240 if err != nil {
241 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200242 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200243 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200244 }
245
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200246 // Replace the node's context with a new one.
247 r := options.Runtime
248 if r.CtxC != nil {
249 r.CtxC()
250 }
251 r.ctxT, r.CtxC = context.WithCancel(ctx)
252
Serge Bazanski66e58952021-10-05 17:06:56 +0200253 var qemuNetType string
254 var qemuNetConfig launch.QemuValue
255 if options.ConnectToSocket != nil {
256 qemuNetType = "socket"
257 qemuNetConfig = launch.QemuValue{
258 "id": {"net0"},
259 "fd": {"3"},
260 }
261 } else {
262 qemuNetType = "user"
263 qemuNetConfig = launch.QemuValue{
264 "id": {"net0"},
265 "net": {"10.42.0.0/24"},
266 "dhcpstart": {"10.42.0.10"},
267 "hostfwd": options.Ports.ToQemuForwards(),
268 }
269 }
270
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200271 // Generate the node's MAC address if it isn't already set in NodeOptions.
272 if options.Mac == nil {
273 mac, err := generateRandomEthernetMAC()
274 if err != nil {
275 return err
276 }
277 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200278 }
279
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100280 ovmfCodePath, err := runfiles.Rlocation("edk2/OVMF_CODE.fd")
281 if err != nil {
282 return err
283 }
284
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200285 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
286 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200287 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200288 qemuArgs := []string{
Serge Bazanski99b02142024-04-17 16:33:28 +0200289 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults", "-m", "2048",
Serge Bazanski66e58952021-10-05 17:06:56 +0200290 "-cpu", "host", "-smp", "sockets=1,cpus=1,cores=2,threads=2,maxcpus=4",
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100291 "-drive", "if=pflash,format=raw,readonly=on,file=" + ovmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200292 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200293 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200294 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200295 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200296 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
297 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
298 "-device", "tpm-tis,tpmdev=tpm0",
299 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200300 "-serial", "stdio",
301 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200302
303 if !options.AllowReboot {
304 qemuArgs = append(qemuArgs, "-no-reboot")
305 }
306
307 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200308 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200309 parametersRaw, err := proto.Marshal(options.NodeParameters)
310 if err != nil {
311 return fmt.Errorf("failed to encode node paraeters: %w", err)
312 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200313 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200314 return fmt.Errorf("failed to write node parameters: %w", err)
315 }
316 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
317 }
318
Leopoldacfad5b2023-01-15 14:05:25 +0100319 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200320 qemuNetDump := launch.QemuValue{
321 "id": {"net0"},
322 "netdev": {"net0"},
323 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100324 }
325 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
326 }
327
Serge Bazanski66e58952021-10-05 17:06:56 +0200328 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200329 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200330
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200331 tpmd := filepath.Join(r.ld, "tpm")
332 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanski66e58952021-10-05 17:06:56 +0200333 tpmEmuCmd.Stderr = os.Stderr
334 tpmEmuCmd.Stdout = os.Stdout
335
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100336 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200337 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200338 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200339 return fmt.Errorf("failed to start TPM emulator: %w", err)
340 }
341
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200342 // Wait for the socket to be created by the TPM emulator before launching
343 // QEMU.
344 for {
345 _, err := os.Stat(tpmSocketPath)
346 if err == nil {
347 break
348 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200349 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200350 tpmCancel()
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 {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200354 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200355 return fmt.Errorf("while waiting for the TPM socket: %w", err)
356 }
357 time.Sleep(time.Millisecond * 100)
358 }
359
Serge Bazanski66e58952021-10-05 17:06:56 +0200360 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200361 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200362 if options.ConnectToSocket != nil {
363 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
364 }
365
366 var stdErrBuf bytes.Buffer
367 systemCmd.Stderr = &stdErrBuf
368 systemCmd.Stdout = options.SerialPort
369
Leopoldaf5086b2023-01-15 14:12:42 +0100370 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
371
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200372 go func() {
373 launch.Log("Node: Starting...")
374 err = systemCmd.Run()
375 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200376
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200377 // Stop TPM emulator and wait for it to exit to properly reap the child process
378 tpmCancel()
379 launch.Log("Node: Waiting for TPM emulator to exit")
380 // Wait returns a SIGKILL error because we just cancelled its context.
381 // We still need to call it to avoid creating zombies.
382 errTpm := tpmEmuCmd.Wait()
383 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200384
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200385 var exerr *exec.ExitError
386 if err != nil && errors.As(err, &exerr) {
387 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
388 if status.Signaled() && status.Signal() == syscall.SIGKILL {
389 // Process was killed externally (most likely by our context being canceled).
390 // This is a normal exit for us, so return nil
391 doneC <- nil
392 return
393 }
394 exerr.Stderr = stdErrBuf.Bytes()
395 newErr := launch.QEMUError(*exerr)
396 launch.Log("Node: %q", stdErrBuf.String())
397 doneC <- &newErr
398 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200399 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200400 doneC <- err
401 }()
402 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200403}
404
405func copyFile(src, dst string) error {
406 in, err := os.Open(src)
407 if err != nil {
408 return fmt.Errorf("when opening source: %w", err)
409 }
410 defer in.Close()
411
412 out, err := os.Create(dst)
413 if err != nil {
414 return fmt.Errorf("when creating destination: %w", err)
415 }
416 defer out.Close()
417
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100418 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200419 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100420 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200421 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100422
423 // Copy the file while preserving its sparseness. The image files are very
424 // sparse (less than 10% allocated), so this is a lot faster.
425 var lastHoleStart int64
426 for {
427 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
428 if err != nil {
429 return fmt.Errorf("when seeking to next data block: %w", err)
430 }
431 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
432 if err != nil {
433 return fmt.Errorf("when seeking to next hole: %w", err)
434 }
435 lastHoleStart = holeStart
436 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
437 return fmt.Errorf("when seeking to current data block: %w", err)
438 }
439 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
440 return fmt.Errorf("when seeking output to next data block: %w", err)
441 }
442 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
443 return fmt.Errorf("when copying file: %w", err)
444 }
445 if endPos == holeStart {
446 // The next hole is at the end of the file, we're done here.
447 break
448 }
449 }
450
Serge Bazanski66e58952021-10-05 17:06:56 +0200451 return out.Close()
452}
453
Serge Bazanskie78a0892021-10-07 17:03:49 +0200454// getNodes wraps around Management.GetNodes to return a list of nodes in a
455// cluster.
456func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200457 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100458 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100459 err := backoff.Retry(func() error {
460 res = nil
461 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200462 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100463 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200464 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100465 for {
466 node, err := srvN.Recv()
467 if err == io.EOF {
468 break
469 }
470 if err != nil {
471 return fmt.Errorf("GetNodes.Recv: %w", err)
472 }
473 res = append(res, node)
474 }
475 return nil
476 }, bo)
477 if err != nil {
478 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200479 }
480 return res, nil
481}
482
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200483// getNode wraps Management.GetNodes. It returns node information matching
484// given node ID.
485func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
486 nodes, err := getNodes(ctx, mgmt)
487 if err != nil {
488 return nil, fmt.Errorf("could not get nodes: %w", err)
489 }
490 for _, n := range nodes {
491 eid := identity.NodeID(n.Pubkey)
492 if eid != id {
493 continue
494 }
495 return n, nil
496 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200497 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200498}
499
Serge Bazanski66e58952021-10-05 17:06:56 +0200500// Gets a random EUI-48 Ethernet MAC address
501func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
502 macBuf := make([]byte, 6)
503 _, err := rand.Read(macBuf)
504 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200505 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200506 }
507
508 // Set U/L bit and clear I/G bit (locally administered individual MAC)
509 // Ref IEEE 802-2014 Section 8.2.2
510 macBuf[0] = (macBuf[0] | 2) & 0xfe
511 mac := net.HardwareAddr(macBuf)
512 return &mac, nil
513}
514
Serge Bazanskibe742842022-04-04 13:18:50 +0200515const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200516
Serge Bazanskibe742842022-04-04 13:18:50 +0200517// ClusterPorts contains all ports handled by Nanoswitch.
518var ClusterPorts = []uint16{
519 // Forwarded to the first node.
520 uint16(node.CuratorServicePort),
521 uint16(node.DebugServicePort),
522 uint16(node.KubernetesAPIPort),
523 uint16(node.KubernetesAPIWrappedPort),
524
525 // SOCKS proxy to the switch network
526 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200527}
528
529// ClusterOptions contains all options for launching a Metropolis cluster.
530type ClusterOptions struct {
531 // The number of nodes this cluster should be started with.
532 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100533
534 // If true, node logs will be saved to individual files instead of being printed
535 // out to stderr. The path of these files will be still printed to stdout.
536 //
537 // The files will be located within the launch directory inside TEST_TMPDIR (or
538 // the default tempdir location, if not set).
539 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200540
541 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
542 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
543 // incomplete.
544 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200545
546 // Optional local registry which will be made available to the cluster to
547 // pull images from. This is a more efficient alternative to preseeding all
548 // images used for testing.
549 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200550
551 // InitialClusterConfiguration will be passed to the first node when creating the
552 // cluster, and defines some basic properties of the cluster. If not specified,
553 // the cluster will default to defaults as defined in
554 // metropolis.proto.api.NodeParameters.
555 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200556}
557
558// Cluster is the running Metropolis cluster launched using the LaunchCluster
559// function.
560type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200561 // Owner is the TLS Certificate of the owner of the test cluster. This can be
562 // used to authenticate further clients to the running cluster.
563 Owner tls.Certificate
564 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200565 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200566 Ports launch.PortMap
567
Serge Bazanskibe742842022-04-04 13:18:50 +0200568 // Nodes is a map from Node ID to its runtime information.
569 Nodes map[string]*NodeInCluster
570 // NodeIDs is a list of node IDs that are backing this cluster, in order of
571 // creation.
572 NodeIDs []string
573
Serge Bazanski54e212a2023-06-14 13:45:11 +0200574 // CACertificate is the cluster's CA certificate.
575 CACertificate *x509.Certificate
576
Serge Bazanski66e58952021-10-05 17:06:56 +0200577 // nodesDone is a list of channels populated with the return codes from all the
578 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100579 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200580 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200581 // nodeOpts are the cluster member nodes' mutable launch options, kept here
582 // to facilitate reboots.
583 nodeOpts []NodeOptions
584 // launchDir points at the directory keeping the nodes' state, such as storage
585 // images, firmware variable files, TPM state.
586 launchDir string
587 // socketDir points at the directory keeping UNIX socket files, such as these
588 // used to facilitate communication between QEMU and swtpm. It's different
589 // from launchDir, and anchored nearer the file system root, due to the
590 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100591 socketDir string
592 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200593
Lorenz Brun276a7462023-07-12 21:28:54 +0200594 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200595 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200596 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200597
598 // authClient is a cached authenticated owner connection to a Curator
599 // instance within the cluster.
600 authClient *grpc.ClientConn
601
602 // ctxT is the context individual node contexts are created from.
603 ctxT context.Context
604 // ctxC is used by Close to cancel the context under which the nodes are
605 // running.
606 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200607}
608
609// NodeInCluster represents information about a node that's part of a Cluster.
610type NodeInCluster struct {
611 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200612 ID string
613 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200614 // Address of the node on the network ran by nanoswitch. Not reachable from the
615 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
616 // on Cluster.Ports[SOCKSPort]).
617 ManagementAddress string
618}
619
620// firstConnection performs the initial owner credential escrow with a newly
621// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
622// running at 10.1.0.2, which is always the case with the current nanoswitch
623// implementation.
624//
Leopold20a036e2023-01-15 00:17:19 +0100625// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200626// information as NodeInCluster.
627func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
628 // Dial external service.
629 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100630 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200631 if err != nil {
632 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
633 }
634 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
635 return socksDialer.Dial("tcp", addr)
636 }
637 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
638 if err != nil {
639 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
640 }
641 defer initClient.Close()
642
643 // Retrieve owner certificate - this can take a while because the node is still
644 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100645 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200646 aaa := apb.NewAAAClient(initClient)
647 var cert *tls.Certificate
648 err = backoff.Retry(func() error {
649 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
650 if st, ok := status.FromError(err); ok {
651 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100652 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200653 return err
654 }
655 }
656 return backoff.Permanent(err)
657 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
658 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200659 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200660 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100661 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200662
663 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200664 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200665 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
666 if err != nil {
667 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
668 }
669 defer authClient.Close()
670 mgmt := apb.NewManagementClient(authClient)
671
672 var node *NodeInCluster
673 err = backoff.Retry(func() error {
674 nodes, err := getNodes(ctx, mgmt)
675 if err != nil {
676 return fmt.Errorf("retrieving nodes failed: %w", err)
677 }
678 if len(nodes) != 1 {
679 return fmt.Errorf("expected one node, got %d", len(nodes))
680 }
681 n := nodes[0]
682 if n.Status == nil || n.Status.ExternalAddress == "" {
683 return fmt.Errorf("node has no status and/or address")
684 }
685 node = &NodeInCluster{
686 ID: identity.NodeID(n.Pubkey),
687 ManagementAddress: n.Status.ExternalAddress,
688 }
689 return nil
690 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
691 if err != nil {
692 return nil, nil, err
693 }
694
695 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200696}
697
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100698func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200699 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100700 if err != nil {
701 return nil, err
702 }
703 return f, nil
704}
705
Serge Bazanski66e58952021-10-05 17:06:56 +0200706// LaunchCluster launches a cluster of Metropolis node VMs together with a
707// Nanoswitch instance to network them all together.
708//
709// The given context will be used to run all qemu instances in the cluster, and
710// canceling the context or calling Close() will terminate them.
711func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200712 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200713 return nil, errors.New("refusing to start cluster with zero nodes")
714 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200715
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200716 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100717 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200718 if err != nil {
719 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
720 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100721 // Create the metroctl config directory. We keep it in /tmp because in some
722 // scenarios it's end-user visible and we want it short.
723 md, err := os.MkdirTemp("/tmp", "metroctl-*")
724 if err != nil {
725 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
726 }
727
728 // Create the socket directory. We keep it in /tmp because of socket path limits.
729 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200730 if err != nil {
731 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
732 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200733
734 // Prepare links between nodes and nanoswitch.
735 var switchPorts []*os.File
736 var vmPorts []*os.File
737 for i := 0; i < opts.NumNodes; i++ {
738 switchPort, vmPort, err := launch.NewSocketPair()
739 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200740 return nil, fmt.Errorf("failed to get socketpair: %w", err)
741 }
742 switchPorts = append(switchPorts, switchPort)
743 vmPorts = append(vmPorts, vmPort)
744 }
745
Serge Bazanskie78a0892021-10-07 17:03:49 +0200746 // Make a list of channels that will be populated by all running node qemu
747 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200748 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200749 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200750 done[i] = make(chan error, 1)
751 }
752
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200753 // Prepare the node options. These will be kept as part of Cluster.
754 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
755 // launch. The runtime information can be later used to restart a node.
756 // The 0th node will be initialized first. The rest will follow after it
757 // had bootstrapped the cluster.
758 nodeOpts := make([]NodeOptions, opts.NumNodes)
759 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100760 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200761 ConnectToSocket: vmPorts[0],
762 NodeParameters: &apb.NodeParameters{
763 Cluster: &apb.NodeParameters_ClusterBootstrap_{
764 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
Serge Bazanskie564f172024-04-03 12:06:06 +0200765 OwnerPublicKey: InsecurePublicKey,
766 InitialClusterConfiguration: opts.InitialClusterConfiguration,
Serge Bazanski66e58952021-10-05 17:06:56 +0200767 },
768 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200769 },
770 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100771 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200772 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100773 if opts.NodeLogsToFiles {
774 path := path.Join(ld, "node-1.txt")
775 port, err := NewSerialFileLogger(path)
776 if err != nil {
777 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
778 }
779 launch.Log("Node 1 logs at %s", path)
780 nodeOpts[0].SerialPort = port
781 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200782
783 // Start the first node.
784 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100785 launch.Log("Cluster: Starting node %d...", 1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200786 if err := LaunchNode(ctxT, ld, sd, &nodeOpts[0], done[0]); err != nil {
787 ctxC()
788 return nil, fmt.Errorf("failed to launch first node: %w", err)
789 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200790
Lorenz Brun150f24a2023-07-13 20:11:06 +0200791 localRegistryAddr := net.TCPAddr{
792 IP: net.IPv4(10, 42, 0, 82),
793 Port: 5000,
794 }
795
796 var guestSvcMap launch.GuestServiceMap
797 if opts.LocalRegistry != nil {
798 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
799 if err != nil {
800 ctxC()
801 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
802 }
803 s := http.Server{
804 Handler: opts.LocalRegistry,
805 }
806 go s.Serve(l)
807 go func() {
808 <-ctxT.Done()
809 s.Close()
810 }()
811 guestSvcMap = launch.GuestServiceMap{
812 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
813 }
814 }
815
Serge Bazanskie78a0892021-10-07 17:03:49 +0200816 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200817 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
818 if err != nil {
819 ctxC()
820 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
821 }
822
823 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100824 var serialPort io.ReadWriter
825 if opts.NodeLogsToFiles {
826 path := path.Join(ld, "nanoswitch.txt")
827 serialPort, err = NewSerialFileLogger(path)
828 if err != nil {
829 launch.Log("Could not open log file for nanoswitch: %v", err)
830 }
831 launch.Log("Nanoswitch logs at %s", path)
832 } else {
833 serialPort = newPrefixedStdio(99)
834 }
Serge Bazanskie84726b2024-04-17 16:32:32 +0200835 kernelPath, err := runfiles.Rlocation("_main/metropolis/test/ktest/vmlinux")
836 if err != nil {
837 launch.Fatal("Failed to resolved nanoswitch kernel: %v", err)
838 }
839 initramfsPath, err := runfiles.Rlocation("_main/metropolis/test/nanoswitch/initramfs.cpio.zst")
840 if err != nil {
841 launch.Fatal("Failed to resolved nanoswitch initramfs: %v", err)
842 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200843 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100844 Name: "nanoswitch",
Serge Bazanskie84726b2024-04-17 16:32:32 +0200845 KernelPath: kernelPath,
846 InitramfsPath: initramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200847 ExtraNetworkInterfaces: switchPorts,
848 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200849 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100850 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100851 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200852 }); err != nil {
853 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100854 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200855 }
856 }
857 }()
858
Serge Bazanskibe742842022-04-04 13:18:50 +0200859 // Build SOCKS dialer.
860 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
861 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200862 if err != nil {
863 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200864 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200865 }
866
Serge Bazanskibe742842022-04-04 13:18:50 +0200867 // Retrieve owner credentials and first node.
868 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200869 if err != nil {
870 ctxC()
871 return nil, err
872 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200873
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100874 // Write credentials to the metroctl directory.
875 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
876 ctxC()
877 return nil, fmt.Errorf("could not write owner key: %w", err)
878 }
879 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
880 ctxC()
881 return nil, fmt.Errorf("could not write owner certificate: %w", err)
882 }
883
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200884 // Set up a partially initialized cluster instance, to be filled in in the
885 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200886 cluster := &Cluster{
887 Owner: *cert,
888 Ports: portMap,
889 Nodes: map[string]*NodeInCluster{
890 firstNode.ID: firstNode,
891 },
892 NodeIDs: []string{
893 firstNode.ID,
894 },
895
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100896 nodesDone: done,
897 nodeOpts: nodeOpts,
898 launchDir: ld,
899 socketDir: sd,
900 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200901
Lorenz Brun276a7462023-07-12 21:28:54 +0200902 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200903
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200904 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200905 ctxC: ctxC,
906 }
907
908 // Now start the rest of the nodes and register them into the cluster.
909
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200910 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200911 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200912 if err != nil {
913 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200914 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200915 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200916 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200917
918 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100919 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200920 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
921 if err != nil {
922 ctxC()
923 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
924 }
925 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100926 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200927
928 // Retrieve cluster info (for directory and ca public key) to register further
929 // nodes.
930 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
931 if err != nil {
932 ctxC()
933 return nil, fmt.Errorf("GetClusterInfo: %w", err)
934 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200935 caCert, err := x509.ParseCertificate(resI.CaCertificate)
936 if err != nil {
937 ctxC()
938 return nil, fmt.Errorf("ParseCertificate: %w", err)
939 }
940 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200941
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200942 // Use the retrieved information to configure the rest of the node options.
943 for i := 1; i < opts.NumNodes; i++ {
944 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100945 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200946 ConnectToSocket: vmPorts[i],
947 NodeParameters: &apb.NodeParameters{
948 Cluster: &apb.NodeParameters_ClusterRegister_{
949 ClusterRegister: &apb.NodeParameters_ClusterRegister{
950 RegisterTicket: ticket,
951 ClusterDirectory: resI.ClusterDirectory,
952 CaCertificate: resI.CaCertificate,
953 },
954 },
955 },
956 SerialPort: newPrefixedStdio(i),
957 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100958 if opts.NodeLogsToFiles {
959 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
960 port, err := NewSerialFileLogger(path)
961 if err != nil {
962 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
963 }
964 launch.Log("Node %d logs at %s", i+1, path)
965 nodeOpts[i].SerialPort = port
966 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200967 }
968
969 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200970 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100971 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200972 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i], done[i])
973 if err != nil {
974 return nil, fmt.Errorf("failed to launch node %d: %w", i+1, err)
975 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200976 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200977
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200978 seenNodes := make(map[string]bool)
979 launch.Log("Cluster: waiting for nodes to appear as NEW...")
980 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200981 for {
982 nodes, err := getNodes(ctx, mgmt)
983 if err != nil {
984 ctxC()
985 return nil, fmt.Errorf("could not get nodes: %w", err)
986 }
987 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200988 if n.State != cpb.NodeState_NODE_STATE_NEW {
989 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200990 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100991 if seenNodes[n.Id] {
992 continue
993 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200994 seenNodes[n.Id] = true
995 cluster.Nodes[n.Id] = &NodeInCluster{
996 ID: n.Id,
997 Pubkey: n.Pubkey,
998 }
999 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001000 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001001
1002 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001003 break
1004 }
1005 time.Sleep(1 * time.Second)
1006 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001007 }
1008 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001009
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001010 approvedNodes := make(map[string]bool)
1011 upNodes := make(map[string]bool)
1012 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001013 for {
1014 nodes, err := getNodes(ctx, mgmt)
1015 if err != nil {
1016 ctxC()
1017 return nil, fmt.Errorf("could not get nodes: %w", err)
1018 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001019 for _, node := range nodes {
1020 if !seenNodes[node.Id] {
1021 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001022 continue
1023 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001024
1025 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1026 launch.Log("Cluster: node %s is up", node.Id)
1027 upNodes[node.Id] = true
1028 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001029 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001030 if upNodes[node.Id] {
1031 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001032 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001033
1034 if !approvedNodes[node.Id] {
1035 launch.Log("Cluster: approving node %s", node.Id)
1036 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1037 Pubkey: node.Pubkey,
1038 })
1039 if err != nil {
1040 ctxC()
1041 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1042 }
1043 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001044 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001045 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001046
1047 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1048 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001049 break
1050 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001051 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001052 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001053 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001054
Serge Bazanski05f813b2023-03-16 17:58:39 +01001055 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001056 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001057 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001058 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001059 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001060
Serge Bazanskibe742842022-04-04 13:18:50 +02001061 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001062}
1063
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001064// RebootNode reboots the cluster member node matching the given index, and
1065// waits for it to rejoin the cluster. It will use the given context ctx to run
1066// cluster API requests, whereas the resulting QEMU process will be created
1067// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1068func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1069 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001070 return fmt.Errorf("index out of bounds")
1071 }
1072 if c.nodeOpts[idx].Runtime == nil {
1073 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001074 }
1075 id := c.NodeIDs[idx]
1076
1077 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001078 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001079 if err != nil {
1080 return err
1081 }
1082 mgmt := apb.NewManagementClient(curC)
1083
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001084 // Cancel the node's context. This will shut down QEMU.
1085 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001086 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001087 err = <-c.nodesDone[idx]
1088 if err != nil {
1089 return fmt.Errorf("while restarting node: %w", err)
1090 }
1091
1092 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001093 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001094 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1095 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1096 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001097
Serge Bazanskibc969572024-03-21 11:56:13 +01001098 start := time.Now()
1099
1100 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001101 for {
1102 cs, err := getNode(ctx, mgmt, id)
1103 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001104 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001105 return err
1106 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001107 launch.Log("Cluster: node health: %+v", cs.Health)
1108
1109 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1110 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001111 break
1112 }
1113 time.Sleep(time.Second)
1114 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001115 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001116 return nil
1117}
1118
Serge Bazanski500f6e02024-04-03 12:06:40 +02001119// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1120// given by idx. If the node is already shut down, this is a no-op.
1121func (c *Cluster) ShutdownNode(idx int) error {
1122 if idx < 0 || idx >= len(c.NodeIDs) {
1123 return fmt.Errorf("index out of bounds")
1124 }
1125 // Return if node is already stopped.
1126 select {
1127 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1128 return nil
1129 default:
1130 }
1131 id := c.NodeIDs[idx]
1132
1133 // Cancel the node's context. This will shut down QEMU.
1134 c.nodeOpts[idx].Runtime.CtxC()
1135 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1136 err := <-c.nodesDone[idx]
1137 if err != nil {
1138 return fmt.Errorf("while shutting down node: %w", err)
1139 }
1140 return nil
1141}
1142
1143// StartNode performs a power on of the node given by idx. If the node is already
1144// running, this is a no-op.
1145func (c *Cluster) StartNode(idx int) error {
1146 if idx < 0 || idx >= len(c.NodeIDs) {
1147 return fmt.Errorf("index out of bounds")
1148 }
1149 id := c.NodeIDs[idx]
1150 // Return if node is already running.
1151 select {
1152 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1153 default:
1154 return nil
1155 }
1156
1157 // Start QEMU again.
1158 launch.Log("Cluster: starting node %d (%s).", idx, id)
1159 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1160 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1161 }
1162 return nil
1163}
1164
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001165// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001166// nodes to stop. It returns an error if stopping the nodes failed, or one of
1167// the nodes failed to fully start in the first place.
1168func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001169 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001170 if c.authClient != nil {
1171 c.authClient.Close()
1172 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001173 c.ctxC()
1174
Leopold20a036e2023-01-15 00:17:19 +01001175 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001176 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001177 for _, c := range c.nodesDone {
1178 err := <-c
1179 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001180 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001181 }
1182 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001183 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001184 os.RemoveAll(c.launchDir)
1185 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001186 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001187 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001188 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001189}
Serge Bazanskibe742842022-04-04 13:18:50 +02001190
1191// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1192// their ID. This is performed by connecting to the cluster nanoswitch via its
1193// SOCKS proxy, and using the cluster node list for name resolution.
1194//
1195// For example:
1196//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001197// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001198func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1199 host, port, err := net.SplitHostPort(addr)
1200 if err != nil {
1201 return nil, fmt.Errorf("invalid host:port: %w", err)
1202 }
1203 // Already an IP address?
1204 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001205 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001206 }
1207
1208 // Otherwise, expect a node name.
1209 node, ok := c.Nodes[host]
1210 if !ok {
1211 return nil, fmt.Errorf("unknown node %q", host)
1212 }
1213 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001214 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001215}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001216
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001217// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1218// Kubernetes authenticating proxy using the cluster owner identity.
1219// It currently has access to everything (i.e. the cluster-admin role)
1220// via the owner-admin binding.
1221func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1222 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1223 if err != nil {
1224 // We explicitly pass an Ed25519 private key in, so this can't happen
1225 panic(err)
1226 }
1227
1228 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001229 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001230 Host: host,
1231 TLSClientConfig: rest.TLSClientConfig{
1232 // TODO(q3k): use CA certificate
1233 Insecure: true,
1234 ServerName: "kubernetes.default.svc",
1235 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1236 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1237 },
1238 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1239 return c.DialNode(ctx, address)
1240 },
1241 }
1242 return kubernetes.NewForConfig(&clientConfig)
1243}
1244
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001245// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1246// which are currently Kubernetes controllers, ie. run an apiserver. This list
1247// might be empty if no node is currently configured with the
1248// 'KubernetesController' node.
1249func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1250 curC, err := c.CuratorClient()
1251 if err != nil {
1252 return nil, err
1253 }
1254 mgmt := apb.NewManagementClient(curC)
1255 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1256 Filter: "has(node.roles.kubernetes_controller)",
1257 })
1258 if err != nil {
1259 return nil, err
1260 }
1261 defer srv.CloseSend()
1262 var res []string
1263 for {
1264 n, err := srv.Recv()
1265 if err == io.EOF {
1266 break
1267 }
1268 if err != nil {
1269 return nil, err
1270 }
1271 if n.Status == nil || n.Status.ExternalAddress == "" {
1272 continue
1273 }
1274 res = append(res, n.Status.ExternalAddress)
1275 }
1276 return res, nil
1277}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001278
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001279// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1280// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001281func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1282 // Get an authenticated owner client within the cluster.
1283 curC, err := c.CuratorClient()
1284 if err != nil {
1285 return err
1286 }
1287 mgmt := apb.NewManagementClient(curC)
1288 nodes, err := getNodes(ctx, mgmt)
1289 if err != nil {
1290 return err
1291 }
1292
1293 var unhealthy []string
1294 for _, node := range nodes {
1295 if node.Health == apb.Node_HEALTHY {
1296 continue
1297 }
1298 unhealthy = append(unhealthy, node.Id)
1299 }
1300 if len(unhealthy) == 0 {
1301 return nil
1302 }
1303 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1304}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001305
1306// ApproveNode approves a node by ID, waiting for it to become UP.
1307func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1308 curC, err := c.CuratorClient()
1309 if err != nil {
1310 return err
1311 }
1312 mgmt := apb.NewManagementClient(curC)
1313
1314 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1315 Pubkey: c.Nodes[id].Pubkey,
1316 })
1317 if err != nil {
1318 return fmt.Errorf("ApproveNode: %w", err)
1319 }
1320 launch.Log("Cluster: %s: approved, waiting for UP", id)
1321 for {
1322 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1323 if err != nil {
1324 return fmt.Errorf("GetNodes: %w", err)
1325 }
1326 found := false
1327 for {
1328 node, err := nodes.Recv()
1329 if errors.Is(err, io.EOF) {
1330 break
1331 }
1332 if err != nil {
1333 return fmt.Errorf("Nodes.Recv: %w", err)
1334 }
1335 if node.Id != id {
1336 continue
1337 }
1338 if node.State != cpb.NodeState_NODE_STATE_UP {
1339 continue
1340 }
1341 found = true
1342 break
1343 }
1344 nodes.CloseSend()
1345
1346 if found {
1347 break
1348 }
1349 time.Sleep(time.Second)
1350 }
1351 launch.Log("Cluster: %s: UP", id)
1352 return nil
1353}
1354
1355// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1356func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1357 curC, err := c.CuratorClient()
1358 if err != nil {
1359 return err
1360 }
1361 mgmt := apb.NewManagementClient(curC)
1362
1363 tr := true
1364 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1365 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1366 Node: &apb.UpdateNodeRolesRequest_Id{
1367 Id: id,
1368 },
1369 KubernetesWorker: &tr,
1370 })
1371 return err
1372}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001373
1374// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1375func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1376 curC, err := c.CuratorClient()
1377 if err != nil {
1378 return err
1379 }
1380 mgmt := apb.NewManagementClient(curC)
1381 cur := ipb.NewCuratorClient(curC)
1382
1383 tr := true
1384 launch.Log("Cluster: %s: adding ConsensusMember", id)
1385 bo := backoff.NewExponentialBackOff()
1386 bo.MaxElapsedTime = 10 * time.Second
1387
1388 backoff.Retry(func() error {
1389 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1390 Node: &apb.UpdateNodeRolesRequest_Id{
1391 Id: id,
1392 },
1393 ConsensusMember: &tr,
1394 })
1395 if err != nil {
1396 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1397 }
1398 return err
1399 }, backoff.WithContext(bo, ctx))
1400 if err != nil {
1401 return err
1402 }
1403
1404 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1405
1406 learner := false
1407 for {
1408 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1409 if err != nil {
1410 return fmt.Errorf("GetConsensusStatus: %w", err)
1411 }
1412 for _, member := range res.EtcdMember {
1413 if member.Id != id {
1414 continue
1415 }
1416 switch member.Status {
1417 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1418 if !learner {
1419 learner = true
1420 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1421 }
1422 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1423 launch.Log("Cluster: %s: became a full member", id)
1424 return nil
1425 }
1426 }
1427 time.Sleep(100 * time.Millisecond)
1428 }
1429}