blob: 4c678a1f3f399d9e289808c2a25d6d0d6dacb97b [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
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000329 swtpm, err := runfiles.Rlocation("swtpm/swtpm")
330 if err != nil {
331 return fmt.Errorf("could not find swtpm: %w", err)
332 }
333
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200334 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200335
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200336 tpmd := filepath.Join(r.ld, "tpm")
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000337 tpmEmuCmd := exec.CommandContext(tpmCtx, swtpm, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
338 // Silence warnings from unsafe libtpms build (uses non-constant-time
339 // cryptographic operations).
340 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200341 tpmEmuCmd.Stderr = os.Stderr
342 tpmEmuCmd.Stdout = os.Stdout
343
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100344 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200345 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200346 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200347 return fmt.Errorf("failed to start TPM emulator: %w", err)
348 }
349
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200350 // Wait for the socket to be created by the TPM emulator before launching
351 // QEMU.
352 for {
353 _, err := os.Stat(tpmSocketPath)
354 if err == nil {
355 break
356 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200357 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200358 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200359 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
360 }
361 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200362 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200363 return fmt.Errorf("while waiting for the TPM socket: %w", err)
364 }
365 time.Sleep(time.Millisecond * 100)
366 }
367
Serge Bazanski66e58952021-10-05 17:06:56 +0200368 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200369 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200370 if options.ConnectToSocket != nil {
371 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
372 }
373
374 var stdErrBuf bytes.Buffer
375 systemCmd.Stderr = &stdErrBuf
376 systemCmd.Stdout = options.SerialPort
377
Leopoldaf5086b2023-01-15 14:12:42 +0100378 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
379
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200380 go func() {
381 launch.Log("Node: Starting...")
382 err = systemCmd.Run()
383 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200384
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200385 // Stop TPM emulator and wait for it to exit to properly reap the child process
386 tpmCancel()
387 launch.Log("Node: Waiting for TPM emulator to exit")
388 // Wait returns a SIGKILL error because we just cancelled its context.
389 // We still need to call it to avoid creating zombies.
390 errTpm := tpmEmuCmd.Wait()
391 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200392
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200393 var exerr *exec.ExitError
394 if err != nil && errors.As(err, &exerr) {
395 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
396 if status.Signaled() && status.Signal() == syscall.SIGKILL {
397 // Process was killed externally (most likely by our context being canceled).
398 // This is a normal exit for us, so return nil
399 doneC <- nil
400 return
401 }
402 exerr.Stderr = stdErrBuf.Bytes()
403 newErr := launch.QEMUError(*exerr)
404 launch.Log("Node: %q", stdErrBuf.String())
405 doneC <- &newErr
406 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200407 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200408 doneC <- err
409 }()
410 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200411}
412
413func copyFile(src, dst string) error {
414 in, err := os.Open(src)
415 if err != nil {
416 return fmt.Errorf("when opening source: %w", err)
417 }
418 defer in.Close()
419
420 out, err := os.Create(dst)
421 if err != nil {
422 return fmt.Errorf("when creating destination: %w", err)
423 }
424 defer out.Close()
425
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100426 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200427 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100428 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200429 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100430
431 // Copy the file while preserving its sparseness. The image files are very
432 // sparse (less than 10% allocated), so this is a lot faster.
433 var lastHoleStart int64
434 for {
435 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
436 if err != nil {
437 return fmt.Errorf("when seeking to next data block: %w", err)
438 }
439 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
440 if err != nil {
441 return fmt.Errorf("when seeking to next hole: %w", err)
442 }
443 lastHoleStart = holeStart
444 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
445 return fmt.Errorf("when seeking to current data block: %w", err)
446 }
447 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
448 return fmt.Errorf("when seeking output to next data block: %w", err)
449 }
450 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
451 return fmt.Errorf("when copying file: %w", err)
452 }
453 if endPos == holeStart {
454 // The next hole is at the end of the file, we're done here.
455 break
456 }
457 }
458
Serge Bazanski66e58952021-10-05 17:06:56 +0200459 return out.Close()
460}
461
Serge Bazanskie78a0892021-10-07 17:03:49 +0200462// getNodes wraps around Management.GetNodes to return a list of nodes in a
463// cluster.
464func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200465 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100466 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100467 err := backoff.Retry(func() error {
468 res = nil
469 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200470 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100471 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200472 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100473 for {
474 node, err := srvN.Recv()
475 if err == io.EOF {
476 break
477 }
478 if err != nil {
479 return fmt.Errorf("GetNodes.Recv: %w", err)
480 }
481 res = append(res, node)
482 }
483 return nil
484 }, bo)
485 if err != nil {
486 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200487 }
488 return res, nil
489}
490
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200491// getNode wraps Management.GetNodes. It returns node information matching
492// given node ID.
493func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
494 nodes, err := getNodes(ctx, mgmt)
495 if err != nil {
496 return nil, fmt.Errorf("could not get nodes: %w", err)
497 }
498 for _, n := range nodes {
499 eid := identity.NodeID(n.Pubkey)
500 if eid != id {
501 continue
502 }
503 return n, nil
504 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200505 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200506}
507
Serge Bazanski66e58952021-10-05 17:06:56 +0200508// Gets a random EUI-48 Ethernet MAC address
509func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
510 macBuf := make([]byte, 6)
511 _, err := rand.Read(macBuf)
512 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200513 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200514 }
515
516 // Set U/L bit and clear I/G bit (locally administered individual MAC)
517 // Ref IEEE 802-2014 Section 8.2.2
518 macBuf[0] = (macBuf[0] | 2) & 0xfe
519 mac := net.HardwareAddr(macBuf)
520 return &mac, nil
521}
522
Serge Bazanskibe742842022-04-04 13:18:50 +0200523const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200524
Serge Bazanskibe742842022-04-04 13:18:50 +0200525// ClusterPorts contains all ports handled by Nanoswitch.
526var ClusterPorts = []uint16{
527 // Forwarded to the first node.
528 uint16(node.CuratorServicePort),
529 uint16(node.DebugServicePort),
530 uint16(node.KubernetesAPIPort),
531 uint16(node.KubernetesAPIWrappedPort),
532
533 // SOCKS proxy to the switch network
534 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200535}
536
537// ClusterOptions contains all options for launching a Metropolis cluster.
538type ClusterOptions struct {
539 // The number of nodes this cluster should be started with.
540 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100541
542 // If true, node logs will be saved to individual files instead of being printed
543 // out to stderr. The path of these files will be still printed to stdout.
544 //
545 // The files will be located within the launch directory inside TEST_TMPDIR (or
546 // the default tempdir location, if not set).
547 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200548
549 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
550 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
551 // incomplete.
552 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200553
554 // Optional local registry which will be made available to the cluster to
555 // pull images from. This is a more efficient alternative to preseeding all
556 // images used for testing.
557 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200558
559 // InitialClusterConfiguration will be passed to the first node when creating the
560 // cluster, and defines some basic properties of the cluster. If not specified,
561 // the cluster will default to defaults as defined in
562 // metropolis.proto.api.NodeParameters.
563 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200564}
565
566// Cluster is the running Metropolis cluster launched using the LaunchCluster
567// function.
568type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200569 // Owner is the TLS Certificate of the owner of the test cluster. This can be
570 // used to authenticate further clients to the running cluster.
571 Owner tls.Certificate
572 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200573 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200574 Ports launch.PortMap
575
Serge Bazanskibe742842022-04-04 13:18:50 +0200576 // Nodes is a map from Node ID to its runtime information.
577 Nodes map[string]*NodeInCluster
578 // NodeIDs is a list of node IDs that are backing this cluster, in order of
579 // creation.
580 NodeIDs []string
581
Serge Bazanski54e212a2023-06-14 13:45:11 +0200582 // CACertificate is the cluster's CA certificate.
583 CACertificate *x509.Certificate
584
Serge Bazanski66e58952021-10-05 17:06:56 +0200585 // nodesDone is a list of channels populated with the return codes from all the
586 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100587 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200588 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200589 // nodeOpts are the cluster member nodes' mutable launch options, kept here
590 // to facilitate reboots.
591 nodeOpts []NodeOptions
592 // launchDir points at the directory keeping the nodes' state, such as storage
593 // images, firmware variable files, TPM state.
594 launchDir string
595 // socketDir points at the directory keeping UNIX socket files, such as these
596 // used to facilitate communication between QEMU and swtpm. It's different
597 // from launchDir, and anchored nearer the file system root, due to the
598 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100599 socketDir string
600 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200601
Lorenz Brun276a7462023-07-12 21:28:54 +0200602 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200603 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200604 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200605
606 // authClient is a cached authenticated owner connection to a Curator
607 // instance within the cluster.
608 authClient *grpc.ClientConn
609
610 // ctxT is the context individual node contexts are created from.
611 ctxT context.Context
612 // ctxC is used by Close to cancel the context under which the nodes are
613 // running.
614 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200615}
616
617// NodeInCluster represents information about a node that's part of a Cluster.
618type NodeInCluster struct {
619 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200620 ID string
621 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200622 // Address of the node on the network ran by nanoswitch. Not reachable from the
623 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
624 // on Cluster.Ports[SOCKSPort]).
625 ManagementAddress string
626}
627
628// firstConnection performs the initial owner credential escrow with a newly
629// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
630// running at 10.1.0.2, which is always the case with the current nanoswitch
631// implementation.
632//
Leopold20a036e2023-01-15 00:17:19 +0100633// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200634// information as NodeInCluster.
635func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
636 // Dial external service.
637 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100638 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200639 if err != nil {
640 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
641 }
642 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
643 return socksDialer.Dial("tcp", addr)
644 }
645 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
646 if err != nil {
647 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
648 }
649 defer initClient.Close()
650
651 // Retrieve owner certificate - this can take a while because the node is still
652 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100653 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200654 aaa := apb.NewAAAClient(initClient)
655 var cert *tls.Certificate
656 err = backoff.Retry(func() error {
657 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
658 if st, ok := status.FromError(err); ok {
659 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100660 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200661 return err
662 }
663 }
664 return backoff.Permanent(err)
665 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
666 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200667 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200668 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100669 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200670
671 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200672 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200673 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
674 if err != nil {
675 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
676 }
677 defer authClient.Close()
678 mgmt := apb.NewManagementClient(authClient)
679
680 var node *NodeInCluster
681 err = backoff.Retry(func() error {
682 nodes, err := getNodes(ctx, mgmt)
683 if err != nil {
684 return fmt.Errorf("retrieving nodes failed: %w", err)
685 }
686 if len(nodes) != 1 {
687 return fmt.Errorf("expected one node, got %d", len(nodes))
688 }
689 n := nodes[0]
690 if n.Status == nil || n.Status.ExternalAddress == "" {
691 return fmt.Errorf("node has no status and/or address")
692 }
693 node = &NodeInCluster{
694 ID: identity.NodeID(n.Pubkey),
695 ManagementAddress: n.Status.ExternalAddress,
696 }
697 return nil
698 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
699 if err != nil {
700 return nil, nil, err
701 }
702
703 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200704}
705
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100706func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200707 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100708 if err != nil {
709 return nil, err
710 }
711 return f, nil
712}
713
Serge Bazanski66e58952021-10-05 17:06:56 +0200714// LaunchCluster launches a cluster of Metropolis node VMs together with a
715// Nanoswitch instance to network them all together.
716//
717// The given context will be used to run all qemu instances in the cluster, and
718// canceling the context or calling Close() will terminate them.
719func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200720 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200721 return nil, errors.New("refusing to start cluster with zero nodes")
722 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200723
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200724 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100725 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200726 if err != nil {
727 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
728 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100729 // Create the metroctl config directory. We keep it in /tmp because in some
730 // scenarios it's end-user visible and we want it short.
731 md, err := os.MkdirTemp("/tmp", "metroctl-*")
732 if err != nil {
733 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
734 }
735
736 // Create the socket directory. We keep it in /tmp because of socket path limits.
737 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200738 if err != nil {
739 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
740 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200741
742 // Prepare links between nodes and nanoswitch.
743 var switchPorts []*os.File
744 var vmPorts []*os.File
745 for i := 0; i < opts.NumNodes; i++ {
746 switchPort, vmPort, err := launch.NewSocketPair()
747 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200748 return nil, fmt.Errorf("failed to get socketpair: %w", err)
749 }
750 switchPorts = append(switchPorts, switchPort)
751 vmPorts = append(vmPorts, vmPort)
752 }
753
Serge Bazanskie78a0892021-10-07 17:03:49 +0200754 // Make a list of channels that will be populated by all running node qemu
755 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200756 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200757 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200758 done[i] = make(chan error, 1)
759 }
760
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200761 // Prepare the node options. These will be kept as part of Cluster.
762 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
763 // launch. The runtime information can be later used to restart a node.
764 // The 0th node will be initialized first. The rest will follow after it
765 // had bootstrapped the cluster.
766 nodeOpts := make([]NodeOptions, opts.NumNodes)
767 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100768 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200769 ConnectToSocket: vmPorts[0],
770 NodeParameters: &apb.NodeParameters{
771 Cluster: &apb.NodeParameters_ClusterBootstrap_{
772 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
Serge Bazanskie564f172024-04-03 12:06:06 +0200773 OwnerPublicKey: InsecurePublicKey,
774 InitialClusterConfiguration: opts.InitialClusterConfiguration,
Serge Bazanski66e58952021-10-05 17:06:56 +0200775 },
776 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200777 },
778 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100779 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200780 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100781 if opts.NodeLogsToFiles {
782 path := path.Join(ld, "node-1.txt")
783 port, err := NewSerialFileLogger(path)
784 if err != nil {
785 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
786 }
787 launch.Log("Node 1 logs at %s", path)
788 nodeOpts[0].SerialPort = port
789 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200790
791 // Start the first node.
792 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100793 launch.Log("Cluster: Starting node %d...", 1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200794 if err := LaunchNode(ctxT, ld, sd, &nodeOpts[0], done[0]); err != nil {
795 ctxC()
796 return nil, fmt.Errorf("failed to launch first node: %w", err)
797 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200798
Lorenz Brun150f24a2023-07-13 20:11:06 +0200799 localRegistryAddr := net.TCPAddr{
800 IP: net.IPv4(10, 42, 0, 82),
801 Port: 5000,
802 }
803
804 var guestSvcMap launch.GuestServiceMap
805 if opts.LocalRegistry != nil {
806 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
807 if err != nil {
808 ctxC()
809 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
810 }
811 s := http.Server{
812 Handler: opts.LocalRegistry,
813 }
814 go s.Serve(l)
815 go func() {
816 <-ctxT.Done()
817 s.Close()
818 }()
819 guestSvcMap = launch.GuestServiceMap{
820 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
821 }
822 }
823
Serge Bazanskie78a0892021-10-07 17:03:49 +0200824 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200825 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
826 if err != nil {
827 ctxC()
828 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
829 }
830
831 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100832 var serialPort io.ReadWriter
833 if opts.NodeLogsToFiles {
834 path := path.Join(ld, "nanoswitch.txt")
835 serialPort, err = NewSerialFileLogger(path)
836 if err != nil {
837 launch.Log("Could not open log file for nanoswitch: %v", err)
838 }
839 launch.Log("Nanoswitch logs at %s", path)
840 } else {
841 serialPort = newPrefixedStdio(99)
842 }
Serge Bazanskie84726b2024-04-17 16:32:32 +0200843 kernelPath, err := runfiles.Rlocation("_main/metropolis/test/ktest/vmlinux")
844 if err != nil {
845 launch.Fatal("Failed to resolved nanoswitch kernel: %v", err)
846 }
847 initramfsPath, err := runfiles.Rlocation("_main/metropolis/test/nanoswitch/initramfs.cpio.zst")
848 if err != nil {
849 launch.Fatal("Failed to resolved nanoswitch initramfs: %v", err)
850 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200851 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100852 Name: "nanoswitch",
Serge Bazanskie84726b2024-04-17 16:32:32 +0200853 KernelPath: kernelPath,
854 InitramfsPath: initramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200855 ExtraNetworkInterfaces: switchPorts,
856 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200857 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100858 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100859 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200860 }); err != nil {
861 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100862 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200863 }
864 }
865 }()
866
Serge Bazanskibe742842022-04-04 13:18:50 +0200867 // Build SOCKS dialer.
868 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
869 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200870 if err != nil {
871 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200872 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200873 }
874
Serge Bazanskibe742842022-04-04 13:18:50 +0200875 // Retrieve owner credentials and first node.
876 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200877 if err != nil {
878 ctxC()
879 return nil, err
880 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200881
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100882 // Write credentials to the metroctl directory.
883 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
884 ctxC()
885 return nil, fmt.Errorf("could not write owner key: %w", err)
886 }
887 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
888 ctxC()
889 return nil, fmt.Errorf("could not write owner certificate: %w", err)
890 }
891
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200892 // Set up a partially initialized cluster instance, to be filled in in the
893 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200894 cluster := &Cluster{
895 Owner: *cert,
896 Ports: portMap,
897 Nodes: map[string]*NodeInCluster{
898 firstNode.ID: firstNode,
899 },
900 NodeIDs: []string{
901 firstNode.ID,
902 },
903
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100904 nodesDone: done,
905 nodeOpts: nodeOpts,
906 launchDir: ld,
907 socketDir: sd,
908 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200909
Lorenz Brun276a7462023-07-12 21:28:54 +0200910 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200911
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200912 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200913 ctxC: ctxC,
914 }
915
916 // Now start the rest of the nodes and register them into the cluster.
917
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200918 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200919 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200920 if err != nil {
921 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200922 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200923 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200924 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200925
926 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100927 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200928 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
929 if err != nil {
930 ctxC()
931 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
932 }
933 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100934 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200935
936 // Retrieve cluster info (for directory and ca public key) to register further
937 // nodes.
938 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
939 if err != nil {
940 ctxC()
941 return nil, fmt.Errorf("GetClusterInfo: %w", err)
942 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200943 caCert, err := x509.ParseCertificate(resI.CaCertificate)
944 if err != nil {
945 ctxC()
946 return nil, fmt.Errorf("ParseCertificate: %w", err)
947 }
948 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200949
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200950 // Use the retrieved information to configure the rest of the node options.
951 for i := 1; i < opts.NumNodes; i++ {
952 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100953 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200954 ConnectToSocket: vmPorts[i],
955 NodeParameters: &apb.NodeParameters{
956 Cluster: &apb.NodeParameters_ClusterRegister_{
957 ClusterRegister: &apb.NodeParameters_ClusterRegister{
958 RegisterTicket: ticket,
959 ClusterDirectory: resI.ClusterDirectory,
960 CaCertificate: resI.CaCertificate,
961 },
962 },
963 },
964 SerialPort: newPrefixedStdio(i),
965 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100966 if opts.NodeLogsToFiles {
967 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
968 port, err := NewSerialFileLogger(path)
969 if err != nil {
970 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
971 }
972 launch.Log("Node %d logs at %s", i+1, path)
973 nodeOpts[i].SerialPort = port
974 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200975 }
976
977 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200978 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100979 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200980 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i], done[i])
981 if err != nil {
982 return nil, fmt.Errorf("failed to launch node %d: %w", i+1, err)
983 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200984 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200985
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200986 seenNodes := make(map[string]bool)
987 launch.Log("Cluster: waiting for nodes to appear as NEW...")
988 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200989 for {
990 nodes, err := getNodes(ctx, mgmt)
991 if err != nil {
992 ctxC()
993 return nil, fmt.Errorf("could not get nodes: %w", err)
994 }
995 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200996 if n.State != cpb.NodeState_NODE_STATE_NEW {
997 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200998 }
Serge Bazanski87d9c592024-03-20 12:35:11 +0100999 if seenNodes[n.Id] {
1000 continue
1001 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001002 seenNodes[n.Id] = true
1003 cluster.Nodes[n.Id] = &NodeInCluster{
1004 ID: n.Id,
1005 Pubkey: n.Pubkey,
1006 }
1007 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001008 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001009
1010 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001011 break
1012 }
1013 time.Sleep(1 * time.Second)
1014 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001015 }
1016 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001017
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001018 approvedNodes := make(map[string]bool)
1019 upNodes := make(map[string]bool)
1020 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001021 for {
1022 nodes, err := getNodes(ctx, mgmt)
1023 if err != nil {
1024 ctxC()
1025 return nil, fmt.Errorf("could not get nodes: %w", err)
1026 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001027 for _, node := range nodes {
1028 if !seenNodes[node.Id] {
1029 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001030 continue
1031 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001032
1033 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1034 launch.Log("Cluster: node %s is up", node.Id)
1035 upNodes[node.Id] = true
1036 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001037 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001038 if upNodes[node.Id] {
1039 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001040 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001041
1042 if !approvedNodes[node.Id] {
1043 launch.Log("Cluster: approving node %s", node.Id)
1044 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1045 Pubkey: node.Pubkey,
1046 })
1047 if err != nil {
1048 ctxC()
1049 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1050 }
1051 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001052 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001053 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001054
1055 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1056 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001057 break
1058 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001059 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001060 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001061 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001062
Serge Bazanski05f813b2023-03-16 17:58:39 +01001063 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001064 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001065 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001066 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001067 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001068
Serge Bazanskibe742842022-04-04 13:18:50 +02001069 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001070}
1071
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001072// RebootNode reboots the cluster member node matching the given index, and
1073// waits for it to rejoin the cluster. It will use the given context ctx to run
1074// cluster API requests, whereas the resulting QEMU process will be created
1075// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1076func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1077 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001078 return fmt.Errorf("index out of bounds")
1079 }
1080 if c.nodeOpts[idx].Runtime == nil {
1081 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001082 }
1083 id := c.NodeIDs[idx]
1084
1085 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001086 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001087 if err != nil {
1088 return err
1089 }
1090 mgmt := apb.NewManagementClient(curC)
1091
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001092 // Cancel the node's context. This will shut down QEMU.
1093 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001094 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001095 err = <-c.nodesDone[idx]
1096 if err != nil {
1097 return fmt.Errorf("while restarting node: %w", err)
1098 }
1099
1100 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001101 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001102 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1103 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1104 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001105
Serge Bazanskibc969572024-03-21 11:56:13 +01001106 start := time.Now()
1107
1108 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001109 for {
1110 cs, err := getNode(ctx, mgmt, id)
1111 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001112 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001113 return err
1114 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001115 launch.Log("Cluster: node health: %+v", cs.Health)
1116
1117 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1118 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001119 break
1120 }
1121 time.Sleep(time.Second)
1122 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001123 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001124 return nil
1125}
1126
Serge Bazanski500f6e02024-04-03 12:06:40 +02001127// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1128// given by idx. If the node is already shut down, this is a no-op.
1129func (c *Cluster) ShutdownNode(idx int) error {
1130 if idx < 0 || idx >= len(c.NodeIDs) {
1131 return fmt.Errorf("index out of bounds")
1132 }
1133 // Return if node is already stopped.
1134 select {
1135 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1136 return nil
1137 default:
1138 }
1139 id := c.NodeIDs[idx]
1140
1141 // Cancel the node's context. This will shut down QEMU.
1142 c.nodeOpts[idx].Runtime.CtxC()
1143 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1144 err := <-c.nodesDone[idx]
1145 if err != nil {
1146 return fmt.Errorf("while shutting down node: %w", err)
1147 }
1148 return nil
1149}
1150
1151// StartNode performs a power on of the node given by idx. If the node is already
1152// running, this is a no-op.
1153func (c *Cluster) StartNode(idx int) error {
1154 if idx < 0 || idx >= len(c.NodeIDs) {
1155 return fmt.Errorf("index out of bounds")
1156 }
1157 id := c.NodeIDs[idx]
1158 // Return if node is already running.
1159 select {
1160 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1161 default:
1162 return nil
1163 }
1164
1165 // Start QEMU again.
1166 launch.Log("Cluster: starting node %d (%s).", idx, id)
1167 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1168 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1169 }
1170 return nil
1171}
1172
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001173// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001174// nodes to stop. It returns an error if stopping the nodes failed, or one of
1175// the nodes failed to fully start in the first place.
1176func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001177 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001178 if c.authClient != nil {
1179 c.authClient.Close()
1180 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001181 c.ctxC()
1182
Leopold20a036e2023-01-15 00:17:19 +01001183 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001184 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001185 for _, c := range c.nodesDone {
1186 err := <-c
1187 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001188 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001189 }
1190 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001191 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001192 os.RemoveAll(c.launchDir)
1193 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001194 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001195 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001196 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001197}
Serge Bazanskibe742842022-04-04 13:18:50 +02001198
1199// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1200// their ID. This is performed by connecting to the cluster nanoswitch via its
1201// SOCKS proxy, and using the cluster node list for name resolution.
1202//
1203// For example:
1204//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001205// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001206func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1207 host, port, err := net.SplitHostPort(addr)
1208 if err != nil {
1209 return nil, fmt.Errorf("invalid host:port: %w", err)
1210 }
1211 // Already an IP address?
1212 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001213 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001214 }
1215
1216 // Otherwise, expect a node name.
1217 node, ok := c.Nodes[host]
1218 if !ok {
1219 return nil, fmt.Errorf("unknown node %q", host)
1220 }
1221 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001222 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001223}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001224
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001225// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1226// Kubernetes authenticating proxy using the cluster owner identity.
1227// It currently has access to everything (i.e. the cluster-admin role)
1228// via the owner-admin binding.
1229func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1230 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1231 if err != nil {
1232 // We explicitly pass an Ed25519 private key in, so this can't happen
1233 panic(err)
1234 }
1235
1236 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001237 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001238 Host: host,
1239 TLSClientConfig: rest.TLSClientConfig{
1240 // TODO(q3k): use CA certificate
1241 Insecure: true,
1242 ServerName: "kubernetes.default.svc",
1243 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1244 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1245 },
1246 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1247 return c.DialNode(ctx, address)
1248 },
1249 }
1250 return kubernetes.NewForConfig(&clientConfig)
1251}
1252
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001253// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1254// which are currently Kubernetes controllers, ie. run an apiserver. This list
1255// might be empty if no node is currently configured with the
1256// 'KubernetesController' node.
1257func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1258 curC, err := c.CuratorClient()
1259 if err != nil {
1260 return nil, err
1261 }
1262 mgmt := apb.NewManagementClient(curC)
1263 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1264 Filter: "has(node.roles.kubernetes_controller)",
1265 })
1266 if err != nil {
1267 return nil, err
1268 }
1269 defer srv.CloseSend()
1270 var res []string
1271 for {
1272 n, err := srv.Recv()
1273 if err == io.EOF {
1274 break
1275 }
1276 if err != nil {
1277 return nil, err
1278 }
1279 if n.Status == nil || n.Status.ExternalAddress == "" {
1280 continue
1281 }
1282 res = append(res, n.Status.ExternalAddress)
1283 }
1284 return res, nil
1285}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001286
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001287// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1288// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001289func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1290 // Get an authenticated owner client within the cluster.
1291 curC, err := c.CuratorClient()
1292 if err != nil {
1293 return err
1294 }
1295 mgmt := apb.NewManagementClient(curC)
1296 nodes, err := getNodes(ctx, mgmt)
1297 if err != nil {
1298 return err
1299 }
1300
1301 var unhealthy []string
1302 for _, node := range nodes {
1303 if node.Health == apb.Node_HEALTHY {
1304 continue
1305 }
1306 unhealthy = append(unhealthy, node.Id)
1307 }
1308 if len(unhealthy) == 0 {
1309 return nil
1310 }
1311 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1312}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001313
1314// ApproveNode approves a node by ID, waiting for it to become UP.
1315func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1316 curC, err := c.CuratorClient()
1317 if err != nil {
1318 return err
1319 }
1320 mgmt := apb.NewManagementClient(curC)
1321
1322 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1323 Pubkey: c.Nodes[id].Pubkey,
1324 })
1325 if err != nil {
1326 return fmt.Errorf("ApproveNode: %w", err)
1327 }
1328 launch.Log("Cluster: %s: approved, waiting for UP", id)
1329 for {
1330 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1331 if err != nil {
1332 return fmt.Errorf("GetNodes: %w", err)
1333 }
1334 found := false
1335 for {
1336 node, err := nodes.Recv()
1337 if errors.Is(err, io.EOF) {
1338 break
1339 }
1340 if err != nil {
1341 return fmt.Errorf("Nodes.Recv: %w", err)
1342 }
1343 if node.Id != id {
1344 continue
1345 }
1346 if node.State != cpb.NodeState_NODE_STATE_UP {
1347 continue
1348 }
1349 found = true
1350 break
1351 }
1352 nodes.CloseSend()
1353
1354 if found {
1355 break
1356 }
1357 time.Sleep(time.Second)
1358 }
1359 launch.Log("Cluster: %s: UP", id)
1360 return nil
1361}
1362
1363// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1364func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1365 curC, err := c.CuratorClient()
1366 if err != nil {
1367 return err
1368 }
1369 mgmt := apb.NewManagementClient(curC)
1370
1371 tr := true
1372 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1373 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1374 Node: &apb.UpdateNodeRolesRequest_Id{
1375 Id: id,
1376 },
1377 KubernetesWorker: &tr,
1378 })
1379 return err
1380}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001381
1382// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1383func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1384 curC, err := c.CuratorClient()
1385 if err != nil {
1386 return err
1387 }
1388 mgmt := apb.NewManagementClient(curC)
1389 cur := ipb.NewCuratorClient(curC)
1390
1391 tr := true
1392 launch.Log("Cluster: %s: adding ConsensusMember", id)
1393 bo := backoff.NewExponentialBackOff()
1394 bo.MaxElapsedTime = 10 * time.Second
1395
1396 backoff.Retry(func() error {
1397 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1398 Node: &apb.UpdateNodeRolesRequest_Id{
1399 Id: id,
1400 },
1401 ConsensusMember: &tr,
1402 })
1403 if err != nil {
1404 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1405 }
1406 return err
1407 }, backoff.WithContext(bo, ctx))
1408 if err != nil {
1409 return err
1410 }
1411
1412 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1413
1414 learner := false
1415 for {
1416 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1417 if err != nil {
1418 return fmt.Errorf("GetConsensusStatus: %w", err)
1419 }
1420 for _, member := range res.EtcdMember {
1421 if member.Id != id {
1422 continue
1423 }
1424 switch member.Status {
1425 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1426 if !learner {
1427 learner = true
1428 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1429 }
1430 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1431 launch.Log("Cluster: %s: became a full member", id)
1432 return nil
1433 }
1434 }
1435 time.Sleep(100 * time.Millisecond)
1436 }
1437}