blob: 5469443dbb53005e40cbfb97ed62ead118616e8e [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 }
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100168 tpms, err := runfiles.Rlocation("_main/metropolis/node/tpm")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200169 if err != nil {
170 return nil, fmt.Errorf("while resolving a path: %w", err)
171 }
172 tpmf, err := os.ReadDir(tpms)
173 if err != nil {
174 return nil, fmt.Errorf("failed to read TPM directory: %w", err)
175 }
176 for _, file := range tpmf {
177 name := file.Name()
Tim Windelschmidt2a1d1b22024-02-06 07:07:42 +0100178 src, err := runfiles.Rlocation(filepath.Join(tpms, name))
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200179 if err != nil {
180 return nil, fmt.Errorf("while resolving a path: %w", err)
181 }
182 tgt := filepath.Join(tpmt, name)
183 if err := copyFile(src, tgt); err != nil {
184 return nil, fmt.Errorf("while copying TPM state: file %q to %q: %w", src, tgt, err)
185 }
186 }
187
188 // Create the socket directory.
189 sotdp, err := os.MkdirTemp(sd, "node_sock*")
190 if err != nil {
191 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
192 }
193
194 return &NodeRuntime{
195 ld: stdp,
196 sd: sotdp,
197 }, nil
198}
199
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200200// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200201// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200202func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200203 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200204 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanski58ddc092022-06-30 18:23:33 +0200205 r := resolver.New(c.ctxT, resolver.WithLogger(func(f string, args ...interface{}) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100206 launch.Log("Cluster: client resolver: %s", fmt.Sprintf(f, args...))
Serge Bazanski58ddc092022-06-30 18:23:33 +0200207 }))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200208 for _, n := range c.NodeIDs {
209 ep, err := resolver.NodeWithDefaultPort(n)
210 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200211 return nil, fmt.Errorf("could not add node %q by DNS: %w", n, err)
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200212 }
213 r.AddEndpoint(ep)
214 }
215 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
216 grpc.WithTransportCredentials(authCreds),
217 grpc.WithResolvers(r),
218 grpc.WithContextDialer(c.DialNode),
219 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200220 if err != nil {
221 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
222 }
223 c.authClient = authClient
224 }
225 return c.authClient, nil
226}
227
Serge Bazanski66e58952021-10-05 17:06:56 +0200228// LaunchNode launches a single Metropolis node instance with the given options.
229// The instance runs mostly paravirtualized but with some emulated hardware
230// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200231// writable, and the changes are kept across reboots and shutdowns. ld and sd
232// point to the launch directory and the socket directory, holding the nodes'
233// state files (storage, tpm state, firmware state), and UNIX socket files
234// (swtpm <-> QEMU interplay) respectively. The directories must exist before
235// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
236// if either are not initialized.
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200237func LaunchNode(ctx context.Context, ld, sd string, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200238 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
239 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200240 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
241 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
242 // that we open and pass the name of it to QEMU. Not pinning this crashes both
243 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
244 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200245
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200246 // If it's the node's first start, set up its runtime directories.
247 if options.Runtime == nil {
248 r, err := setupRuntime(ld, sd)
249 if err != nil {
250 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200251 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200252 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200253 }
254
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200255 // Replace the node's context with a new one.
256 r := options.Runtime
257 if r.CtxC != nil {
258 r.CtxC()
259 }
260 r.ctxT, r.CtxC = context.WithCancel(ctx)
261
Serge Bazanski66e58952021-10-05 17:06:56 +0200262 var qemuNetType string
263 var qemuNetConfig launch.QemuValue
264 if options.ConnectToSocket != nil {
265 qemuNetType = "socket"
266 qemuNetConfig = launch.QemuValue{
267 "id": {"net0"},
268 "fd": {"3"},
269 }
270 } else {
271 qemuNetType = "user"
272 qemuNetConfig = launch.QemuValue{
273 "id": {"net0"},
274 "net": {"10.42.0.0/24"},
275 "dhcpstart": {"10.42.0.10"},
276 "hostfwd": options.Ports.ToQemuForwards(),
277 }
278 }
279
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200280 // Generate the node's MAC address if it isn't already set in NodeOptions.
281 if options.Mac == nil {
282 mac, err := generateRandomEthernetMAC()
283 if err != nil {
284 return err
285 }
286 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200287 }
288
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100289 ovmfCodePath, err := runfiles.Rlocation("edk2/OVMF_CODE.fd")
290 if err != nil {
291 return err
292 }
293
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200294 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
295 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200296 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200297 qemuArgs := []string{
Serge Bazanski99b02142024-04-17 16:33:28 +0200298 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults", "-m", "2048",
Serge Bazanski66e58952021-10-05 17:06:56 +0200299 "-cpu", "host", "-smp", "sockets=1,cpus=1,cores=2,threads=2,maxcpus=4",
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100300 "-drive", "if=pflash,format=raw,readonly=on,file=" + ovmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200301 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200302 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200303 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200304 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200305 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
306 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
307 "-device", "tpm-tis,tpmdev=tpm0",
308 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200309 "-serial", "stdio",
310 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200311
312 if !options.AllowReboot {
313 qemuArgs = append(qemuArgs, "-no-reboot")
314 }
315
316 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200317 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200318 parametersRaw, err := proto.Marshal(options.NodeParameters)
319 if err != nil {
320 return fmt.Errorf("failed to encode node paraeters: %w", err)
321 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200322 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200323 return fmt.Errorf("failed to write node parameters: %w", err)
324 }
325 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
326 }
327
Leopoldacfad5b2023-01-15 14:05:25 +0100328 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200329 qemuNetDump := launch.QemuValue{
330 "id": {"net0"},
331 "netdev": {"net0"},
332 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100333 }
334 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
335 }
336
Serge Bazanski66e58952021-10-05 17:06:56 +0200337 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200338 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200339
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200340 tpmd := filepath.Join(r.ld, "tpm")
341 tpmEmuCmd := exec.CommandContext(tpmCtx, "swtpm", "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanski66e58952021-10-05 17:06:56 +0200342 tpmEmuCmd.Stderr = os.Stderr
343 tpmEmuCmd.Stdout = os.Stdout
344
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100345 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200346 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200347 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200348 return fmt.Errorf("failed to start TPM emulator: %w", err)
349 }
350
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200351 // Wait for the socket to be created by the TPM emulator before launching
352 // QEMU.
353 for {
354 _, err := os.Stat(tpmSocketPath)
355 if err == nil {
356 break
357 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200358 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200359 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200360 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
361 }
362 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200363 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200364 return fmt.Errorf("while waiting for the TPM socket: %w", err)
365 }
366 time.Sleep(time.Millisecond * 100)
367 }
368
Serge Bazanski66e58952021-10-05 17:06:56 +0200369 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200370 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200371 if options.ConnectToSocket != nil {
372 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
373 }
374
375 var stdErrBuf bytes.Buffer
376 systemCmd.Stderr = &stdErrBuf
377 systemCmd.Stdout = options.SerialPort
378
Leopoldaf5086b2023-01-15 14:12:42 +0100379 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
380
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200381 go func() {
382 launch.Log("Node: Starting...")
383 err = systemCmd.Run()
384 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200385
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200386 // Stop TPM emulator and wait for it to exit to properly reap the child process
387 tpmCancel()
388 launch.Log("Node: Waiting for TPM emulator to exit")
389 // Wait returns a SIGKILL error because we just cancelled its context.
390 // We still need to call it to avoid creating zombies.
391 errTpm := tpmEmuCmd.Wait()
392 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200393
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200394 var exerr *exec.ExitError
395 if err != nil && errors.As(err, &exerr) {
396 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
397 if status.Signaled() && status.Signal() == syscall.SIGKILL {
398 // Process was killed externally (most likely by our context being canceled).
399 // This is a normal exit for us, so return nil
400 doneC <- nil
401 return
402 }
403 exerr.Stderr = stdErrBuf.Bytes()
404 newErr := launch.QEMUError(*exerr)
405 launch.Log("Node: %q", stdErrBuf.String())
406 doneC <- &newErr
407 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200408 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200409 doneC <- err
410 }()
411 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200412}
413
414func copyFile(src, dst string) error {
415 in, err := os.Open(src)
416 if err != nil {
417 return fmt.Errorf("when opening source: %w", err)
418 }
419 defer in.Close()
420
421 out, err := os.Create(dst)
422 if err != nil {
423 return fmt.Errorf("when creating destination: %w", err)
424 }
425 defer out.Close()
426
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100427 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200428 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100429 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200430 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100431
432 // Copy the file while preserving its sparseness. The image files are very
433 // sparse (less than 10% allocated), so this is a lot faster.
434 var lastHoleStart int64
435 for {
436 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
437 if err != nil {
438 return fmt.Errorf("when seeking to next data block: %w", err)
439 }
440 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
441 if err != nil {
442 return fmt.Errorf("when seeking to next hole: %w", err)
443 }
444 lastHoleStart = holeStart
445 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
446 return fmt.Errorf("when seeking to current data block: %w", err)
447 }
448 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
449 return fmt.Errorf("when seeking output to next data block: %w", err)
450 }
451 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
452 return fmt.Errorf("when copying file: %w", err)
453 }
454 if endPos == holeStart {
455 // The next hole is at the end of the file, we're done here.
456 break
457 }
458 }
459
Serge Bazanski66e58952021-10-05 17:06:56 +0200460 return out.Close()
461}
462
Serge Bazanskie78a0892021-10-07 17:03:49 +0200463// getNodes wraps around Management.GetNodes to return a list of nodes in a
464// cluster.
465func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200466 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100467 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100468 err := backoff.Retry(func() error {
469 res = nil
470 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200471 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100472 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200473 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100474 for {
475 node, err := srvN.Recv()
476 if err == io.EOF {
477 break
478 }
479 if err != nil {
480 return fmt.Errorf("GetNodes.Recv: %w", err)
481 }
482 res = append(res, node)
483 }
484 return nil
485 }, bo)
486 if err != nil {
487 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200488 }
489 return res, nil
490}
491
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200492// getNode wraps Management.GetNodes. It returns node information matching
493// given node ID.
494func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
495 nodes, err := getNodes(ctx, mgmt)
496 if err != nil {
497 return nil, fmt.Errorf("could not get nodes: %w", err)
498 }
499 for _, n := range nodes {
500 eid := identity.NodeID(n.Pubkey)
501 if eid != id {
502 continue
503 }
504 return n, nil
505 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200506 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200507}
508
Serge Bazanski66e58952021-10-05 17:06:56 +0200509// Gets a random EUI-48 Ethernet MAC address
510func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
511 macBuf := make([]byte, 6)
512 _, err := rand.Read(macBuf)
513 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200514 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200515 }
516
517 // Set U/L bit and clear I/G bit (locally administered individual MAC)
518 // Ref IEEE 802-2014 Section 8.2.2
519 macBuf[0] = (macBuf[0] | 2) & 0xfe
520 mac := net.HardwareAddr(macBuf)
521 return &mac, nil
522}
523
Serge Bazanskibe742842022-04-04 13:18:50 +0200524const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200525
Serge Bazanskibe742842022-04-04 13:18:50 +0200526// ClusterPorts contains all ports handled by Nanoswitch.
527var ClusterPorts = []uint16{
528 // Forwarded to the first node.
529 uint16(node.CuratorServicePort),
530 uint16(node.DebugServicePort),
531 uint16(node.KubernetesAPIPort),
532 uint16(node.KubernetesAPIWrappedPort),
533
534 // SOCKS proxy to the switch network
535 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200536}
537
538// ClusterOptions contains all options for launching a Metropolis cluster.
539type ClusterOptions struct {
540 // The number of nodes this cluster should be started with.
541 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100542
543 // If true, node logs will be saved to individual files instead of being printed
544 // out to stderr. The path of these files will be still printed to stdout.
545 //
546 // The files will be located within the launch directory inside TEST_TMPDIR (or
547 // the default tempdir location, if not set).
548 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200549
550 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
551 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
552 // incomplete.
553 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200554
555 // Optional local registry which will be made available to the cluster to
556 // pull images from. This is a more efficient alternative to preseeding all
557 // images used for testing.
558 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200559
560 // InitialClusterConfiguration will be passed to the first node when creating the
561 // cluster, and defines some basic properties of the cluster. If not specified,
562 // the cluster will default to defaults as defined in
563 // metropolis.proto.api.NodeParameters.
564 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200565}
566
567// Cluster is the running Metropolis cluster launched using the LaunchCluster
568// function.
569type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200570 // Owner is the TLS Certificate of the owner of the test cluster. This can be
571 // used to authenticate further clients to the running cluster.
572 Owner tls.Certificate
573 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200574 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200575 Ports launch.PortMap
576
Serge Bazanskibe742842022-04-04 13:18:50 +0200577 // Nodes is a map from Node ID to its runtime information.
578 Nodes map[string]*NodeInCluster
579 // NodeIDs is a list of node IDs that are backing this cluster, in order of
580 // creation.
581 NodeIDs []string
582
Serge Bazanski54e212a2023-06-14 13:45:11 +0200583 // CACertificate is the cluster's CA certificate.
584 CACertificate *x509.Certificate
585
Serge Bazanski66e58952021-10-05 17:06:56 +0200586 // nodesDone is a list of channels populated with the return codes from all the
587 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100588 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200589 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200590 // nodeOpts are the cluster member nodes' mutable launch options, kept here
591 // to facilitate reboots.
592 nodeOpts []NodeOptions
593 // launchDir points at the directory keeping the nodes' state, such as storage
594 // images, firmware variable files, TPM state.
595 launchDir string
596 // socketDir points at the directory keeping UNIX socket files, such as these
597 // used to facilitate communication between QEMU and swtpm. It's different
598 // from launchDir, and anchored nearer the file system root, due to the
599 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100600 socketDir string
601 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200602
Lorenz Brun276a7462023-07-12 21:28:54 +0200603 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200604 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200605 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200606
607 // authClient is a cached authenticated owner connection to a Curator
608 // instance within the cluster.
609 authClient *grpc.ClientConn
610
611 // ctxT is the context individual node contexts are created from.
612 ctxT context.Context
613 // ctxC is used by Close to cancel the context under which the nodes are
614 // running.
615 ctxC context.CancelFunc
Serge Bazanskibe742842022-04-04 13:18:50 +0200616}
617
618// NodeInCluster represents information about a node that's part of a Cluster.
619type NodeInCluster struct {
620 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200621 ID string
622 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200623 // Address of the node on the network ran by nanoswitch. Not reachable from the
624 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
625 // on Cluster.Ports[SOCKSPort]).
626 ManagementAddress string
627}
628
629// firstConnection performs the initial owner credential escrow with a newly
630// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
631// running at 10.1.0.2, which is always the case with the current nanoswitch
632// implementation.
633//
Leopold20a036e2023-01-15 00:17:19 +0100634// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200635// information as NodeInCluster.
636func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
637 // Dial external service.
638 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100639 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200640 if err != nil {
641 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
642 }
643 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
644 return socksDialer.Dial("tcp", addr)
645 }
646 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
647 if err != nil {
648 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
649 }
650 defer initClient.Close()
651
652 // Retrieve owner certificate - this can take a while because the node is still
653 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100654 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200655 aaa := apb.NewAAAClient(initClient)
656 var cert *tls.Certificate
657 err = backoff.Retry(func() error {
658 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
659 if st, ok := status.FromError(err); ok {
660 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100661 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200662 return err
663 }
664 }
665 return backoff.Permanent(err)
666 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
667 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200668 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200669 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100670 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200671
672 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200673 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200674 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
675 if err != nil {
676 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
677 }
678 defer authClient.Close()
679 mgmt := apb.NewManagementClient(authClient)
680
681 var node *NodeInCluster
682 err = backoff.Retry(func() error {
683 nodes, err := getNodes(ctx, mgmt)
684 if err != nil {
685 return fmt.Errorf("retrieving nodes failed: %w", err)
686 }
687 if len(nodes) != 1 {
688 return fmt.Errorf("expected one node, got %d", len(nodes))
689 }
690 n := nodes[0]
691 if n.Status == nil || n.Status.ExternalAddress == "" {
692 return fmt.Errorf("node has no status and/or address")
693 }
694 node = &NodeInCluster{
695 ID: identity.NodeID(n.Pubkey),
696 ManagementAddress: n.Status.ExternalAddress,
697 }
698 return nil
699 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
700 if err != nil {
701 return nil, nil, err
702 }
703
704 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200705}
706
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100707func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200708 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100709 if err != nil {
710 return nil, err
711 }
712 return f, nil
713}
714
Serge Bazanski66e58952021-10-05 17:06:56 +0200715// LaunchCluster launches a cluster of Metropolis node VMs together with a
716// Nanoswitch instance to network them all together.
717//
718// The given context will be used to run all qemu instances in the cluster, and
719// canceling the context or calling Close() will terminate them.
720func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200721 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200722 return nil, errors.New("refusing to start cluster with zero nodes")
723 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200724
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200725 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100726 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200727 if err != nil {
728 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
729 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100730 // Create the metroctl config directory. We keep it in /tmp because in some
731 // scenarios it's end-user visible and we want it short.
732 md, err := os.MkdirTemp("/tmp", "metroctl-*")
733 if err != nil {
734 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
735 }
736
737 // Create the socket directory. We keep it in /tmp because of socket path limits.
738 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200739 if err != nil {
740 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
741 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200742
743 // Prepare links between nodes and nanoswitch.
744 var switchPorts []*os.File
745 var vmPorts []*os.File
746 for i := 0; i < opts.NumNodes; i++ {
747 switchPort, vmPort, err := launch.NewSocketPair()
748 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200749 return nil, fmt.Errorf("failed to get socketpair: %w", err)
750 }
751 switchPorts = append(switchPorts, switchPort)
752 vmPorts = append(vmPorts, vmPort)
753 }
754
Serge Bazanskie78a0892021-10-07 17:03:49 +0200755 // Make a list of channels that will be populated by all running node qemu
756 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200757 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200758 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200759 done[i] = make(chan error, 1)
760 }
761
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200762 // Prepare the node options. These will be kept as part of Cluster.
763 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
764 // launch. The runtime information can be later used to restart a node.
765 // The 0th node will be initialized first. The rest will follow after it
766 // had bootstrapped the cluster.
767 nodeOpts := make([]NodeOptions, opts.NumNodes)
768 nodeOpts[0] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100769 Name: "node0",
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200770 ConnectToSocket: vmPorts[0],
771 NodeParameters: &apb.NodeParameters{
772 Cluster: &apb.NodeParameters_ClusterBootstrap_{
773 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
Serge Bazanskie564f172024-04-03 12:06:06 +0200774 OwnerPublicKey: InsecurePublicKey,
775 InitialClusterConfiguration: opts.InitialClusterConfiguration,
Serge Bazanski66e58952021-10-05 17:06:56 +0200776 },
777 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200778 },
779 SerialPort: newPrefixedStdio(0),
Leopoldacfad5b2023-01-15 14:05:25 +0100780 PcapDump: true,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200781 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100782 if opts.NodeLogsToFiles {
783 path := path.Join(ld, "node-1.txt")
784 port, err := NewSerialFileLogger(path)
785 if err != nil {
786 return nil, fmt.Errorf("could not open log file for node 1: %w", err)
787 }
788 launch.Log("Node 1 logs at %s", path)
789 nodeOpts[0].SerialPort = port
790 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200791
792 // Start the first node.
793 ctxT, ctxC := context.WithCancel(ctx)
Serge Bazanski05f813b2023-03-16 17:58:39 +0100794 launch.Log("Cluster: Starting node %d...", 1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200795 if err := LaunchNode(ctxT, ld, sd, &nodeOpts[0], done[0]); err != nil {
796 ctxC()
797 return nil, fmt.Errorf("failed to launch first node: %w", err)
798 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200799
Lorenz Brun150f24a2023-07-13 20:11:06 +0200800 localRegistryAddr := net.TCPAddr{
801 IP: net.IPv4(10, 42, 0, 82),
802 Port: 5000,
803 }
804
805 var guestSvcMap launch.GuestServiceMap
806 if opts.LocalRegistry != nil {
807 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
808 if err != nil {
809 ctxC()
810 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
811 }
812 s := http.Server{
813 Handler: opts.LocalRegistry,
814 }
815 go s.Serve(l)
816 go func() {
817 <-ctxT.Done()
818 s.Close()
819 }()
820 guestSvcMap = launch.GuestServiceMap{
821 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
822 }
823 }
824
Serge Bazanskie78a0892021-10-07 17:03:49 +0200825 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200826 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
827 if err != nil {
828 ctxC()
829 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
830 }
831
832 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100833 var serialPort io.ReadWriter
834 if opts.NodeLogsToFiles {
835 path := path.Join(ld, "nanoswitch.txt")
836 serialPort, err = NewSerialFileLogger(path)
837 if err != nil {
838 launch.Log("Could not open log file for nanoswitch: %v", err)
839 }
840 launch.Log("Nanoswitch logs at %s", path)
841 } else {
842 serialPort = newPrefixedStdio(99)
843 }
Serge Bazanskie84726b2024-04-17 16:32:32 +0200844 kernelPath, err := runfiles.Rlocation("_main/metropolis/test/ktest/vmlinux")
845 if err != nil {
846 launch.Fatal("Failed to resolved nanoswitch kernel: %v", err)
847 }
848 initramfsPath, err := runfiles.Rlocation("_main/metropolis/test/nanoswitch/initramfs.cpio.zst")
849 if err != nil {
850 launch.Fatal("Failed to resolved nanoswitch initramfs: %v", err)
851 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200852 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100853 Name: "nanoswitch",
Serge Bazanskie84726b2024-04-17 16:32:32 +0200854 KernelPath: kernelPath,
855 InitramfsPath: initramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200856 ExtraNetworkInterfaces: switchPorts,
857 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200858 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100859 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100860 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200861 }); err != nil {
862 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100863 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200864 }
865 }
866 }()
867
Serge Bazanskibe742842022-04-04 13:18:50 +0200868 // Build SOCKS dialer.
869 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
870 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200871 if err != nil {
872 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200873 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200874 }
875
Serge Bazanskibe742842022-04-04 13:18:50 +0200876 // Retrieve owner credentials and first node.
877 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200878 if err != nil {
879 ctxC()
880 return nil, err
881 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200882
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100883 // Write credentials to the metroctl directory.
884 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
885 ctxC()
886 return nil, fmt.Errorf("could not write owner key: %w", err)
887 }
888 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
889 ctxC()
890 return nil, fmt.Errorf("could not write owner certificate: %w", err)
891 }
892
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200893 // Set up a partially initialized cluster instance, to be filled in in the
894 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200895 cluster := &Cluster{
896 Owner: *cert,
897 Ports: portMap,
898 Nodes: map[string]*NodeInCluster{
899 firstNode.ID: firstNode,
900 },
901 NodeIDs: []string{
902 firstNode.ID,
903 },
904
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100905 nodesDone: done,
906 nodeOpts: nodeOpts,
907 launchDir: ld,
908 socketDir: sd,
909 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200910
Lorenz Brun276a7462023-07-12 21:28:54 +0200911 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200912
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200913 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200914 ctxC: ctxC,
915 }
916
917 // Now start the rest of the nodes and register them into the cluster.
918
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200919 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200920 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200921 if err != nil {
922 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200923 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200924 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200925 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200926
927 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100928 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200929 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
930 if err != nil {
931 ctxC()
932 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
933 }
934 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100935 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200936
937 // Retrieve cluster info (for directory and ca public key) to register further
938 // nodes.
939 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
940 if err != nil {
941 ctxC()
942 return nil, fmt.Errorf("GetClusterInfo: %w", err)
943 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200944 caCert, err := x509.ParseCertificate(resI.CaCertificate)
945 if err != nil {
946 ctxC()
947 return nil, fmt.Errorf("ParseCertificate: %w", err)
948 }
949 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200950
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200951 // Use the retrieved information to configure the rest of the node options.
952 for i := 1; i < opts.NumNodes; i++ {
953 nodeOpts[i] = NodeOptions{
Leopoldaf5086b2023-01-15 14:12:42 +0100954 Name: fmt.Sprintf("node%d", i),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200955 ConnectToSocket: vmPorts[i],
956 NodeParameters: &apb.NodeParameters{
957 Cluster: &apb.NodeParameters_ClusterRegister_{
958 ClusterRegister: &apb.NodeParameters_ClusterRegister{
959 RegisterTicket: ticket,
960 ClusterDirectory: resI.ClusterDirectory,
961 CaCertificate: resI.CaCertificate,
962 },
963 },
964 },
965 SerialPort: newPrefixedStdio(i),
966 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100967 if opts.NodeLogsToFiles {
968 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i+1))
969 port, err := NewSerialFileLogger(path)
970 if err != nil {
971 return nil, fmt.Errorf("could not open log file for node %d: %w", i+1, err)
972 }
973 launch.Log("Node %d logs at %s", i+1, path)
974 nodeOpts[i].SerialPort = port
975 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200976 }
977
978 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +0200979 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100980 launch.Log("Cluster: Starting node %d...", i+1)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200981 err := LaunchNode(ctxT, ld, sd, &nodeOpts[i], done[i])
982 if err != nil {
983 return nil, fmt.Errorf("failed to launch node %d: %w", i+1, err)
984 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200985 }
Serge Bazanskie78a0892021-10-07 17:03:49 +0200986
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200987 seenNodes := make(map[string]bool)
988 launch.Log("Cluster: waiting for nodes to appear as NEW...")
989 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200990 for {
991 nodes, err := getNodes(ctx, mgmt)
992 if err != nil {
993 ctxC()
994 return nil, fmt.Errorf("could not get nodes: %w", err)
995 }
996 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200997 if n.State != cpb.NodeState_NODE_STATE_NEW {
998 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +0200999 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001000 if seenNodes[n.Id] {
1001 continue
1002 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001003 seenNodes[n.Id] = true
1004 cluster.Nodes[n.Id] = &NodeInCluster{
1005 ID: n.Id,
1006 Pubkey: n.Pubkey,
1007 }
1008 cluster.NodeIDs = append(cluster.NodeIDs, n.Id)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001009 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001010
1011 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001012 break
1013 }
1014 time.Sleep(1 * time.Second)
1015 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001016 }
1017 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001018
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001019 approvedNodes := make(map[string]bool)
1020 upNodes := make(map[string]bool)
1021 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001022 for {
1023 nodes, err := getNodes(ctx, mgmt)
1024 if err != nil {
1025 ctxC()
1026 return nil, fmt.Errorf("could not get nodes: %w", err)
1027 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001028 for _, node := range nodes {
1029 if !seenNodes[node.Id] {
1030 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001031 continue
1032 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001033
1034 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1035 launch.Log("Cluster: node %s is up", node.Id)
1036 upNodes[node.Id] = true
1037 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001038 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001039 if upNodes[node.Id] {
1040 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001041 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001042
1043 if !approvedNodes[node.Id] {
1044 launch.Log("Cluster: approving node %s", node.Id)
1045 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1046 Pubkey: node.Pubkey,
1047 })
1048 if err != nil {
1049 ctxC()
1050 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1051 }
1052 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001053 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001054 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001055
1056 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes-1, len(upNodes))
1057 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001058 break
1059 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001060 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001061 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001062 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001063
Serge Bazanski05f813b2023-03-16 17:58:39 +01001064 launch.Log("Cluster: all nodes up:")
Serge Bazanskibe742842022-04-04 13:18:50 +02001065 for _, node := range cluster.Nodes {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001066 launch.Log("Cluster: - %s at %s", node.ID, node.ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001067 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001068 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001069
Serge Bazanskibe742842022-04-04 13:18:50 +02001070 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001071}
1072
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001073// RebootNode reboots the cluster member node matching the given index, and
1074// waits for it to rejoin the cluster. It will use the given context ctx to run
1075// cluster API requests, whereas the resulting QEMU process will be created
1076// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1077func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1078 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001079 return fmt.Errorf("index out of bounds")
1080 }
1081 if c.nodeOpts[idx].Runtime == nil {
1082 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001083 }
1084 id := c.NodeIDs[idx]
1085
1086 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001087 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001088 if err != nil {
1089 return err
1090 }
1091 mgmt := apb.NewManagementClient(curC)
1092
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001093 // Cancel the node's context. This will shut down QEMU.
1094 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001095 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001096 err = <-c.nodesDone[idx]
1097 if err != nil {
1098 return fmt.Errorf("while restarting node: %w", err)
1099 }
1100
1101 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001102 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001103 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1104 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1105 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001106
Serge Bazanskibc969572024-03-21 11:56:13 +01001107 start := time.Now()
1108
1109 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001110 for {
1111 cs, err := getNode(ctx, mgmt, id)
1112 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001113 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001114 return err
1115 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001116 launch.Log("Cluster: node health: %+v", cs.Health)
1117
1118 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1119 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001120 break
1121 }
1122 time.Sleep(time.Second)
1123 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001124 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001125 return nil
1126}
1127
Serge Bazanski500f6e02024-04-03 12:06:40 +02001128// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1129// given by idx. If the node is already shut down, this is a no-op.
1130func (c *Cluster) ShutdownNode(idx int) error {
1131 if idx < 0 || idx >= len(c.NodeIDs) {
1132 return fmt.Errorf("index out of bounds")
1133 }
1134 // Return if node is already stopped.
1135 select {
1136 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1137 return nil
1138 default:
1139 }
1140 id := c.NodeIDs[idx]
1141
1142 // Cancel the node's context. This will shut down QEMU.
1143 c.nodeOpts[idx].Runtime.CtxC()
1144 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1145 err := <-c.nodesDone[idx]
1146 if err != nil {
1147 return fmt.Errorf("while shutting down node: %w", err)
1148 }
1149 return nil
1150}
1151
1152// StartNode performs a power on of the node given by idx. If the node is already
1153// running, this is a no-op.
1154func (c *Cluster) StartNode(idx int) error {
1155 if idx < 0 || idx >= len(c.NodeIDs) {
1156 return fmt.Errorf("index out of bounds")
1157 }
1158 id := c.NodeIDs[idx]
1159 // Return if node is already running.
1160 select {
1161 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1162 default:
1163 return nil
1164 }
1165
1166 // Start QEMU again.
1167 launch.Log("Cluster: starting node %d (%s).", idx, id)
1168 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
1169 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1170 }
1171 return nil
1172}
1173
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001174// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001175// nodes to stop. It returns an error if stopping the nodes failed, or one of
1176// the nodes failed to fully start in the first place.
1177func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001178 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001179 if c.authClient != nil {
1180 c.authClient.Close()
1181 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001182 c.ctxC()
1183
Leopold20a036e2023-01-15 00:17:19 +01001184 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001185 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001186 for _, c := range c.nodesDone {
1187 err := <-c
1188 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001189 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001190 }
1191 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001192 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001193 os.RemoveAll(c.launchDir)
1194 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001195 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001196 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001197 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001198}
Serge Bazanskibe742842022-04-04 13:18:50 +02001199
1200// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1201// their ID. This is performed by connecting to the cluster nanoswitch via its
1202// SOCKS proxy, and using the cluster node list for name resolution.
1203//
1204// For example:
1205//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001206// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001207func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1208 host, port, err := net.SplitHostPort(addr)
1209 if err != nil {
1210 return nil, fmt.Errorf("invalid host:port: %w", err)
1211 }
1212 // Already an IP address?
1213 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001214 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001215 }
1216
1217 // Otherwise, expect a node name.
1218 node, ok := c.Nodes[host]
1219 if !ok {
1220 return nil, fmt.Errorf("unknown node %q", host)
1221 }
1222 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001223 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001224}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001225
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001226// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1227// Kubernetes authenticating proxy using the cluster owner identity.
1228// It currently has access to everything (i.e. the cluster-admin role)
1229// via the owner-admin binding.
1230func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1231 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1232 if err != nil {
1233 // We explicitly pass an Ed25519 private key in, so this can't happen
1234 panic(err)
1235 }
1236
1237 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001238 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001239 Host: host,
1240 TLSClientConfig: rest.TLSClientConfig{
1241 // TODO(q3k): use CA certificate
1242 Insecure: true,
1243 ServerName: "kubernetes.default.svc",
1244 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1245 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1246 },
1247 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1248 return c.DialNode(ctx, address)
1249 },
1250 }
1251 return kubernetes.NewForConfig(&clientConfig)
1252}
1253
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001254// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1255// which are currently Kubernetes controllers, ie. run an apiserver. This list
1256// might be empty if no node is currently configured with the
1257// 'KubernetesController' node.
1258func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1259 curC, err := c.CuratorClient()
1260 if err != nil {
1261 return nil, err
1262 }
1263 mgmt := apb.NewManagementClient(curC)
1264 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1265 Filter: "has(node.roles.kubernetes_controller)",
1266 })
1267 if err != nil {
1268 return nil, err
1269 }
1270 defer srv.CloseSend()
1271 var res []string
1272 for {
1273 n, err := srv.Recv()
1274 if err == io.EOF {
1275 break
1276 }
1277 if err != nil {
1278 return nil, err
1279 }
1280 if n.Status == nil || n.Status.ExternalAddress == "" {
1281 continue
1282 }
1283 res = append(res, n.Status.ExternalAddress)
1284 }
1285 return res, nil
1286}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001287
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001288// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1289// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001290func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1291 // Get an authenticated owner client within the cluster.
1292 curC, err := c.CuratorClient()
1293 if err != nil {
1294 return err
1295 }
1296 mgmt := apb.NewManagementClient(curC)
1297 nodes, err := getNodes(ctx, mgmt)
1298 if err != nil {
1299 return err
1300 }
1301
1302 var unhealthy []string
1303 for _, node := range nodes {
1304 if node.Health == apb.Node_HEALTHY {
1305 continue
1306 }
1307 unhealthy = append(unhealthy, node.Id)
1308 }
1309 if len(unhealthy) == 0 {
1310 return nil
1311 }
1312 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1313}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001314
1315// ApproveNode approves a node by ID, waiting for it to become UP.
1316func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1317 curC, err := c.CuratorClient()
1318 if err != nil {
1319 return err
1320 }
1321 mgmt := apb.NewManagementClient(curC)
1322
1323 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1324 Pubkey: c.Nodes[id].Pubkey,
1325 })
1326 if err != nil {
1327 return fmt.Errorf("ApproveNode: %w", err)
1328 }
1329 launch.Log("Cluster: %s: approved, waiting for UP", id)
1330 for {
1331 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1332 if err != nil {
1333 return fmt.Errorf("GetNodes: %w", err)
1334 }
1335 found := false
1336 for {
1337 node, err := nodes.Recv()
1338 if errors.Is(err, io.EOF) {
1339 break
1340 }
1341 if err != nil {
1342 return fmt.Errorf("Nodes.Recv: %w", err)
1343 }
1344 if node.Id != id {
1345 continue
1346 }
1347 if node.State != cpb.NodeState_NODE_STATE_UP {
1348 continue
1349 }
1350 found = true
1351 break
1352 }
1353 nodes.CloseSend()
1354
1355 if found {
1356 break
1357 }
1358 time.Sleep(time.Second)
1359 }
1360 launch.Log("Cluster: %s: UP", id)
1361 return nil
1362}
1363
1364// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1365func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1366 curC, err := c.CuratorClient()
1367 if err != nil {
1368 return err
1369 }
1370 mgmt := apb.NewManagementClient(curC)
1371
1372 tr := true
1373 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1374 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1375 Node: &apb.UpdateNodeRolesRequest_Id{
1376 Id: id,
1377 },
1378 KubernetesWorker: &tr,
1379 })
1380 return err
1381}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001382
1383// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1384func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1385 curC, err := c.CuratorClient()
1386 if err != nil {
1387 return err
1388 }
1389 mgmt := apb.NewManagementClient(curC)
1390 cur := ipb.NewCuratorClient(curC)
1391
1392 tr := true
1393 launch.Log("Cluster: %s: adding ConsensusMember", id)
1394 bo := backoff.NewExponentialBackOff()
1395 bo.MaxElapsedTime = 10 * time.Second
1396
1397 backoff.Retry(func() error {
1398 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1399 Node: &apb.UpdateNodeRolesRequest_Id{
1400 Id: id,
1401 },
1402 ConsensusMember: &tr,
1403 })
1404 if err != nil {
1405 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1406 }
1407 return err
1408 }, backoff.WithContext(bo, ctx))
1409 if err != nil {
1410 return err
1411 }
1412
1413 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1414
1415 learner := false
1416 for {
1417 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1418 if err != nil {
1419 return fmt.Errorf("GetConsensusStatus: %w", err)
1420 }
1421 for _, member := range res.EtcdMember {
1422 if member.Id != id {
1423 continue
1424 }
1425 switch member.Status {
1426 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1427 if !learner {
1428 learner = true
1429 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1430 }
1431 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1432 launch.Log("Cluster: %s: became a full member", id)
1433 return nil
1434 }
1435 }
1436 time.Sleep(100 * time.Millisecond)
1437 }
1438}