blob: 29096b8a0bcde72b05e69fca17ca48294a4c8661 [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.
Tim Windelschmidt9f21f532024-05-07 15:14:20 +02005package launch
Serge Bazanski66e58952021-10-05 17:06:56 +02006
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 Bazanski53458ba2024-06-18 09:56:46 +000024 "strconv"
Serge Bazanski630fb5c2023-04-06 10:50:24 +020025 "strings"
Serge Bazanski66e58952021-10-05 17:06:56 +020026 "syscall"
27 "time"
28
29 "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"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020050 "source.monogon.dev/metropolis/test/localregistry"
51 "source.monogon.dev/osbase/test/launch"
Serge Bazanski66e58952021-10-05 17:06:56 +020052)
53
Serge Bazanski53458ba2024-06-18 09:56:46 +000054const (
55 // nodeNumberKey is the key of the node label used to carry a node's numerical
56 // index in the test system.
57 nodeNumberKey string = "test-node-number"
58)
59
Leopold20a036e2023-01-15 00:17:19 +010060// NodeOptions contains all options that can be passed to Launch()
Serge Bazanski66e58952021-10-05 17:06:56 +020061type NodeOptions struct {
Leopoldaf5086b2023-01-15 14:12:42 +010062 // Name is a human-readable identifier to be used in debug output.
63 Name string
64
Jan Schära9b060b2024-08-07 10:42:29 +020065 // CPUs is the number of virtual CPUs of the VM.
66 CPUs int
67
68 // ThreadsPerCPU is the number of threads per CPU. This is multiplied by
69 // CPUs to get the total number of threads.
70 ThreadsPerCPU int
71
72 // MemoryMiB is the RAM size in MiB of the VM.
73 MemoryMiB int
74
Serge Bazanski66e58952021-10-05 17:06:56 +020075 // Ports contains the port mapping where to expose the internal ports of the VM to
76 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
77 // ConnectToSocket is set.
78 Ports launch.PortMap
79
Leopold20a036e2023-01-15 00:17:19 +010080 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
81 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020082 // want to test reboot behavior this should be false.
83 AllowReboot bool
84
Leopold20a036e2023-01-15 00:17:19 +010085 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
86 // set, it is instead connected to the given file descriptor/socket. If this is
87 // set, all port maps from the Ports option are ignored. Intended for networking
88 // this instance together with others for running more complex network
89 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020090 ConnectToSocket *os.File
91
Leopoldacfad5b2023-01-15 14:05:25 +010092 // When PcapDump is set, all traffic is dumped to a pcap file in the
93 // runtime directory (e.g. "net0.pcap" for the first interface).
94 PcapDump bool
95
Leopold20a036e2023-01-15 00:17:19 +010096 // SerialPort is an io.ReadWriter over which you can communicate with the serial
97 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +020098 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
99 SerialPort io.ReadWriter
100
101 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
102 // registering into a cluster.
103 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200104
105 // Mac is the node's MAC address.
106 Mac *net.HardwareAddr
107
108 // Runtime keeps the node's QEMU runtime state.
109 Runtime *NodeRuntime
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200110
111 // RunVNC starts a VNC socket for troubleshooting/testing console code. Note:
112 // this will not work in tests, as those use a built-in qemu which does not
113 // implement a VGA device.
114 RunVNC bool
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200115}
116
Leopold20a036e2023-01-15 00:17:19 +0100117// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200118type NodeRuntime struct {
119 // ld points at the node's launch directory storing data such as storage
120 // images, firmware variables or the TPM state.
121 ld string
122 // sd points at the node's socket directory.
123 sd string
124
125 // ctxT is the context QEMU will execute in.
126 ctxT context.Context
127 // CtxC is the QEMU context's cancellation function.
128 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200129}
130
131// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200132var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200133 node.ConsensusPort,
134
135 node.CuratorServicePort,
136 node.DebugServicePort,
137
138 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100139 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200140 node.CuratorServicePort,
141 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200142 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200143}
144
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200145// setupRuntime creates the node's QEMU runtime directory, together with all
146// files required to preserve its state, a level below the chosen path ld. The
147// node's socket directory is similarily created a level below sd. It may
148// return an I/O error.
149func setupRuntime(ld, sd string) (*NodeRuntime, error) {
150 // Create a temporary directory to keep all the runtime files.
151 stdp, err := os.MkdirTemp(ld, "node_state*")
152 if err != nil {
153 return nil, fmt.Errorf("failed to create the state directory: %w", err)
154 }
155
156 // Initialize the node's storage with a prebuilt image.
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200157 di := filepath.Join(stdp, "image.qcow2")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000158 launch.Log("Cluster: generating node QCOW2 snapshot image: %s -> %s", xNodeImagePath, di)
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200159
160 df, err := os.Create(di)
161 if err != nil {
162 return nil, fmt.Errorf("while opening image for writing: %w", err)
163 }
164 defer df.Close()
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000165 if err := qcow2.Generate(df, qcow2.GenerateWithBackingFile(xNodeImagePath)); err != nil {
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200166 return nil, fmt.Errorf("while creating copy-on-write node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200167 }
168
169 // Initialize the OVMF firmware variables file.
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000170 dv := filepath.Join(stdp, filepath.Base(xOvmfVarsPath))
171 if err := copyFile(xOvmfVarsPath, dv); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200172 return nil, fmt.Errorf("while copying firmware variables: %w", err)
173 }
174
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200175 // Create the socket directory.
176 sotdp, err := os.MkdirTemp(sd, "node_sock*")
177 if err != nil {
178 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
179 }
180
181 return &NodeRuntime{
182 ld: stdp,
183 sd: sotdp,
184 }, nil
185}
186
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200187// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200188// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200189func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200190 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200191 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanski58ddc092022-06-30 18:23:33 +0200192 r := resolver.New(c.ctxT, resolver.WithLogger(func(f string, args ...interface{}) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100193 launch.Log("Cluster: client resolver: %s", fmt.Sprintf(f, args...))
Serge Bazanski58ddc092022-06-30 18:23:33 +0200194 }))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200195 for _, n := range c.NodeIDs {
196 ep, err := resolver.NodeWithDefaultPort(n)
197 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200198 return nil, fmt.Errorf("could not add node %q by DNS: %w", n, err)
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200199 }
200 r.AddEndpoint(ep)
201 }
202 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
203 grpc.WithTransportCredentials(authCreds),
204 grpc.WithResolvers(r),
205 grpc.WithContextDialer(c.DialNode),
206 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200207 if err != nil {
208 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
209 }
210 c.authClient = authClient
211 }
212 return c.authClient, nil
213}
214
Serge Bazanski66e58952021-10-05 17:06:56 +0200215// LaunchNode launches a single Metropolis node instance with the given options.
216// The instance runs mostly paravirtualized but with some emulated hardware
217// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200218// writable, and the changes are kept across reboots and shutdowns. ld and sd
219// point to the launch directory and the socket directory, holding the nodes'
220// state files (storage, tpm state, firmware state), and UNIX socket files
221// (swtpm <-> QEMU interplay) respectively. The directories must exist before
222// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
223// if either are not initialized.
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200224func LaunchNode(ctx context.Context, ld, sd string, tpmFactory *TPMFactory, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200225 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
226 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200227 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
228 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
229 // that we open and pass the name of it to QEMU. Not pinning this crashes both
230 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
231 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200232
Jan Schära9b060b2024-08-07 10:42:29 +0200233 if options.CPUs == 0 {
234 options.CPUs = 1
235 }
236 if options.ThreadsPerCPU == 0 {
237 options.ThreadsPerCPU = 1
238 }
239 if options.MemoryMiB == 0 {
240 options.MemoryMiB = 2048
241 }
242
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200243 // If it's the node's first start, set up its runtime directories.
244 if options.Runtime == nil {
245 r, err := setupRuntime(ld, sd)
246 if err != nil {
247 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200248 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200249 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200250 }
251
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200252 // Replace the node's context with a new one.
253 r := options.Runtime
254 if r.CtxC != nil {
255 r.CtxC()
256 }
257 r.ctxT, r.CtxC = context.WithCancel(ctx)
258
Serge Bazanski66e58952021-10-05 17:06:56 +0200259 var qemuNetType string
260 var qemuNetConfig launch.QemuValue
261 if options.ConnectToSocket != nil {
262 qemuNetType = "socket"
263 qemuNetConfig = launch.QemuValue{
264 "id": {"net0"},
265 "fd": {"3"},
266 }
267 } else {
268 qemuNetType = "user"
269 qemuNetConfig = launch.QemuValue{
270 "id": {"net0"},
271 "net": {"10.42.0.0/24"},
272 "dhcpstart": {"10.42.0.10"},
273 "hostfwd": options.Ports.ToQemuForwards(),
274 }
275 }
276
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200277 // Generate the node's MAC address if it isn't already set in NodeOptions.
278 if options.Mac == nil {
279 mac, err := generateRandomEthernetMAC()
280 if err != nil {
281 return err
282 }
283 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200284 }
285
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200286 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
287 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200288 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200289 qemuArgs := []string{
Jan Schära9b060b2024-08-07 10:42:29 +0200290 "-machine", "q35",
291 "-accel", "kvm",
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200292 "-display", "none",
Jan Schära9b060b2024-08-07 10:42:29 +0200293 "-nodefaults",
294 "-cpu", "host",
295 "-m", fmt.Sprintf("%dM", options.MemoryMiB),
296 "-smp", fmt.Sprintf("cores=%d,threads=%d", options.CPUs, options.ThreadsPerCPU),
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000297 "-drive", "if=pflash,format=raw,readonly=on,file=" + xOvmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200298 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200299 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200300 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200301 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200302 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
303 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
304 "-device", "tpm-tis,tpmdev=tpm0",
305 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200306 "-serial", "stdio",
307 }
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200308 if options.RunVNC {
309 vncSocketPath := filepath.Join(r.sd, "vnc-socket")
310 qemuArgs = append(qemuArgs,
311 "-vnc", "unix:"+vncSocketPath,
312 "-device", "virtio-vga",
313 )
314 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200315
316 if !options.AllowReboot {
317 qemuArgs = append(qemuArgs, "-no-reboot")
318 }
319
320 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200321 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200322 parametersRaw, err := proto.Marshal(options.NodeParameters)
323 if err != nil {
324 return fmt.Errorf("failed to encode node paraeters: %w", err)
325 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200326 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200327 return fmt.Errorf("failed to write node parameters: %w", err)
328 }
329 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
330 }
331
Leopoldacfad5b2023-01-15 14:05:25 +0100332 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200333 qemuNetDump := launch.QemuValue{
334 "id": {"net0"},
335 "netdev": {"net0"},
336 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100337 }
338 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
339 }
340
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200341 // Manufacture TPM if needed.
342 tpmd := filepath.Join(r.ld, "tpm")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000343 err := tpmFactory.Manufacture(ctx, tpmd, &TPMPlatform{
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200344 Manufacturer: "Monogon",
345 Version: "1.0",
346 Model: "TestCluster",
347 })
348 if err != nil {
349 return fmt.Errorf("could not manufacture TPM: %w", err)
350 }
351
Serge Bazanski66e58952021-10-05 17:06:56 +0200352 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200353 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200354
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000355 tpmEmuCmd := exec.CommandContext(tpmCtx, xSwtpmPath, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000356 // Silence warnings from unsafe libtpms build (uses non-constant-time
357 // cryptographic operations).
358 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200359 tpmEmuCmd.Stderr = os.Stderr
360 tpmEmuCmd.Stdout = os.Stdout
361
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100362 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200363 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200364 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200365 return fmt.Errorf("failed to start TPM emulator: %w", err)
366 }
367
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200368 // Wait for the socket to be created by the TPM emulator before launching
369 // QEMU.
370 for {
371 _, err := os.Stat(tpmSocketPath)
372 if err == nil {
373 break
374 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200375 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200376 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200377 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
378 }
379 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200380 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200381 return fmt.Errorf("while waiting for the TPM socket: %w", err)
382 }
383 time.Sleep(time.Millisecond * 100)
384 }
385
Serge Bazanski66e58952021-10-05 17:06:56 +0200386 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200387 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200388 if options.ConnectToSocket != nil {
389 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
390 }
391
392 var stdErrBuf bytes.Buffer
393 systemCmd.Stderr = &stdErrBuf
394 systemCmd.Stdout = options.SerialPort
395
Leopoldaf5086b2023-01-15 14:12:42 +0100396 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
397
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200398 go func() {
399 launch.Log("Node: Starting...")
400 err = systemCmd.Run()
401 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200402
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200403 // Stop TPM emulator and wait for it to exit to properly reap the child process
404 tpmCancel()
405 launch.Log("Node: Waiting for TPM emulator to exit")
406 // Wait returns a SIGKILL error because we just cancelled its context.
407 // We still need to call it to avoid creating zombies.
408 errTpm := tpmEmuCmd.Wait()
409 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200410
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200411 var exerr *exec.ExitError
412 if err != nil && errors.As(err, &exerr) {
413 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
414 if status.Signaled() && status.Signal() == syscall.SIGKILL {
415 // Process was killed externally (most likely by our context being canceled).
416 // This is a normal exit for us, so return nil
417 doneC <- nil
418 return
419 }
420 exerr.Stderr = stdErrBuf.Bytes()
421 newErr := launch.QEMUError(*exerr)
422 launch.Log("Node: %q", stdErrBuf.String())
423 doneC <- &newErr
424 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200425 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200426 doneC <- err
427 }()
428 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200429}
430
431func copyFile(src, dst string) error {
432 in, err := os.Open(src)
433 if err != nil {
434 return fmt.Errorf("when opening source: %w", err)
435 }
436 defer in.Close()
437
438 out, err := os.Create(dst)
439 if err != nil {
440 return fmt.Errorf("when creating destination: %w", err)
441 }
442 defer out.Close()
443
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100444 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200445 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100446 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200447 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100448
449 // Copy the file while preserving its sparseness. The image files are very
450 // sparse (less than 10% allocated), so this is a lot faster.
451 var lastHoleStart int64
452 for {
453 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
454 if err != nil {
455 return fmt.Errorf("when seeking to next data block: %w", err)
456 }
457 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
458 if err != nil {
459 return fmt.Errorf("when seeking to next hole: %w", err)
460 }
461 lastHoleStart = holeStart
462 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
463 return fmt.Errorf("when seeking to current data block: %w", err)
464 }
465 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
466 return fmt.Errorf("when seeking output to next data block: %w", err)
467 }
468 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
469 return fmt.Errorf("when copying file: %w", err)
470 }
471 if endPos == holeStart {
472 // The next hole is at the end of the file, we're done here.
473 break
474 }
475 }
476
Serge Bazanski66e58952021-10-05 17:06:56 +0200477 return out.Close()
478}
479
Serge Bazanskie78a0892021-10-07 17:03:49 +0200480// getNodes wraps around Management.GetNodes to return a list of nodes in a
481// cluster.
482func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200483 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100484 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100485 err := backoff.Retry(func() error {
486 res = nil
487 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200488 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100489 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200490 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100491 for {
492 node, err := srvN.Recv()
493 if err == io.EOF {
494 break
495 }
496 if err != nil {
497 return fmt.Errorf("GetNodes.Recv: %w", err)
498 }
499 res = append(res, node)
500 }
501 return nil
502 }, bo)
503 if err != nil {
504 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200505 }
506 return res, nil
507}
508
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200509// getNode wraps Management.GetNodes. It returns node information matching
510// given node ID.
511func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
512 nodes, err := getNodes(ctx, mgmt)
513 if err != nil {
514 return nil, fmt.Errorf("could not get nodes: %w", err)
515 }
516 for _, n := range nodes {
517 eid := identity.NodeID(n.Pubkey)
518 if eid != id {
519 continue
520 }
521 return n, nil
522 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200523 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200524}
525
Serge Bazanski66e58952021-10-05 17:06:56 +0200526// Gets a random EUI-48 Ethernet MAC address
527func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
528 macBuf := make([]byte, 6)
529 _, err := rand.Read(macBuf)
530 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200531 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200532 }
533
534 // Set U/L bit and clear I/G bit (locally administered individual MAC)
535 // Ref IEEE 802-2014 Section 8.2.2
536 macBuf[0] = (macBuf[0] | 2) & 0xfe
537 mac := net.HardwareAddr(macBuf)
538 return &mac, nil
539}
540
Serge Bazanskibe742842022-04-04 13:18:50 +0200541const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200542
Serge Bazanskibe742842022-04-04 13:18:50 +0200543// ClusterPorts contains all ports handled by Nanoswitch.
544var ClusterPorts = []uint16{
545 // Forwarded to the first node.
546 uint16(node.CuratorServicePort),
547 uint16(node.DebugServicePort),
548 uint16(node.KubernetesAPIPort),
549 uint16(node.KubernetesAPIWrappedPort),
550
551 // SOCKS proxy to the switch network
552 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200553}
554
555// ClusterOptions contains all options for launching a Metropolis cluster.
556type ClusterOptions struct {
557 // The number of nodes this cluster should be started with.
558 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100559
Jan Schära9b060b2024-08-07 10:42:29 +0200560 // Node are default options of all nodes.
561 Node NodeOptions
562
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100563 // If true, node logs will be saved to individual files instead of being printed
564 // out to stderr. The path of these files will be still printed to stdout.
565 //
566 // The files will be located within the launch directory inside TEST_TMPDIR (or
567 // the default tempdir location, if not set).
568 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200569
570 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
571 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
572 // incomplete.
573 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200574
575 // Optional local registry which will be made available to the cluster to
576 // pull images from. This is a more efficient alternative to preseeding all
577 // images used for testing.
578 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200579
580 // InitialClusterConfiguration will be passed to the first node when creating the
581 // cluster, and defines some basic properties of the cluster. If not specified,
582 // the cluster will default to defaults as defined in
583 // metropolis.proto.api.NodeParameters.
584 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200585}
586
587// Cluster is the running Metropolis cluster launched using the LaunchCluster
588// function.
589type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200590 // Owner is the TLS Certificate of the owner of the test cluster. This can be
591 // used to authenticate further clients to the running cluster.
592 Owner tls.Certificate
593 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200594 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200595 Ports launch.PortMap
596
Serge Bazanskibe742842022-04-04 13:18:50 +0200597 // Nodes is a map from Node ID to its runtime information.
598 Nodes map[string]*NodeInCluster
599 // NodeIDs is a list of node IDs that are backing this cluster, in order of
600 // creation.
601 NodeIDs []string
602
Serge Bazanski54e212a2023-06-14 13:45:11 +0200603 // CACertificate is the cluster's CA certificate.
604 CACertificate *x509.Certificate
605
Serge Bazanski66e58952021-10-05 17:06:56 +0200606 // nodesDone is a list of channels populated with the return codes from all the
607 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100608 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200609 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200610 // nodeOpts are the cluster member nodes' mutable launch options, kept here
611 // to facilitate reboots.
612 nodeOpts []NodeOptions
613 // launchDir points at the directory keeping the nodes' state, such as storage
614 // images, firmware variable files, TPM state.
615 launchDir string
616 // socketDir points at the directory keeping UNIX socket files, such as these
617 // used to facilitate communication between QEMU and swtpm. It's different
618 // from launchDir, and anchored nearer the file system root, due to the
619 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100620 socketDir string
621 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200622
Lorenz Brun276a7462023-07-12 21:28:54 +0200623 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200624 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200625 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200626
627 // authClient is a cached authenticated owner connection to a Curator
628 // instance within the cluster.
629 authClient *grpc.ClientConn
630
631 // ctxT is the context individual node contexts are created from.
632 ctxT context.Context
633 // ctxC is used by Close to cancel the context under which the nodes are
634 // running.
635 ctxC context.CancelFunc
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200636
637 tpmFactory *TPMFactory
Serge Bazanskibe742842022-04-04 13:18:50 +0200638}
639
640// NodeInCluster represents information about a node that's part of a Cluster.
641type NodeInCluster struct {
642 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200643 ID string
644 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200645 // Address of the node on the network ran by nanoswitch. Not reachable from the
646 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
647 // on Cluster.Ports[SOCKSPort]).
648 ManagementAddress string
649}
650
651// firstConnection performs the initial owner credential escrow with a newly
652// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
653// running at 10.1.0.2, which is always the case with the current nanoswitch
654// implementation.
655//
Leopold20a036e2023-01-15 00:17:19 +0100656// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200657// information as NodeInCluster.
658func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
659 // Dial external service.
660 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100661 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200662 if err != nil {
663 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
664 }
665 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
666 return socksDialer.Dial("tcp", addr)
667 }
668 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
669 if err != nil {
670 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
671 }
672 defer initClient.Close()
673
674 // Retrieve owner certificate - this can take a while because the node is still
675 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100676 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200677 aaa := apb.NewAAAClient(initClient)
678 var cert *tls.Certificate
679 err = backoff.Retry(func() error {
680 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
681 if st, ok := status.FromError(err); ok {
682 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100683 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200684 return err
685 }
686 }
687 return backoff.Permanent(err)
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200688 }, backoff.WithContext(backoff.NewExponentialBackOff(backoff.WithMaxElapsedTime(time.Minute)), ctx))
Serge Bazanskibe742842022-04-04 13:18:50 +0200689 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200690 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200691 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100692 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200693
694 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200695 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200696 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
697 if err != nil {
698 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
699 }
700 defer authClient.Close()
701 mgmt := apb.NewManagementClient(authClient)
702
703 var node *NodeInCluster
704 err = backoff.Retry(func() error {
705 nodes, err := getNodes(ctx, mgmt)
706 if err != nil {
707 return fmt.Errorf("retrieving nodes failed: %w", err)
708 }
709 if len(nodes) != 1 {
710 return fmt.Errorf("expected one node, got %d", len(nodes))
711 }
712 n := nodes[0]
713 if n.Status == nil || n.Status.ExternalAddress == "" {
714 return fmt.Errorf("node has no status and/or address")
715 }
716 node = &NodeInCluster{
717 ID: identity.NodeID(n.Pubkey),
718 ManagementAddress: n.Status.ExternalAddress,
719 }
720 return nil
721 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
722 if err != nil {
723 return nil, nil, err
724 }
725
726 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200727}
728
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100729func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200730 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100731 if err != nil {
732 return nil, err
733 }
734 return f, nil
735}
736
Serge Bazanski66e58952021-10-05 17:06:56 +0200737// LaunchCluster launches a cluster of Metropolis node VMs together with a
738// Nanoswitch instance to network them all together.
739//
740// The given context will be used to run all qemu instances in the cluster, and
741// canceling the context or calling Close() will terminate them.
742func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200743 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200744 return nil, errors.New("refusing to start cluster with zero nodes")
745 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200746
Jan Schära9b060b2024-08-07 10:42:29 +0200747 // Prepare the node options. These will be kept as part of Cluster.
748 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
749 // launch. The runtime information can be later used to restart a node.
750 // The 0th node will be initialized first. The rest will follow after it
751 // had bootstrapped the cluster.
752 nodeOpts := make([]NodeOptions, opts.NumNodes)
753 for i := range opts.NumNodes {
754 nodeOpts[i] = opts.Node
755 nodeOpts[i].Name = fmt.Sprintf("node%d", i)
756 nodeOpts[i].SerialPort = newPrefixedStdio(i)
757 }
758 nodeOpts[0].NodeParameters = &apb.NodeParameters{
759 Cluster: &apb.NodeParameters_ClusterBootstrap_{
760 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
761 OwnerPublicKey: InsecurePublicKey,
762 InitialClusterConfiguration: opts.InitialClusterConfiguration,
763 Labels: &cpb.NodeLabels{
764 Pairs: []*cpb.NodeLabels_Pair{
765 {Key: nodeNumberKey, Value: "0"},
766 },
767 },
768 },
769 },
770 }
771 nodeOpts[0].PcapDump = true
772
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200773 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100774 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200775 if err != nil {
776 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
777 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100778 // Create the metroctl config directory. We keep it in /tmp because in some
779 // scenarios it's end-user visible and we want it short.
780 md, err := os.MkdirTemp("/tmp", "metroctl-*")
781 if err != nil {
782 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
783 }
784
785 // Create the socket directory. We keep it in /tmp because of socket path limits.
786 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200787 if err != nil {
788 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
789 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200790
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200791 // Set up TPM factory.
792 tpmf, err := NewTPMFactory(filepath.Join(ld, "tpm"))
793 if err != nil {
794 return nil, fmt.Errorf("failed to create TPM factory: %w", err)
795 }
796
Serge Bazanski66e58952021-10-05 17:06:56 +0200797 // Prepare links between nodes and nanoswitch.
798 var switchPorts []*os.File
Jan Schära9b060b2024-08-07 10:42:29 +0200799 for i := range opts.NumNodes {
Serge Bazanski66e58952021-10-05 17:06:56 +0200800 switchPort, vmPort, err := launch.NewSocketPair()
801 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200802 return nil, fmt.Errorf("failed to get socketpair: %w", err)
803 }
804 switchPorts = append(switchPorts, switchPort)
Jan Schära9b060b2024-08-07 10:42:29 +0200805 nodeOpts[i].ConnectToSocket = vmPort
Serge Bazanski66e58952021-10-05 17:06:56 +0200806 }
807
Serge Bazanskie78a0892021-10-07 17:03:49 +0200808 // Make a list of channels that will be populated by all running node qemu
809 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200810 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200811 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200812 done[i] = make(chan error, 1)
813 }
814
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100815 if opts.NodeLogsToFiles {
Jan Schära9b060b2024-08-07 10:42:29 +0200816 for i := range opts.NumNodes {
817 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i))
818 port, err := NewSerialFileLogger(path)
819 if err != nil {
820 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
821 }
822 launch.Log("Node %d logs at %s", i, path)
823 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100824 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100825 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200826
827 // Start the first node.
828 ctxT, ctxC := context.WithCancel(ctx)
Jan Schär0b927652024-07-31 18:08:50 +0200829 launch.Log("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200830 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200831 ctxC()
832 return nil, fmt.Errorf("failed to launch first node: %w", err)
833 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200834
Lorenz Brun150f24a2023-07-13 20:11:06 +0200835 localRegistryAddr := net.TCPAddr{
836 IP: net.IPv4(10, 42, 0, 82),
837 Port: 5000,
838 }
839
840 var guestSvcMap launch.GuestServiceMap
841 if opts.LocalRegistry != nil {
842 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
843 if err != nil {
844 ctxC()
845 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
846 }
847 s := http.Server{
848 Handler: opts.LocalRegistry,
849 }
850 go s.Serve(l)
851 go func() {
852 <-ctxT.Done()
853 s.Close()
854 }()
855 guestSvcMap = launch.GuestServiceMap{
856 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
857 }
858 }
859
Serge Bazanskie78a0892021-10-07 17:03:49 +0200860 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200861 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
862 if err != nil {
863 ctxC()
864 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
865 }
866
867 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100868 var serialPort io.ReadWriter
869 if opts.NodeLogsToFiles {
870 path := path.Join(ld, "nanoswitch.txt")
871 serialPort, err = NewSerialFileLogger(path)
872 if err != nil {
873 launch.Log("Could not open log file for nanoswitch: %v", err)
874 }
875 launch.Log("Nanoswitch logs at %s", path)
876 } else {
877 serialPort = newPrefixedStdio(99)
878 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200879 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100880 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000881 KernelPath: xKernelPath,
882 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200883 ExtraNetworkInterfaces: switchPorts,
884 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200885 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100886 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100887 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200888 }); err != nil {
889 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100890 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200891 }
892 }
893 }()
894
Serge Bazanskibe742842022-04-04 13:18:50 +0200895 // Build SOCKS dialer.
896 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
897 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200898 if err != nil {
899 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200900 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200901 }
902
Serge Bazanskibe742842022-04-04 13:18:50 +0200903 // Retrieve owner credentials and first node.
904 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200905 if err != nil {
906 ctxC()
907 return nil, err
908 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200909
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100910 // Write credentials to the metroctl directory.
911 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
912 ctxC()
913 return nil, fmt.Errorf("could not write owner key: %w", err)
914 }
915 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
916 ctxC()
917 return nil, fmt.Errorf("could not write owner certificate: %w", err)
918 }
919
Serge Bazanski53458ba2024-06-18 09:56:46 +0000920 launch.Log("Cluster: Node %d is %s", 0, firstNode.ID)
921
922 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200923 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200924 cluster := &Cluster{
925 Owner: *cert,
926 Ports: portMap,
927 Nodes: map[string]*NodeInCluster{
928 firstNode.ID: firstNode,
929 },
930 NodeIDs: []string{
931 firstNode.ID,
932 },
933
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100934 nodesDone: done,
935 nodeOpts: nodeOpts,
936 launchDir: ld,
937 socketDir: sd,
938 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200939
Lorenz Brun276a7462023-07-12 21:28:54 +0200940 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200941
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200942 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200943 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200944
945 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +0200946 }
947
948 // Now start the rest of the nodes and register them into the cluster.
949
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200950 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200951 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200952 if err != nil {
953 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200954 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200955 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200956 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200957
958 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100959 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200960 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
961 if err != nil {
962 ctxC()
963 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
964 }
965 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100966 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200967
968 // Retrieve cluster info (for directory and ca public key) to register further
969 // nodes.
970 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
971 if err != nil {
972 ctxC()
973 return nil, fmt.Errorf("GetClusterInfo: %w", err)
974 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200975 caCert, err := x509.ParseCertificate(resI.CaCertificate)
976 if err != nil {
977 ctxC()
978 return nil, fmt.Errorf("ParseCertificate: %w", err)
979 }
980 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200981
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200982 // Use the retrieved information to configure the rest of the node options.
983 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +0200984 nodeOpts[i].NodeParameters = &apb.NodeParameters{
985 Cluster: &apb.NodeParameters_ClusterRegister_{
986 ClusterRegister: &apb.NodeParameters_ClusterRegister{
987 RegisterTicket: ticket,
988 ClusterDirectory: resI.ClusterDirectory,
989 CaCertificate: resI.CaCertificate,
990 Labels: &cpb.NodeLabels{
991 Pairs: []*cpb.NodeLabels_Pair{
992 {Key: nodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +0200993 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200994 },
995 },
996 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100997 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200998 }
999
1000 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001001 for i := 1; i < opts.NumNodes; i++ {
Jan Schär0b927652024-07-31 18:08:50 +02001002 launch.Log("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001003 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001004 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001005 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001006 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001007 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001008
Serge Bazanski53458ba2024-06-18 09:56:46 +00001009 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001010 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001011 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001012 nodeNumberToID := make(map[int]string)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001013 launch.Log("Cluster: waiting for nodes to appear as NEW...")
1014 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001015 for {
1016 nodes, err := getNodes(ctx, mgmt)
1017 if err != nil {
1018 ctxC()
1019 return nil, fmt.Errorf("could not get nodes: %w", err)
1020 }
1021 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001022 if n.State != cpb.NodeState_NODE_STATE_NEW {
1023 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001024 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001025 if seenNodes[n.Id] {
1026 continue
1027 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001028 seenNodes[n.Id] = true
1029 cluster.Nodes[n.Id] = &NodeInCluster{
1030 ID: n.Id,
1031 Pubkey: n.Pubkey,
1032 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001033
1034 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, nodeNumberKey))
1035 if err != nil {
1036 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1037 }
1038 launch.Log("Cluster: Node %d is %s", num, n.Id)
1039 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001040 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001041
1042 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001043 break
1044 }
1045 time.Sleep(1 * time.Second)
1046 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001047 }
1048 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001049
Serge Bazanski53458ba2024-06-18 09:56:46 +00001050 // Build the rest of NodeIDs from map.
1051 for i := 1; i < opts.NumNodes; i++ {
1052 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1053 }
1054
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001055 approvedNodes := make(map[string]bool)
1056 upNodes := make(map[string]bool)
1057 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001058 for {
1059 nodes, err := getNodes(ctx, mgmt)
1060 if err != nil {
1061 ctxC()
1062 return nil, fmt.Errorf("could not get nodes: %w", err)
1063 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001064 for _, node := range nodes {
1065 if !seenNodes[node.Id] {
1066 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001067 continue
1068 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001069
1070 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1071 launch.Log("Cluster: node %s is up", node.Id)
1072 upNodes[node.Id] = true
1073 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001074 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001075 if upNodes[node.Id] {
1076 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001077 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001078
1079 if !approvedNodes[node.Id] {
1080 launch.Log("Cluster: approving node %s", node.Id)
1081 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1082 Pubkey: node.Pubkey,
1083 })
1084 if err != nil {
1085 ctxC()
1086 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1087 }
1088 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001089 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001090 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001091
Jan Schär0b927652024-07-31 18:08:50 +02001092 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001093 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001094 break
1095 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001096 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001097 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001098 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001099
Serge Bazanski05f813b2023-03-16 17:58:39 +01001100 launch.Log("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001101 for i, nodeID := range cluster.NodeIDs {
1102 launch.Log("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001103 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001104 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001105
Serge Bazanskibe742842022-04-04 13:18:50 +02001106 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001107}
1108
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001109// RebootNode reboots the cluster member node matching the given index, and
1110// waits for it to rejoin the cluster. It will use the given context ctx to run
1111// cluster API requests, whereas the resulting QEMU process will be created
1112// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1113func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1114 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001115 return fmt.Errorf("index out of bounds")
1116 }
1117 if c.nodeOpts[idx].Runtime == nil {
1118 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001119 }
1120 id := c.NodeIDs[idx]
1121
1122 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001123 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001124 if err != nil {
1125 return err
1126 }
1127 mgmt := apb.NewManagementClient(curC)
1128
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001129 // Cancel the node's context. This will shut down QEMU.
1130 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001131 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001132 err = <-c.nodesDone[idx]
1133 if err != nil {
1134 return fmt.Errorf("while restarting node: %w", err)
1135 }
1136
1137 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001138 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001139 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, c.tpmFactory, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001140 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1141 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001142
Serge Bazanskibc969572024-03-21 11:56:13 +01001143 start := time.Now()
1144
1145 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001146 for {
1147 cs, err := getNode(ctx, mgmt, id)
1148 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001149 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001150 return err
1151 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001152 launch.Log("Cluster: node health: %+v", cs.Health)
1153
1154 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1155 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001156 break
1157 }
1158 time.Sleep(time.Second)
1159 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001160 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001161 return nil
1162}
1163
Serge Bazanski500f6e02024-04-03 12:06:40 +02001164// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1165// given by idx. If the node is already shut down, this is a no-op.
1166func (c *Cluster) ShutdownNode(idx int) error {
1167 if idx < 0 || idx >= len(c.NodeIDs) {
1168 return fmt.Errorf("index out of bounds")
1169 }
1170 // Return if node is already stopped.
1171 select {
1172 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1173 return nil
1174 default:
1175 }
1176 id := c.NodeIDs[idx]
1177
1178 // Cancel the node's context. This will shut down QEMU.
1179 c.nodeOpts[idx].Runtime.CtxC()
1180 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1181 err := <-c.nodesDone[idx]
1182 if err != nil {
1183 return fmt.Errorf("while shutting down node: %w", err)
1184 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001185 launch.Log("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001186 return nil
1187}
1188
1189// StartNode performs a power on of the node given by idx. If the node is already
1190// running, this is a no-op.
1191func (c *Cluster) StartNode(idx int) error {
1192 if idx < 0 || idx >= len(c.NodeIDs) {
1193 return fmt.Errorf("index out of bounds")
1194 }
1195 id := c.NodeIDs[idx]
1196 // Return if node is already running.
1197 select {
1198 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1199 default:
1200 return nil
1201 }
1202
1203 // Start QEMU again.
1204 launch.Log("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001205 if err := LaunchNode(c.ctxT, c.launchDir, c.socketDir, c.tpmFactory, &c.nodeOpts[idx], c.nodesDone[idx]); err != nil {
Serge Bazanski500f6e02024-04-03 12:06:40 +02001206 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1207 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001208 launch.Log("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001209 return nil
1210}
1211
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001212// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001213// nodes to stop. It returns an error if stopping the nodes failed, or one of
1214// the nodes failed to fully start in the first place.
1215func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001216 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001217 if c.authClient != nil {
1218 c.authClient.Close()
1219 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001220 c.ctxC()
1221
Leopold20a036e2023-01-15 00:17:19 +01001222 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001223 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001224 for _, c := range c.nodesDone {
1225 err := <-c
1226 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001227 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001228 }
1229 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001230 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001231 os.RemoveAll(c.launchDir)
1232 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001233 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001234 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001235 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001236}
Serge Bazanskibe742842022-04-04 13:18:50 +02001237
1238// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1239// their ID. This is performed by connecting to the cluster nanoswitch via its
1240// SOCKS proxy, and using the cluster node list for name resolution.
1241//
1242// For example:
1243//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001244// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001245func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1246 host, port, err := net.SplitHostPort(addr)
1247 if err != nil {
1248 return nil, fmt.Errorf("invalid host:port: %w", err)
1249 }
1250 // Already an IP address?
1251 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001252 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001253 }
1254
1255 // Otherwise, expect a node name.
1256 node, ok := c.Nodes[host]
1257 if !ok {
1258 return nil, fmt.Errorf("unknown node %q", host)
1259 }
1260 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001261 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001262}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001263
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001264// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1265// Kubernetes authenticating proxy using the cluster owner identity.
1266// It currently has access to everything (i.e. the cluster-admin role)
1267// via the owner-admin binding.
1268func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1269 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1270 if err != nil {
1271 // We explicitly pass an Ed25519 private key in, so this can't happen
1272 panic(err)
1273 }
1274
1275 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001276 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001277 Host: host,
1278 TLSClientConfig: rest.TLSClientConfig{
1279 // TODO(q3k): use CA certificate
1280 Insecure: true,
1281 ServerName: "kubernetes.default.svc",
1282 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1283 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1284 },
1285 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1286 return c.DialNode(ctx, address)
1287 },
1288 }
1289 return kubernetes.NewForConfig(&clientConfig)
1290}
1291
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001292// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1293// which are currently Kubernetes controllers, ie. run an apiserver. This list
1294// might be empty if no node is currently configured with the
1295// 'KubernetesController' node.
1296func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1297 curC, err := c.CuratorClient()
1298 if err != nil {
1299 return nil, err
1300 }
1301 mgmt := apb.NewManagementClient(curC)
1302 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1303 Filter: "has(node.roles.kubernetes_controller)",
1304 })
1305 if err != nil {
1306 return nil, err
1307 }
1308 defer srv.CloseSend()
1309 var res []string
1310 for {
1311 n, err := srv.Recv()
1312 if err == io.EOF {
1313 break
1314 }
1315 if err != nil {
1316 return nil, err
1317 }
1318 if n.Status == nil || n.Status.ExternalAddress == "" {
1319 continue
1320 }
1321 res = append(res, n.Status.ExternalAddress)
1322 }
1323 return res, nil
1324}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001325
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001326// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1327// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001328func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1329 // Get an authenticated owner client within the cluster.
1330 curC, err := c.CuratorClient()
1331 if err != nil {
1332 return err
1333 }
1334 mgmt := apb.NewManagementClient(curC)
1335 nodes, err := getNodes(ctx, mgmt)
1336 if err != nil {
1337 return err
1338 }
1339
1340 var unhealthy []string
1341 for _, node := range nodes {
1342 if node.Health == apb.Node_HEALTHY {
1343 continue
1344 }
1345 unhealthy = append(unhealthy, node.Id)
1346 }
1347 if len(unhealthy) == 0 {
1348 return nil
1349 }
1350 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1351}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001352
1353// ApproveNode approves a node by ID, waiting for it to become UP.
1354func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1355 curC, err := c.CuratorClient()
1356 if err != nil {
1357 return err
1358 }
1359 mgmt := apb.NewManagementClient(curC)
1360
1361 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1362 Pubkey: c.Nodes[id].Pubkey,
1363 })
1364 if err != nil {
1365 return fmt.Errorf("ApproveNode: %w", err)
1366 }
1367 launch.Log("Cluster: %s: approved, waiting for UP", id)
1368 for {
1369 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1370 if err != nil {
1371 return fmt.Errorf("GetNodes: %w", err)
1372 }
1373 found := false
1374 for {
1375 node, err := nodes.Recv()
1376 if errors.Is(err, io.EOF) {
1377 break
1378 }
1379 if err != nil {
1380 return fmt.Errorf("Nodes.Recv: %w", err)
1381 }
1382 if node.Id != id {
1383 continue
1384 }
1385 if node.State != cpb.NodeState_NODE_STATE_UP {
1386 continue
1387 }
1388 found = true
1389 break
1390 }
1391 nodes.CloseSend()
1392
1393 if found {
1394 break
1395 }
1396 time.Sleep(time.Second)
1397 }
1398 launch.Log("Cluster: %s: UP", id)
1399 return nil
1400}
1401
1402// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1403func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1404 curC, err := c.CuratorClient()
1405 if err != nil {
1406 return err
1407 }
1408 mgmt := apb.NewManagementClient(curC)
1409
1410 tr := true
1411 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1412 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1413 Node: &apb.UpdateNodeRolesRequest_Id{
1414 Id: id,
1415 },
1416 KubernetesWorker: &tr,
1417 })
1418 return err
1419}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001420
Jan Schära9b060b2024-08-07 10:42:29 +02001421// MakeKubernetesController adds the KubernetesController role to a node by ID.
1422func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1423 curC, err := c.CuratorClient()
1424 if err != nil {
1425 return err
1426 }
1427 mgmt := apb.NewManagementClient(curC)
1428
1429 tr := true
1430 launch.Log("Cluster: %s: adding KubernetesController", id)
1431 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1432 Node: &apb.UpdateNodeRolesRequest_Id{
1433 Id: id,
1434 },
1435 KubernetesController: &tr,
1436 })
1437 return err
1438}
1439
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001440// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1441func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1442 curC, err := c.CuratorClient()
1443 if err != nil {
1444 return err
1445 }
1446 mgmt := apb.NewManagementClient(curC)
1447 cur := ipb.NewCuratorClient(curC)
1448
1449 tr := true
1450 launch.Log("Cluster: %s: adding ConsensusMember", id)
1451 bo := backoff.NewExponentialBackOff()
1452 bo.MaxElapsedTime = 10 * time.Second
1453
1454 backoff.Retry(func() error {
1455 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1456 Node: &apb.UpdateNodeRolesRequest_Id{
1457 Id: id,
1458 },
1459 ConsensusMember: &tr,
1460 })
1461 if err != nil {
1462 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1463 }
1464 return err
1465 }, backoff.WithContext(bo, ctx))
1466 if err != nil {
1467 return err
1468 }
1469
1470 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1471
1472 learner := false
1473 for {
1474 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1475 if err != nil {
1476 return fmt.Errorf("GetConsensusStatus: %w", err)
1477 }
1478 for _, member := range res.EtcdMember {
1479 if member.Id != id {
1480 continue
1481 }
1482 switch member.Status {
1483 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1484 if !learner {
1485 learner = true
1486 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1487 }
1488 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1489 launch.Log("Cluster: %s: became a full member", id)
1490 return nil
1491 }
1492 }
1493 time.Sleep(100 * time.Millisecond)
1494 }
1495}