blob: e0a0473e0ce5a5b10052623582a1ee528828c75e [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
Jan Schär07003572024-08-26 10:42:16 +020075 // DiskBytes contains the size of the root disk in bytes or zero if the
76 // unmodified image size is used.
77 DiskBytes uint64
78
Serge Bazanski66e58952021-10-05 17:06:56 +020079 // Ports contains the port mapping where to expose the internal ports of the VM to
80 // the host. See IdentityPortMap() and ConflictFreePortMap(). Ignored when
81 // ConnectToSocket is set.
82 Ports launch.PortMap
83
Leopold20a036e2023-01-15 00:17:19 +010084 // If set to true, reboots are honored. Otherwise, all reboots exit the Launch()
85 // command. Metropolis nodes generally restart on almost all errors, so unless you
Serge Bazanski66e58952021-10-05 17:06:56 +020086 // want to test reboot behavior this should be false.
87 AllowReboot bool
88
Leopold20a036e2023-01-15 00:17:19 +010089 // By default, the VM is connected to the Host via SLIRP. If ConnectToSocket is
90 // set, it is instead connected to the given file descriptor/socket. If this is
91 // set, all port maps from the Ports option are ignored. Intended for networking
92 // this instance together with others for running more complex network
93 // configurations.
Serge Bazanski66e58952021-10-05 17:06:56 +020094 ConnectToSocket *os.File
95
Leopoldacfad5b2023-01-15 14:05:25 +010096 // When PcapDump is set, all traffic is dumped to a pcap file in the
97 // runtime directory (e.g. "net0.pcap" for the first interface).
98 PcapDump bool
99
Leopold20a036e2023-01-15 00:17:19 +0100100 // SerialPort is an io.ReadWriter over which you can communicate with the serial
101 // port of the machine. It can be set to an existing file descriptor (like
Serge Bazanski66e58952021-10-05 17:06:56 +0200102 // os.Stdout/os.Stderr) or any Go structure implementing this interface.
103 SerialPort io.ReadWriter
104
105 // NodeParameters is passed into the VM and subsequently used for bootstrapping or
106 // registering into a cluster.
107 NodeParameters *apb.NodeParameters
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200108
109 // Mac is the node's MAC address.
110 Mac *net.HardwareAddr
111
112 // Runtime keeps the node's QEMU runtime state.
113 Runtime *NodeRuntime
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200114
115 // RunVNC starts a VNC socket for troubleshooting/testing console code. Note:
116 // this will not work in tests, as those use a built-in qemu which does not
117 // implement a VGA device.
118 RunVNC bool
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200119}
120
Leopold20a036e2023-01-15 00:17:19 +0100121// NodeRuntime keeps the node's QEMU runtime options.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200122type NodeRuntime struct {
123 // ld points at the node's launch directory storing data such as storage
124 // images, firmware variables or the TPM state.
125 ld string
126 // sd points at the node's socket directory.
127 sd string
128
129 // ctxT is the context QEMU will execute in.
130 ctxT context.Context
131 // CtxC is the QEMU context's cancellation function.
132 CtxC context.CancelFunc
Serge Bazanski66e58952021-10-05 17:06:56 +0200133}
134
135// NodePorts is the list of ports a fully operational Metropolis node listens on
Serge Bazanski52304a82021-10-29 16:56:18 +0200136var NodePorts = []node.Port{
Serge Bazanski66e58952021-10-05 17:06:56 +0200137 node.ConsensusPort,
138
139 node.CuratorServicePort,
140 node.DebugServicePort,
141
142 node.KubernetesAPIPort,
Lorenz Bruncc078df2021-12-23 11:51:55 +0100143 node.KubernetesAPIWrappedPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200144 node.CuratorServicePort,
145 node.DebuggerPort,
Tim Windelschmidtbe25a3b2023-07-19 16:31:56 +0200146 node.MetricsPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200147}
148
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200149// setupRuntime creates the node's QEMU runtime directory, together with all
150// files required to preserve its state, a level below the chosen path ld. The
151// node's socket directory is similarily created a level below sd. It may
152// return an I/O error.
Jan Schär07003572024-08-26 10:42:16 +0200153func setupRuntime(ld, sd string, diskBytes uint64) (*NodeRuntime, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200154 // Create a temporary directory to keep all the runtime files.
155 stdp, err := os.MkdirTemp(ld, "node_state*")
156 if err != nil {
157 return nil, fmt.Errorf("failed to create the state directory: %w", err)
158 }
159
160 // Initialize the node's storage with a prebuilt image.
Jan Schär07003572024-08-26 10:42:16 +0200161 st, err := os.Stat(xNodeImagePath)
162 if err != nil {
163 return nil, fmt.Errorf("cannot read image file: %w", err)
164 }
165 diskBytes = max(diskBytes, uint64(st.Size()))
166
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200167 di := filepath.Join(stdp, "image.qcow2")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000168 launch.Log("Cluster: generating node QCOW2 snapshot image: %s -> %s", xNodeImagePath, di)
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200169
170 df, err := os.Create(di)
171 if err != nil {
172 return nil, fmt.Errorf("while opening image for writing: %w", err)
173 }
174 defer df.Close()
Jan Schär07003572024-08-26 10:42:16 +0200175 if err := qcow2.Generate(df, qcow2.GenerateWithBackingFile(xNodeImagePath), qcow2.GenerateWithFileSize(diskBytes)); err != nil {
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200176 return nil, fmt.Errorf("while creating copy-on-write node image: %w", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200177 }
178
179 // Initialize the OVMF firmware variables file.
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000180 dv := filepath.Join(stdp, filepath.Base(xOvmfVarsPath))
181 if err := copyFile(xOvmfVarsPath, dv); err != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200182 return nil, fmt.Errorf("while copying firmware variables: %w", err)
183 }
184
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200185 // Create the socket directory.
186 sotdp, err := os.MkdirTemp(sd, "node_sock*")
187 if err != nil {
188 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
189 }
190
191 return &NodeRuntime{
192 ld: stdp,
193 sd: sotdp,
194 }, nil
195}
196
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200197// CuratorClient returns an authenticated owner connection to a Curator
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200198// instance within Cluster c, or nil together with an error.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200199func (c *Cluster) CuratorClient() (*grpc.ClientConn, error) {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200200 if c.authClient == nil {
Serge Bazanski8535cb52023-03-29 14:15:08 +0200201 authCreds := rpc.NewAuthenticatedCredentials(c.Owner, rpc.WantInsecure())
Serge Bazanski58ddc092022-06-30 18:23:33 +0200202 r := resolver.New(c.ctxT, resolver.WithLogger(func(f string, args ...interface{}) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100203 launch.Log("Cluster: client resolver: %s", fmt.Sprintf(f, args...))
Serge Bazanski58ddc092022-06-30 18:23:33 +0200204 }))
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200205 for _, n := range c.NodeIDs {
206 ep, err := resolver.NodeWithDefaultPort(n)
207 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200208 return nil, fmt.Errorf("could not add node %q by DNS: %w", n, err)
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200209 }
210 r.AddEndpoint(ep)
211 }
212 authClient, err := grpc.Dial(resolver.MetropolisControlAddress,
213 grpc.WithTransportCredentials(authCreds),
214 grpc.WithResolvers(r),
215 grpc.WithContextDialer(c.DialNode),
216 )
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200217 if err != nil {
218 return nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
219 }
220 c.authClient = authClient
221 }
222 return c.authClient, nil
223}
224
Serge Bazanski66e58952021-10-05 17:06:56 +0200225// LaunchNode launches a single Metropolis node instance with the given options.
226// The instance runs mostly paravirtualized but with some emulated hardware
227// similar to how a cloud provider might set up its VMs. The disk is fully
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200228// writable, and the changes are kept across reboots and shutdowns. ld and sd
229// point to the launch directory and the socket directory, holding the nodes'
230// state files (storage, tpm state, firmware state), and UNIX socket files
231// (swtpm <-> QEMU interplay) respectively. The directories must exist before
232// LaunchNode is called. LaunchNode will update options.Runtime and options.Mac
233// if either are not initialized.
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200234func LaunchNode(ctx context.Context, ld, sd string, tpmFactory *TPMFactory, options *NodeOptions, doneC chan error) error {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200235 // TODO(mateusz@monogon.tech) try using QEMU's abstract socket namespace instead
236 // of /tmp (requires QEMU version >5.0).
Serge Bazanski66e58952021-10-05 17:06:56 +0200237 // https://github.com/qemu/qemu/commit/776b97d3605ed0fc94443048fdf988c7725e38a9).
238 // swtpm accepts already-open FDs so we can pass in an abstract socket namespace FD
239 // that we open and pass the name of it to QEMU. Not pinning this crashes both
240 // swtpm and qemu because we run into UNIX socket length limitations (for legacy
241 // reasons 108 chars).
Serge Bazanski66e58952021-10-05 17:06:56 +0200242
Jan Schära9b060b2024-08-07 10:42:29 +0200243 if options.CPUs == 0 {
244 options.CPUs = 1
245 }
246 if options.ThreadsPerCPU == 0 {
247 options.ThreadsPerCPU = 1
248 }
249 if options.MemoryMiB == 0 {
250 options.MemoryMiB = 2048
251 }
252
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200253 // If it's the node's first start, set up its runtime directories.
254 if options.Runtime == nil {
Jan Schär07003572024-08-26 10:42:16 +0200255 r, err := setupRuntime(ld, sd, options.DiskBytes)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200256 if err != nil {
257 return fmt.Errorf("while setting up node runtime: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200258 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200259 options.Runtime = r
Serge Bazanski66e58952021-10-05 17:06:56 +0200260 }
261
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200262 // Replace the node's context with a new one.
263 r := options.Runtime
264 if r.CtxC != nil {
265 r.CtxC()
266 }
267 r.ctxT, r.CtxC = context.WithCancel(ctx)
268
Serge Bazanski66e58952021-10-05 17:06:56 +0200269 var qemuNetType string
270 var qemuNetConfig launch.QemuValue
271 if options.ConnectToSocket != nil {
272 qemuNetType = "socket"
273 qemuNetConfig = launch.QemuValue{
274 "id": {"net0"},
275 "fd": {"3"},
276 }
277 } else {
278 qemuNetType = "user"
279 qemuNetConfig = launch.QemuValue{
280 "id": {"net0"},
281 "net": {"10.42.0.0/24"},
282 "dhcpstart": {"10.42.0.10"},
283 "hostfwd": options.Ports.ToQemuForwards(),
284 }
285 }
286
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200287 // Generate the node's MAC address if it isn't already set in NodeOptions.
288 if options.Mac == nil {
289 mac, err := generateRandomEthernetMAC()
290 if err != nil {
291 return err
292 }
293 options.Mac = mac
Serge Bazanski66e58952021-10-05 17:06:56 +0200294 }
295
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200296 tpmSocketPath := filepath.Join(r.sd, "tpm-socket")
297 fwVarPath := filepath.Join(r.ld, "OVMF_VARS.fd")
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200298 storagePath := filepath.Join(r.ld, "image.qcow2")
Lorenz Brun150f24a2023-07-13 20:11:06 +0200299 qemuArgs := []string{
Jan Schära9b060b2024-08-07 10:42:29 +0200300 "-machine", "q35",
301 "-accel", "kvm",
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200302 "-display", "none",
Jan Schära9b060b2024-08-07 10:42:29 +0200303 "-nodefaults",
304 "-cpu", "host",
305 "-m", fmt.Sprintf("%dM", options.MemoryMiB),
306 "-smp", fmt.Sprintf("cores=%d,threads=%d", options.CPUs, options.ThreadsPerCPU),
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000307 "-drive", "if=pflash,format=raw,readonly=on,file=" + xOvmfCodePath,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200308 "-drive", "if=pflash,format=raw,file=" + fwVarPath,
Serge Bazanskidd5b03c2024-05-16 18:07:06 +0200309 "-drive", "if=virtio,format=qcow2,cache=unsafe,file=" + storagePath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200310 "-netdev", qemuNetConfig.ToOption(qemuNetType),
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200311 "-device", "virtio-net-pci,netdev=net0,mac=" + options.Mac.String(),
Serge Bazanski66e58952021-10-05 17:06:56 +0200312 "-chardev", "socket,id=chrtpm,path=" + tpmSocketPath,
313 "-tpmdev", "emulator,id=tpm0,chardev=chrtpm",
314 "-device", "tpm-tis,tpmdev=tpm0",
315 "-device", "virtio-rng-pci",
Lorenz Brun150f24a2023-07-13 20:11:06 +0200316 "-serial", "stdio",
317 }
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200318 if options.RunVNC {
319 vncSocketPath := filepath.Join(r.sd, "vnc-socket")
320 qemuArgs = append(qemuArgs,
321 "-vnc", "unix:"+vncSocketPath,
322 "-device", "virtio-vga",
323 )
324 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200325
326 if !options.AllowReboot {
327 qemuArgs = append(qemuArgs, "-no-reboot")
328 }
329
330 if options.NodeParameters != nil {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200331 parametersPath := filepath.Join(r.ld, "parameters.pb")
Serge Bazanski66e58952021-10-05 17:06:56 +0200332 parametersRaw, err := proto.Marshal(options.NodeParameters)
333 if err != nil {
334 return fmt.Errorf("failed to encode node paraeters: %w", err)
335 }
Lorenz Brun150f24a2023-07-13 20:11:06 +0200336 if err := os.WriteFile(parametersPath, parametersRaw, 0o644); err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200337 return fmt.Errorf("failed to write node parameters: %w", err)
338 }
339 qemuArgs = append(qemuArgs, "-fw_cfg", "name=dev.monogon.metropolis/parameters.pb,file="+parametersPath)
340 }
341
Leopoldacfad5b2023-01-15 14:05:25 +0100342 if options.PcapDump {
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200343 qemuNetDump := launch.QemuValue{
344 "id": {"net0"},
345 "netdev": {"net0"},
346 "file": {filepath.Join(r.ld, "net0.pcap")},
Leopoldacfad5b2023-01-15 14:05:25 +0100347 }
348 qemuArgs = append(qemuArgs, "-object", qemuNetDump.ToOption("filter-dump"))
349 }
350
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200351 // Manufacture TPM if needed.
352 tpmd := filepath.Join(r.ld, "tpm")
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000353 err := tpmFactory.Manufacture(ctx, tpmd, &TPMPlatform{
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200354 Manufacturer: "Monogon",
355 Version: "1.0",
356 Model: "TestCluster",
357 })
358 if err != nil {
359 return fmt.Errorf("could not manufacture TPM: %w", err)
360 }
361
Serge Bazanski66e58952021-10-05 17:06:56 +0200362 // Start TPM emulator as a subprocess
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200363 tpmCtx, tpmCancel := context.WithCancel(options.Runtime.ctxT)
Serge Bazanski66e58952021-10-05 17:06:56 +0200364
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000365 tpmEmuCmd := exec.CommandContext(tpmCtx, xSwtpmPath, "socket", "--tpm2", "--tpmstate", "dir="+tpmd, "--ctrl", "type=unixio,path="+tpmSocketPath)
Serge Bazanskib07c57a2024-06-04 14:33:27 +0000366 // Silence warnings from unsafe libtpms build (uses non-constant-time
367 // cryptographic operations).
368 tpmEmuCmd.Env = append(tpmEmuCmd.Env, "MONOGON_LIBTPMS_ACKNOWLEDGE_UNSAFE=yes")
Serge Bazanski66e58952021-10-05 17:06:56 +0200369 tpmEmuCmd.Stderr = os.Stderr
370 tpmEmuCmd.Stdout = os.Stdout
371
Tim Windelschmidt244b5672024-02-06 10:18:56 +0100372 err = tpmEmuCmd.Start()
Serge Bazanski66e58952021-10-05 17:06:56 +0200373 if err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200374 tpmCancel()
Serge Bazanski66e58952021-10-05 17:06:56 +0200375 return fmt.Errorf("failed to start TPM emulator: %w", err)
376 }
377
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200378 // Wait for the socket to be created by the TPM emulator before launching
379 // QEMU.
380 for {
381 _, err := os.Stat(tpmSocketPath)
382 if err == nil {
383 break
384 }
Tim Windelschmidta7a82f32024-04-11 01:40:25 +0200385 if !os.IsNotExist(err) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200386 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200387 return fmt.Errorf("while stat-ing TPM socket path: %w", err)
388 }
389 if err := tpmCtx.Err(); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200390 tpmCancel()
Mateusz Zalegae90f4a12022-05-25 18:24:01 +0200391 return fmt.Errorf("while waiting for the TPM socket: %w", err)
392 }
393 time.Sleep(time.Millisecond * 100)
394 }
395
Serge Bazanski66e58952021-10-05 17:06:56 +0200396 // Start the main qemu binary
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200397 systemCmd := exec.CommandContext(options.Runtime.ctxT, "qemu-system-x86_64", qemuArgs...)
Serge Bazanski66e58952021-10-05 17:06:56 +0200398 if options.ConnectToSocket != nil {
399 systemCmd.ExtraFiles = []*os.File{options.ConnectToSocket}
400 }
401
402 var stdErrBuf bytes.Buffer
403 systemCmd.Stderr = &stdErrBuf
404 systemCmd.Stdout = options.SerialPort
405
Leopoldaf5086b2023-01-15 14:12:42 +0100406 launch.PrettyPrintQemuArgs(options.Name, systemCmd.Args)
407
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200408 go func() {
409 launch.Log("Node: Starting...")
410 err = systemCmd.Run()
411 launch.Log("Node: Returned: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200412
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200413 // Stop TPM emulator and wait for it to exit to properly reap the child process
414 tpmCancel()
415 launch.Log("Node: Waiting for TPM emulator to exit")
416 // Wait returns a SIGKILL error because we just cancelled its context.
417 // We still need to call it to avoid creating zombies.
418 errTpm := tpmEmuCmd.Wait()
419 launch.Log("Node: TPM emulator done: %v", errTpm)
Serge Bazanski66e58952021-10-05 17:06:56 +0200420
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200421 var exerr *exec.ExitError
422 if err != nil && errors.As(err, &exerr) {
423 status := exerr.ProcessState.Sys().(syscall.WaitStatus)
424 if status.Signaled() && status.Signal() == syscall.SIGKILL {
425 // Process was killed externally (most likely by our context being canceled).
426 // This is a normal exit for us, so return nil
427 doneC <- nil
428 return
429 }
430 exerr.Stderr = stdErrBuf.Bytes()
431 newErr := launch.QEMUError(*exerr)
432 launch.Log("Node: %q", stdErrBuf.String())
433 doneC <- &newErr
434 return
Serge Bazanski66e58952021-10-05 17:06:56 +0200435 }
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200436 doneC <- err
437 }()
438 return nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200439}
440
441func copyFile(src, dst string) error {
442 in, err := os.Open(src)
443 if err != nil {
444 return fmt.Errorf("when opening source: %w", err)
445 }
446 defer in.Close()
447
448 out, err := os.Create(dst)
449 if err != nil {
450 return fmt.Errorf("when creating destination: %w", err)
451 }
452 defer out.Close()
453
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100454 endPos, err := in.Seek(0, io.SeekEnd)
Serge Bazanski66e58952021-10-05 17:06:56 +0200455 if err != nil {
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100456 return fmt.Errorf("when getting source end: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200457 }
Lorenz Brun87bbf7e2024-03-18 18:22:25 +0100458
459 // Copy the file while preserving its sparseness. The image files are very
460 // sparse (less than 10% allocated), so this is a lot faster.
461 var lastHoleStart int64
462 for {
463 dataStart, err := in.Seek(lastHoleStart, unix.SEEK_DATA)
464 if err != nil {
465 return fmt.Errorf("when seeking to next data block: %w", err)
466 }
467 holeStart, err := in.Seek(dataStart, unix.SEEK_HOLE)
468 if err != nil {
469 return fmt.Errorf("when seeking to next hole: %w", err)
470 }
471 lastHoleStart = holeStart
472 if _, err := in.Seek(dataStart, io.SeekStart); err != nil {
473 return fmt.Errorf("when seeking to current data block: %w", err)
474 }
475 if _, err := out.Seek(dataStart, io.SeekStart); err != nil {
476 return fmt.Errorf("when seeking output to next data block: %w", err)
477 }
478 if _, err := io.CopyN(out, in, holeStart-dataStart); err != nil {
479 return fmt.Errorf("when copying file: %w", err)
480 }
481 if endPos == holeStart {
482 // The next hole is at the end of the file, we're done here.
483 break
484 }
485 }
486
Serge Bazanski66e58952021-10-05 17:06:56 +0200487 return out.Close()
488}
489
Serge Bazanskie78a0892021-10-07 17:03:49 +0200490// getNodes wraps around Management.GetNodes to return a list of nodes in a
491// cluster.
492func getNodes(ctx context.Context, mgmt apb.ManagementClient) ([]*apb.Node, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200493 var res []*apb.Node
Serge Bazanski636032e2022-01-26 14:21:33 +0100494 bo := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
Serge Bazanski075465c2021-11-16 15:38:49 +0100495 err := backoff.Retry(func() error {
496 res = nil
497 srvN, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
Serge Bazanskie78a0892021-10-07 17:03:49 +0200498 if err != nil {
Serge Bazanski075465c2021-11-16 15:38:49 +0100499 return fmt.Errorf("GetNodes: %w", err)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200500 }
Serge Bazanski075465c2021-11-16 15:38:49 +0100501 for {
502 node, err := srvN.Recv()
503 if err == io.EOF {
504 break
505 }
506 if err != nil {
507 return fmt.Errorf("GetNodes.Recv: %w", err)
508 }
509 res = append(res, node)
510 }
511 return nil
512 }, bo)
513 if err != nil {
514 return nil, err
Serge Bazanskie78a0892021-10-07 17:03:49 +0200515 }
516 return res, nil
517}
518
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200519// getNode wraps Management.GetNodes. It returns node information matching
520// given node ID.
521func getNode(ctx context.Context, mgmt apb.ManagementClient, id string) (*apb.Node, error) {
522 nodes, err := getNodes(ctx, mgmt)
523 if err != nil {
524 return nil, fmt.Errorf("could not get nodes: %w", err)
525 }
526 for _, n := range nodes {
527 eid := identity.NodeID(n.Pubkey)
528 if eid != id {
529 continue
530 }
531 return n, nil
532 }
Tim Windelschmidt73e98822024-04-18 23:13:49 +0200533 return nil, fmt.Errorf("no such node")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200534}
535
Serge Bazanski66e58952021-10-05 17:06:56 +0200536// Gets a random EUI-48 Ethernet MAC address
537func generateRandomEthernetMAC() (*net.HardwareAddr, error) {
538 macBuf := make([]byte, 6)
539 _, err := rand.Read(macBuf)
540 if err != nil {
Tim Windelschmidtadcf5d72024-05-21 13:46:25 +0200541 return nil, fmt.Errorf("failed to read randomness for MAC: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200542 }
543
544 // Set U/L bit and clear I/G bit (locally administered individual MAC)
545 // Ref IEEE 802-2014 Section 8.2.2
546 macBuf[0] = (macBuf[0] | 2) & 0xfe
547 mac := net.HardwareAddr(macBuf)
548 return &mac, nil
549}
550
Serge Bazanskibe742842022-04-04 13:18:50 +0200551const SOCKSPort uint16 = 1080
Serge Bazanski66e58952021-10-05 17:06:56 +0200552
Serge Bazanskibe742842022-04-04 13:18:50 +0200553// ClusterPorts contains all ports handled by Nanoswitch.
554var ClusterPorts = []uint16{
555 // Forwarded to the first node.
556 uint16(node.CuratorServicePort),
557 uint16(node.DebugServicePort),
558 uint16(node.KubernetesAPIPort),
559 uint16(node.KubernetesAPIWrappedPort),
560
561 // SOCKS proxy to the switch network
562 SOCKSPort,
Serge Bazanski66e58952021-10-05 17:06:56 +0200563}
564
565// ClusterOptions contains all options for launching a Metropolis cluster.
566type ClusterOptions struct {
567 // The number of nodes this cluster should be started with.
568 NumNodes int
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100569
Jan Schära9b060b2024-08-07 10:42:29 +0200570 // Node are default options of all nodes.
571 Node NodeOptions
572
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100573 // If true, node logs will be saved to individual files instead of being printed
574 // out to stderr. The path of these files will be still printed to stdout.
575 //
576 // The files will be located within the launch directory inside TEST_TMPDIR (or
577 // the default tempdir location, if not set).
578 NodeLogsToFiles bool
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200579
580 // LeaveNodesNew, if set, will leave all non-bootstrap nodes in NEW, without
581 // bootstrapping them. The nodes' address information in Cluster.Nodes will be
582 // incomplete.
583 LeaveNodesNew bool
Lorenz Brun150f24a2023-07-13 20:11:06 +0200584
585 // Optional local registry which will be made available to the cluster to
586 // pull images from. This is a more efficient alternative to preseeding all
587 // images used for testing.
588 LocalRegistry *localregistry.Server
Serge Bazanskie564f172024-04-03 12:06:06 +0200589
590 // InitialClusterConfiguration will be passed to the first node when creating the
591 // cluster, and defines some basic properties of the cluster. If not specified,
592 // the cluster will default to defaults as defined in
593 // metropolis.proto.api.NodeParameters.
594 InitialClusterConfiguration *cpb.ClusterConfiguration
Serge Bazanski66e58952021-10-05 17:06:56 +0200595}
596
597// Cluster is the running Metropolis cluster launched using the LaunchCluster
598// function.
599type Cluster struct {
Serge Bazanski66e58952021-10-05 17:06:56 +0200600 // Owner is the TLS Certificate of the owner of the test cluster. This can be
601 // used to authenticate further clients to the running cluster.
602 Owner tls.Certificate
603 // Ports is the PortMap used to access the first nodes' services (defined in
Serge Bazanskibe742842022-04-04 13:18:50 +0200604 // ClusterPorts) and the SOCKS proxy (at SOCKSPort).
Serge Bazanski66e58952021-10-05 17:06:56 +0200605 Ports launch.PortMap
606
Serge Bazanskibe742842022-04-04 13:18:50 +0200607 // Nodes is a map from Node ID to its runtime information.
608 Nodes map[string]*NodeInCluster
609 // NodeIDs is a list of node IDs that are backing this cluster, in order of
610 // creation.
611 NodeIDs []string
612
Serge Bazanski54e212a2023-06-14 13:45:11 +0200613 // CACertificate is the cluster's CA certificate.
614 CACertificate *x509.Certificate
615
Serge Bazanski66e58952021-10-05 17:06:56 +0200616 // nodesDone is a list of channels populated with the return codes from all the
617 // nodes' qemu instances. It's used by Close to ensure all nodes have
Leopold20a036e2023-01-15 00:17:19 +0100618 // successfully been stopped.
Serge Bazanski66e58952021-10-05 17:06:56 +0200619 nodesDone []chan error
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200620 // nodeOpts are the cluster member nodes' mutable launch options, kept here
621 // to facilitate reboots.
622 nodeOpts []NodeOptions
623 // launchDir points at the directory keeping the nodes' state, such as storage
624 // images, firmware variable files, TPM state.
625 launchDir string
626 // socketDir points at the directory keeping UNIX socket files, such as these
627 // used to facilitate communication between QEMU and swtpm. It's different
628 // from launchDir, and anchored nearer the file system root, due to the
629 // socket path length limitation imposed by the kernel.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100630 socketDir string
631 metroctlDir string
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200632
Lorenz Brun276a7462023-07-12 21:28:54 +0200633 // SOCKSDialer is used by DialNode to establish connections to nodes via the
Serge Bazanskibe742842022-04-04 13:18:50 +0200634 // SOCKS server ran by nanoswitch.
Lorenz Brun276a7462023-07-12 21:28:54 +0200635 SOCKSDialer proxy.Dialer
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200636
637 // authClient is a cached authenticated owner connection to a Curator
638 // instance within the cluster.
639 authClient *grpc.ClientConn
640
641 // ctxT is the context individual node contexts are created from.
642 ctxT context.Context
643 // ctxC is used by Close to cancel the context under which the nodes are
644 // running.
645 ctxC context.CancelFunc
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200646
647 tpmFactory *TPMFactory
Serge Bazanskibe742842022-04-04 13:18:50 +0200648}
649
650// NodeInCluster represents information about a node that's part of a Cluster.
651type NodeInCluster struct {
652 // ID of the node, which can be used to dial this node's services via DialNode.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +0200653 ID string
654 Pubkey []byte
Serge Bazanskibe742842022-04-04 13:18:50 +0200655 // Address of the node on the network ran by nanoswitch. Not reachable from the
656 // host unless dialed via DialNode or via the nanoswitch SOCKS proxy (reachable
657 // on Cluster.Ports[SOCKSPort]).
658 ManagementAddress string
659}
660
661// firstConnection performs the initial owner credential escrow with a newly
662// started nanoswitch-backed cluster over SOCKS. It expects the first node to be
663// running at 10.1.0.2, which is always the case with the current nanoswitch
664// implementation.
665//
Leopold20a036e2023-01-15 00:17:19 +0100666// It returns the newly escrowed credentials as well as the first node's
Serge Bazanskibe742842022-04-04 13:18:50 +0200667// information as NodeInCluster.
668func firstConnection(ctx context.Context, socksDialer proxy.Dialer) (*tls.Certificate, *NodeInCluster, error) {
669 // Dial external service.
670 remote := fmt.Sprintf("10.1.0.2:%s", node.CuratorServicePort.PortString())
Serge Bazanski0c280152024-02-05 14:33:19 +0100671 initCreds, err := rpc.NewEphemeralCredentials(InsecurePrivateKey, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200672 if err != nil {
673 return nil, nil, fmt.Errorf("NewEphemeralCredentials: %w", err)
674 }
675 initDialer := func(_ context.Context, addr string) (net.Conn, error) {
676 return socksDialer.Dial("tcp", addr)
677 }
678 initClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(initCreds))
679 if err != nil {
680 return nil, nil, fmt.Errorf("dialing with ephemeral credentials failed: %w", err)
681 }
682 defer initClient.Close()
683
684 // Retrieve owner certificate - this can take a while because the node is still
685 // coming up, so do it in a backoff loop.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100686 launch.Log("Cluster: retrieving owner certificate (this can take a few seconds while the first node boots)...")
Serge Bazanskibe742842022-04-04 13:18:50 +0200687 aaa := apb.NewAAAClient(initClient)
688 var cert *tls.Certificate
689 err = backoff.Retry(func() error {
690 cert, err = rpc.RetrieveOwnerCertificate(ctx, aaa, InsecurePrivateKey)
691 if st, ok := status.FromError(err); ok {
692 if st.Code() == codes.Unavailable {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100693 launch.Log("Cluster: cluster UNAVAILABLE: %v", st.Message())
Serge Bazanskibe742842022-04-04 13:18:50 +0200694 return err
695 }
696 }
697 return backoff.Permanent(err)
Serge Bazanski62e6f0b2024-09-03 12:18:56 +0200698 }, backoff.WithContext(backoff.NewExponentialBackOff(backoff.WithMaxElapsedTime(time.Minute)), ctx))
Serge Bazanskibe742842022-04-04 13:18:50 +0200699 if err != nil {
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200700 return nil, nil, fmt.Errorf("couldn't retrieve owner certificate: %w", err)
Serge Bazanskibe742842022-04-04 13:18:50 +0200701 }
Serge Bazanski05f813b2023-03-16 17:58:39 +0100702 launch.Log("Cluster: retrieved owner certificate.")
Serge Bazanskibe742842022-04-04 13:18:50 +0200703
704 // Now connect authenticated and get the node ID.
Serge Bazanski8535cb52023-03-29 14:15:08 +0200705 creds := rpc.NewAuthenticatedCredentials(*cert, rpc.WantInsecure())
Serge Bazanskibe742842022-04-04 13:18:50 +0200706 authClient, err := grpc.Dial(remote, grpc.WithContextDialer(initDialer), grpc.WithTransportCredentials(creds))
707 if err != nil {
708 return nil, nil, fmt.Errorf("dialing with owner credentials failed: %w", err)
709 }
710 defer authClient.Close()
711 mgmt := apb.NewManagementClient(authClient)
712
713 var node *NodeInCluster
714 err = backoff.Retry(func() error {
715 nodes, err := getNodes(ctx, mgmt)
716 if err != nil {
717 return fmt.Errorf("retrieving nodes failed: %w", err)
718 }
719 if len(nodes) != 1 {
720 return fmt.Errorf("expected one node, got %d", len(nodes))
721 }
722 n := nodes[0]
723 if n.Status == nil || n.Status.ExternalAddress == "" {
724 return fmt.Errorf("node has no status and/or address")
725 }
726 node = &NodeInCluster{
727 ID: identity.NodeID(n.Pubkey),
728 ManagementAddress: n.Status.ExternalAddress,
729 }
730 return nil
731 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))
732 if err != nil {
733 return nil, nil, err
734 }
735
736 return cert, node, nil
Serge Bazanski66e58952021-10-05 17:06:56 +0200737}
738
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100739func NewSerialFileLogger(p string) (io.ReadWriter, error) {
Lorenz Brun150f24a2023-07-13 20:11:06 +0200740 f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE, 0o600)
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100741 if err != nil {
742 return nil, err
743 }
744 return f, nil
745}
746
Serge Bazanski66e58952021-10-05 17:06:56 +0200747// LaunchCluster launches a cluster of Metropolis node VMs together with a
748// Nanoswitch instance to network them all together.
749//
750// The given context will be used to run all qemu instances in the cluster, and
751// canceling the context or calling Close() will terminate them.
752func LaunchCluster(ctx context.Context, opts ClusterOptions) (*Cluster, error) {
Serge Bazanskie78a0892021-10-07 17:03:49 +0200753 if opts.NumNodes <= 0 {
Serge Bazanski66e58952021-10-05 17:06:56 +0200754 return nil, errors.New("refusing to start cluster with zero nodes")
755 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200756
Jan Schära9b060b2024-08-07 10:42:29 +0200757 // Prepare the node options. These will be kept as part of Cluster.
758 // nodeOpts[].Runtime will be initialized by LaunchNode during the first
759 // launch. The runtime information can be later used to restart a node.
760 // The 0th node will be initialized first. The rest will follow after it
761 // had bootstrapped the cluster.
762 nodeOpts := make([]NodeOptions, opts.NumNodes)
763 for i := range opts.NumNodes {
764 nodeOpts[i] = opts.Node
765 nodeOpts[i].Name = fmt.Sprintf("node%d", i)
766 nodeOpts[i].SerialPort = newPrefixedStdio(i)
767 }
768 nodeOpts[0].NodeParameters = &apb.NodeParameters{
769 Cluster: &apb.NodeParameters_ClusterBootstrap_{
770 ClusterBootstrap: &apb.NodeParameters_ClusterBootstrap{
771 OwnerPublicKey: InsecurePublicKey,
772 InitialClusterConfiguration: opts.InitialClusterConfiguration,
773 Labels: &cpb.NodeLabels{
774 Pairs: []*cpb.NodeLabels_Pair{
775 {Key: nodeNumberKey, Value: "0"},
776 },
777 },
778 },
779 },
780 }
781 nodeOpts[0].PcapDump = true
782
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200783 // Create the launch directory.
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100784 ld, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200785 if err != nil {
786 return nil, fmt.Errorf("failed to create the launch directory: %w", err)
787 }
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100788 // Create the metroctl config directory. We keep it in /tmp because in some
789 // scenarios it's end-user visible and we want it short.
790 md, err := os.MkdirTemp("/tmp", "metroctl-*")
791 if err != nil {
792 return nil, fmt.Errorf("failed to create the metroctl directory: %w", err)
793 }
794
795 // Create the socket directory. We keep it in /tmp because of socket path limits.
796 sd, err := os.MkdirTemp("/tmp", "cluster-*")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200797 if err != nil {
798 return nil, fmt.Errorf("failed to create the socket directory: %w", err)
799 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200800
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200801 // Set up TPM factory.
802 tpmf, err := NewTPMFactory(filepath.Join(ld, "tpm"))
803 if err != nil {
804 return nil, fmt.Errorf("failed to create TPM factory: %w", err)
805 }
806
Serge Bazanski66e58952021-10-05 17:06:56 +0200807 // Prepare links between nodes and nanoswitch.
808 var switchPorts []*os.File
Jan Schära9b060b2024-08-07 10:42:29 +0200809 for i := range opts.NumNodes {
Serge Bazanski66e58952021-10-05 17:06:56 +0200810 switchPort, vmPort, err := launch.NewSocketPair()
811 if err != nil {
Serge Bazanski66e58952021-10-05 17:06:56 +0200812 return nil, fmt.Errorf("failed to get socketpair: %w", err)
813 }
814 switchPorts = append(switchPorts, switchPort)
Jan Schära9b060b2024-08-07 10:42:29 +0200815 nodeOpts[i].ConnectToSocket = vmPort
Serge Bazanski66e58952021-10-05 17:06:56 +0200816 }
817
Serge Bazanskie78a0892021-10-07 17:03:49 +0200818 // Make a list of channels that will be populated by all running node qemu
819 // processes.
Serge Bazanski66e58952021-10-05 17:06:56 +0200820 done := make([]chan error, opts.NumNodes)
Lorenz Brun150f24a2023-07-13 20:11:06 +0200821 for i := range done {
Serge Bazanski66e58952021-10-05 17:06:56 +0200822 done[i] = make(chan error, 1)
823 }
824
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100825 if opts.NodeLogsToFiles {
Jan Schära9b060b2024-08-07 10:42:29 +0200826 for i := range opts.NumNodes {
827 path := path.Join(ld, fmt.Sprintf("node-%d.txt", i))
828 port, err := NewSerialFileLogger(path)
829 if err != nil {
830 return nil, fmt.Errorf("could not open log file for node %d: %w", i, err)
831 }
832 launch.Log("Node %d logs at %s", i, path)
833 nodeOpts[i].SerialPort = port
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100834 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100835 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200836
837 // Start the first node.
838 ctxT, ctxC := context.WithCancel(ctx)
Jan Schär0b927652024-07-31 18:08:50 +0200839 launch.Log("Cluster: Starting node %d...", 0)
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200840 if err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[0], done[0]); err != nil {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +0200841 ctxC()
842 return nil, fmt.Errorf("failed to launch first node: %w", err)
843 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200844
Lorenz Brun150f24a2023-07-13 20:11:06 +0200845 localRegistryAddr := net.TCPAddr{
846 IP: net.IPv4(10, 42, 0, 82),
847 Port: 5000,
848 }
849
850 var guestSvcMap launch.GuestServiceMap
851 if opts.LocalRegistry != nil {
852 l, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
853 if err != nil {
854 ctxC()
855 return nil, fmt.Errorf("failed to create TCP listener for local registry: %w", err)
856 }
857 s := http.Server{
858 Handler: opts.LocalRegistry,
859 }
860 go s.Serve(l)
861 go func() {
862 <-ctxT.Done()
863 s.Close()
864 }()
865 guestSvcMap = launch.GuestServiceMap{
866 &localRegistryAddr: *l.Addr().(*net.TCPAddr),
867 }
868 }
869
Serge Bazanskie78a0892021-10-07 17:03:49 +0200870 // Launch nanoswitch.
Serge Bazanski66e58952021-10-05 17:06:56 +0200871 portMap, err := launch.ConflictFreePortMap(ClusterPorts)
872 if err != nil {
873 ctxC()
874 return nil, fmt.Errorf("failed to allocate ephemeral ports: %w", err)
875 }
876
877 go func() {
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100878 var serialPort io.ReadWriter
879 if opts.NodeLogsToFiles {
880 path := path.Join(ld, "nanoswitch.txt")
881 serialPort, err = NewSerialFileLogger(path)
882 if err != nil {
883 launch.Log("Could not open log file for nanoswitch: %v", err)
884 }
885 launch.Log("Nanoswitch logs at %s", path)
886 } else {
887 serialPort = newPrefixedStdio(99)
888 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200889 if err := launch.RunMicroVM(ctxT, &launch.MicroVMOptions{
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100890 Name: "nanoswitch",
Tim Windelschmidt82e6af72024-07-23 00:05:42 +0000891 KernelPath: xKernelPath,
892 InitramfsPath: xInitramfsPath,
Serge Bazanski66e58952021-10-05 17:06:56 +0200893 ExtraNetworkInterfaces: switchPorts,
894 PortMap: portMap,
Lorenz Brun150f24a2023-07-13 20:11:06 +0200895 GuestServiceMap: guestSvcMap,
Serge Bazanskid09c58f2023-03-17 00:25:08 +0100896 SerialPort: serialPort,
Leopoldacfad5b2023-01-15 14:05:25 +0100897 PcapDump: path.Join(ld, "nanoswitch.pcap"),
Serge Bazanski66e58952021-10-05 17:06:56 +0200898 }); err != nil {
899 if !errors.Is(err, ctxT.Err()) {
Serge Bazanski05f813b2023-03-16 17:58:39 +0100900 launch.Fatal("Failed to launch nanoswitch: %v", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200901 }
902 }
903 }()
904
Serge Bazanskibe742842022-04-04 13:18:50 +0200905 // Build SOCKS dialer.
906 socksRemote := fmt.Sprintf("localhost:%v", portMap[SOCKSPort])
907 socksDialer, err := proxy.SOCKS5("tcp", socksRemote, nil, proxy.Direct)
Serge Bazanski66e58952021-10-05 17:06:56 +0200908 if err != nil {
909 ctxC()
Serge Bazanskibe742842022-04-04 13:18:50 +0200910 return nil, fmt.Errorf("failed to build SOCKS dialer: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200911 }
912
Serge Bazanskibe742842022-04-04 13:18:50 +0200913 // Retrieve owner credentials and first node.
914 cert, firstNode, err := firstConnection(ctxT, socksDialer)
Serge Bazanski66e58952021-10-05 17:06:56 +0200915 if err != nil {
916 ctxC()
917 return nil, err
918 }
Serge Bazanski66e58952021-10-05 17:06:56 +0200919
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100920 // Write credentials to the metroctl directory.
921 if err := metroctl.WriteOwnerKey(md, cert.PrivateKey.(ed25519.PrivateKey)); err != nil {
922 ctxC()
923 return nil, fmt.Errorf("could not write owner key: %w", err)
924 }
925 if err := metroctl.WriteOwnerCertificate(md, cert.Certificate[0]); err != nil {
926 ctxC()
927 return nil, fmt.Errorf("could not write owner certificate: %w", err)
928 }
929
Serge Bazanski53458ba2024-06-18 09:56:46 +0000930 launch.Log("Cluster: Node %d is %s", 0, firstNode.ID)
931
932 // Set up a partially initialized cluster instance, to be filled in the
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200933 // later steps.
Serge Bazanskibe742842022-04-04 13:18:50 +0200934 cluster := &Cluster{
935 Owner: *cert,
936 Ports: portMap,
937 Nodes: map[string]*NodeInCluster{
938 firstNode.ID: firstNode,
939 },
940 NodeIDs: []string{
941 firstNode.ID,
942 },
943
Serge Bazanski1f8cad72023-03-20 16:58:10 +0100944 nodesDone: done,
945 nodeOpts: nodeOpts,
946 launchDir: ld,
947 socketDir: sd,
948 metroctlDir: md,
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200949
Lorenz Brun276a7462023-07-12 21:28:54 +0200950 SOCKSDialer: socksDialer,
Serge Bazanskibe742842022-04-04 13:18:50 +0200951
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200952 ctxT: ctxT,
Serge Bazanskibe742842022-04-04 13:18:50 +0200953 ctxC: ctxC,
Serge Bazanski2b6dc312024-06-04 17:44:55 +0200954
955 tpmFactory: tpmf,
Serge Bazanskibe742842022-04-04 13:18:50 +0200956 }
957
958 // Now start the rest of the nodes and register them into the cluster.
959
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200960 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200961 curC, err := cluster.CuratorClient()
Serge Bazanski66e58952021-10-05 17:06:56 +0200962 if err != nil {
963 ctxC()
Serge Bazanski5bb8a332022-06-23 17:41:33 +0200964 return nil, fmt.Errorf("CuratorClient: %w", err)
Serge Bazanski66e58952021-10-05 17:06:56 +0200965 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200966 mgmt := apb.NewManagementClient(curC)
Serge Bazanskie78a0892021-10-07 17:03:49 +0200967
968 // Retrieve register ticket to register further nodes.
Serge Bazanski05f813b2023-03-16 17:58:39 +0100969 launch.Log("Cluster: retrieving register ticket...")
Serge Bazanskie78a0892021-10-07 17:03:49 +0200970 resT, err := mgmt.GetRegisterTicket(ctx, &apb.GetRegisterTicketRequest{})
971 if err != nil {
972 ctxC()
973 return nil, fmt.Errorf("GetRegisterTicket: %w", err)
974 }
975 ticket := resT.Ticket
Serge Bazanski05f813b2023-03-16 17:58:39 +0100976 launch.Log("Cluster: retrieved register ticket (%d bytes).", len(ticket))
Serge Bazanskie78a0892021-10-07 17:03:49 +0200977
978 // Retrieve cluster info (for directory and ca public key) to register further
979 // nodes.
980 resI, err := mgmt.GetClusterInfo(ctx, &apb.GetClusterInfoRequest{})
981 if err != nil {
982 ctxC()
983 return nil, fmt.Errorf("GetClusterInfo: %w", err)
984 }
Serge Bazanski54e212a2023-06-14 13:45:11 +0200985 caCert, err := x509.ParseCertificate(resI.CaCertificate)
986 if err != nil {
987 ctxC()
988 return nil, fmt.Errorf("ParseCertificate: %w", err)
989 }
990 cluster.CACertificate = caCert
Serge Bazanskie78a0892021-10-07 17:03:49 +0200991
Mateusz Zalega0246f5e2022-04-22 17:29:04 +0200992 // Use the retrieved information to configure the rest of the node options.
993 for i := 1; i < opts.NumNodes; i++ {
Jan Schära9b060b2024-08-07 10:42:29 +0200994 nodeOpts[i].NodeParameters = &apb.NodeParameters{
995 Cluster: &apb.NodeParameters_ClusterRegister_{
996 ClusterRegister: &apb.NodeParameters_ClusterRegister{
997 RegisterTicket: ticket,
998 ClusterDirectory: resI.ClusterDirectory,
999 CaCertificate: resI.CaCertificate,
1000 Labels: &cpb.NodeLabels{
1001 Pairs: []*cpb.NodeLabels_Pair{
1002 {Key: nodeNumberKey, Value: fmt.Sprintf("%d", i)},
Serge Bazanski30e30b32024-05-22 14:11:56 +02001003 },
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001004 },
1005 },
1006 },
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001007 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001008 }
1009
1010 // Now run the rest of the nodes.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001011 for i := 1; i < opts.NumNodes; i++ {
Jan Schär0b927652024-07-31 18:08:50 +02001012 launch.Log("Cluster: Starting node %d...", i)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001013 err := LaunchNode(ctxT, ld, sd, tpmf, &nodeOpts[i], done[i])
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001014 if err != nil {
Jan Schär0b927652024-07-31 18:08:50 +02001015 return nil, fmt.Errorf("failed to launch node %d: %w", i, err)
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001016 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001017 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001018
Serge Bazanski53458ba2024-06-18 09:56:46 +00001019 // Wait for nodes to appear as NEW, populate a map from node number (index into
Jan Schära9b060b2024-08-07 10:42:29 +02001020 // nodeOpts, etc.) to Metropolis Node ID.
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001021 seenNodes := make(map[string]bool)
Serge Bazanski53458ba2024-06-18 09:56:46 +00001022 nodeNumberToID := make(map[int]string)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001023 launch.Log("Cluster: waiting for nodes to appear as NEW...")
1024 for i := 1; i < opts.NumNodes; i++ {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001025 for {
1026 nodes, err := getNodes(ctx, mgmt)
1027 if err != nil {
1028 ctxC()
1029 return nil, fmt.Errorf("could not get nodes: %w", err)
1030 }
1031 for _, n := range nodes {
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001032 if n.State != cpb.NodeState_NODE_STATE_NEW {
1033 continue
Serge Bazanskie78a0892021-10-07 17:03:49 +02001034 }
Serge Bazanski87d9c592024-03-20 12:35:11 +01001035 if seenNodes[n.Id] {
1036 continue
1037 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001038 seenNodes[n.Id] = true
1039 cluster.Nodes[n.Id] = &NodeInCluster{
1040 ID: n.Id,
1041 Pubkey: n.Pubkey,
1042 }
Serge Bazanski53458ba2024-06-18 09:56:46 +00001043
1044 num, err := strconv.Atoi(node.GetNodeLabel(n.Labels, nodeNumberKey))
1045 if err != nil {
1046 return nil, fmt.Errorf("node %s has undecodable number label: %w", n.Id, err)
1047 }
1048 launch.Log("Cluster: Node %d is %s", num, n.Id)
1049 nodeNumberToID[num] = n.Id
Serge Bazanskie78a0892021-10-07 17:03:49 +02001050 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001051
1052 if len(seenNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001053 break
1054 }
1055 time.Sleep(1 * time.Second)
1056 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001057 }
1058 launch.Log("Found all expected nodes")
Serge Bazanskie78a0892021-10-07 17:03:49 +02001059
Serge Bazanski53458ba2024-06-18 09:56:46 +00001060 // Build the rest of NodeIDs from map.
1061 for i := 1; i < opts.NumNodes; i++ {
1062 cluster.NodeIDs = append(cluster.NodeIDs, nodeNumberToID[i])
1063 }
1064
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001065 approvedNodes := make(map[string]bool)
1066 upNodes := make(map[string]bool)
1067 if !opts.LeaveNodesNew {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001068 for {
1069 nodes, err := getNodes(ctx, mgmt)
1070 if err != nil {
1071 ctxC()
1072 return nil, fmt.Errorf("could not get nodes: %w", err)
1073 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001074 for _, node := range nodes {
1075 if !seenNodes[node.Id] {
1076 // Skip nodes that weren't NEW in the previous step.
Serge Bazanskie78a0892021-10-07 17:03:49 +02001077 continue
1078 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001079
1080 if node.State == cpb.NodeState_NODE_STATE_UP && node.Status != nil && node.Status.ExternalAddress != "" {
1081 launch.Log("Cluster: node %s is up", node.Id)
1082 upNodes[node.Id] = true
1083 cluster.Nodes[node.Id].ManagementAddress = node.Status.ExternalAddress
Serge Bazanskie78a0892021-10-07 17:03:49 +02001084 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001085 if upNodes[node.Id] {
1086 continue
Serge Bazanskibe742842022-04-04 13:18:50 +02001087 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001088
1089 if !approvedNodes[node.Id] {
1090 launch.Log("Cluster: approving node %s", node.Id)
1091 _, err := mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1092 Pubkey: node.Pubkey,
1093 })
1094 if err != nil {
1095 ctxC()
1096 return nil, fmt.Errorf("ApproveNode(%s): %w", node.Id, err)
1097 }
1098 approvedNodes[node.Id] = true
Serge Bazanskibe742842022-04-04 13:18:50 +02001099 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001100 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001101
Jan Schär0b927652024-07-31 18:08:50 +02001102 launch.Log("Cluster: want %d up nodes, have %d", opts.NumNodes, len(upNodes)+1)
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001103 if len(upNodes) == opts.NumNodes-1 {
Serge Bazanskie78a0892021-10-07 17:03:49 +02001104 break
1105 }
Serge Bazanskibe742842022-04-04 13:18:50 +02001106 time.Sleep(time.Second)
Serge Bazanskie78a0892021-10-07 17:03:49 +02001107 }
Serge Bazanskie78a0892021-10-07 17:03:49 +02001108 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001109
Serge Bazanski05f813b2023-03-16 17:58:39 +01001110 launch.Log("Cluster: all nodes up:")
Jan Schär0b927652024-07-31 18:08:50 +02001111 for i, nodeID := range cluster.NodeIDs {
1112 launch.Log("Cluster: %d. %s at %s", i, nodeID, cluster.Nodes[nodeID].ManagementAddress)
Serge Bazanskibe742842022-04-04 13:18:50 +02001113 }
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001114 launch.Log("Cluster: starting tests...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001115
Serge Bazanskibe742842022-04-04 13:18:50 +02001116 return cluster, nil
Serge Bazanski66e58952021-10-05 17:06:56 +02001117}
1118
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001119// RebootNode reboots the cluster member node matching the given index, and
1120// waits for it to rejoin the cluster. It will use the given context ctx to run
1121// cluster API requests, whereas the resulting QEMU process will be created
1122// using the cluster's context c.ctxT. The nodes are indexed starting at 0.
1123func (c *Cluster) RebootNode(ctx context.Context, idx int) error {
1124 if idx < 0 || idx >= len(c.NodeIDs) {
Serge Bazanskiee8c81b2024-04-03 11:59:38 +02001125 return fmt.Errorf("index out of bounds")
1126 }
1127 if c.nodeOpts[idx].Runtime == nil {
1128 return fmt.Errorf("node not running")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001129 }
1130 id := c.NodeIDs[idx]
1131
1132 // Get an authenticated owner client within the cluster.
Serge Bazanski5bb8a332022-06-23 17:41:33 +02001133 curC, err := c.CuratorClient()
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001134 if err != nil {
1135 return err
1136 }
1137 mgmt := apb.NewManagementClient(curC)
1138
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001139 // Cancel the node's context. This will shut down QEMU.
1140 c.nodeOpts[idx].Runtime.CtxC()
Serge Bazanski05f813b2023-03-16 17:58:39 +01001141 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001142 err = <-c.nodesDone[idx]
1143 if err != nil {
1144 return fmt.Errorf("while restarting node: %w", err)
1145 }
1146
1147 // Start QEMU again.
Serge Bazanski05f813b2023-03-16 17:58:39 +01001148 launch.Log("Cluster: restarting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001149 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 +02001150 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1151 }
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001152
Serge Bazanskibc969572024-03-21 11:56:13 +01001153 start := time.Now()
1154
1155 // Poll Management.GetNodes until the node is healthy.
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001156 for {
1157 cs, err := getNode(ctx, mgmt, id)
1158 if err != nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001159 launch.Log("Cluster: node get error: %v", err)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001160 return err
1161 }
Serge Bazanskibc969572024-03-21 11:56:13 +01001162 launch.Log("Cluster: node health: %+v", cs.Health)
1163
1164 lhb := time.Now().Add(-cs.TimeSinceHeartbeat.AsDuration())
1165 if lhb.After(start) && cs.Health == apb.Node_HEALTHY {
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001166 break
1167 }
1168 time.Sleep(time.Second)
1169 }
Serge Bazanski05f813b2023-03-16 17:58:39 +01001170 launch.Log("Cluster: node %d (%s) has rejoined the cluster.", idx, id)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001171 return nil
1172}
1173
Serge Bazanski500f6e02024-04-03 12:06:40 +02001174// ShutdownNode performs an ungraceful shutdown (i.e. power off) of the node
1175// given by idx. If the node is already shut down, this is a no-op.
1176func (c *Cluster) ShutdownNode(idx int) error {
1177 if idx < 0 || idx >= len(c.NodeIDs) {
1178 return fmt.Errorf("index out of bounds")
1179 }
1180 // Return if node is already stopped.
1181 select {
1182 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1183 return nil
1184 default:
1185 }
1186 id := c.NodeIDs[idx]
1187
1188 // Cancel the node's context. This will shut down QEMU.
1189 c.nodeOpts[idx].Runtime.CtxC()
1190 launch.Log("Cluster: waiting for node %d (%s) to stop.", idx, id)
1191 err := <-c.nodesDone[idx]
1192 if err != nil {
1193 return fmt.Errorf("while shutting down node: %w", err)
1194 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001195 launch.Log("Cluster: node %d (%s) stopped.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001196 return nil
1197}
1198
1199// StartNode performs a power on of the node given by idx. If the node is already
1200// running, this is a no-op.
1201func (c *Cluster) StartNode(idx int) error {
1202 if idx < 0 || idx >= len(c.NodeIDs) {
1203 return fmt.Errorf("index out of bounds")
1204 }
1205 id := c.NodeIDs[idx]
1206 // Return if node is already running.
1207 select {
1208 case <-c.nodeOpts[idx].Runtime.ctxT.Done():
1209 default:
1210 return nil
1211 }
1212
1213 // Start QEMU again.
1214 launch.Log("Cluster: starting node %d (%s).", idx, id)
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001215 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 +02001216 return fmt.Errorf("failed to launch node %d: %w", idx, err)
1217 }
Serge Bazanski2b6dc312024-06-04 17:44:55 +02001218 launch.Log("Cluster: node %d (%s) started.", idx, id)
Serge Bazanski500f6e02024-04-03 12:06:40 +02001219 return nil
1220}
1221
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001222// Close cancels the running clusters' context and waits for all virtualized
Serge Bazanski66e58952021-10-05 17:06:56 +02001223// nodes to stop. It returns an error if stopping the nodes failed, or one of
1224// the nodes failed to fully start in the first place.
1225func (c *Cluster) Close() error {
Serge Bazanski05f813b2023-03-16 17:58:39 +01001226 launch.Log("Cluster: stopping...")
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001227 if c.authClient != nil {
1228 c.authClient.Close()
1229 }
Serge Bazanski66e58952021-10-05 17:06:56 +02001230 c.ctxC()
1231
Leopold20a036e2023-01-15 00:17:19 +01001232 var errs []error
Serge Bazanski05f813b2023-03-16 17:58:39 +01001233 launch.Log("Cluster: waiting for nodes to exit...")
Serge Bazanski66e58952021-10-05 17:06:56 +02001234 for _, c := range c.nodesDone {
1235 err := <-c
1236 if err != nil {
Leopold20a036e2023-01-15 00:17:19 +01001237 errs = append(errs, err)
Serge Bazanski66e58952021-10-05 17:06:56 +02001238 }
1239 }
Serge Bazanskid09c58f2023-03-17 00:25:08 +01001240 launch.Log("Cluster: removing nodes' state files (%s) and sockets (%s).", c.launchDir, c.socketDir)
Mateusz Zalega0246f5e2022-04-22 17:29:04 +02001241 os.RemoveAll(c.launchDir)
1242 os.RemoveAll(c.socketDir)
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001243 os.RemoveAll(c.metroctlDir)
Serge Bazanski05f813b2023-03-16 17:58:39 +01001244 launch.Log("Cluster: done")
Leopold20a036e2023-01-15 00:17:19 +01001245 return multierr.Combine(errs...)
Serge Bazanski66e58952021-10-05 17:06:56 +02001246}
Serge Bazanskibe742842022-04-04 13:18:50 +02001247
1248// DialNode is a grpc.WithContextDialer compatible dialer which dials nodes by
1249// their ID. This is performed by connecting to the cluster nanoswitch via its
1250// SOCKS proxy, and using the cluster node list for name resolution.
1251//
1252// For example:
1253//
Serge Bazanski05f813b2023-03-16 17:58:39 +01001254// grpc.Dial("metropolis-deadbeef:1234", grpc.WithContextDialer(c.DialNode))
Serge Bazanskibe742842022-04-04 13:18:50 +02001255func (c *Cluster) DialNode(_ context.Context, addr string) (net.Conn, error) {
1256 host, port, err := net.SplitHostPort(addr)
1257 if err != nil {
1258 return nil, fmt.Errorf("invalid host:port: %w", err)
1259 }
1260 // Already an IP address?
1261 if net.ParseIP(host) != nil {
Lorenz Brun276a7462023-07-12 21:28:54 +02001262 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001263 }
1264
1265 // Otherwise, expect a node name.
1266 node, ok := c.Nodes[host]
1267 if !ok {
1268 return nil, fmt.Errorf("unknown node %q", host)
1269 }
1270 addr = net.JoinHostPort(node.ManagementAddress, port)
Lorenz Brun276a7462023-07-12 21:28:54 +02001271 return c.SOCKSDialer.Dial("tcp", addr)
Serge Bazanskibe742842022-04-04 13:18:50 +02001272}
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001273
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001274// GetKubeClientSet gets a Kubernetes client set accessing the Metropolis
1275// Kubernetes authenticating proxy using the cluster owner identity.
1276// It currently has access to everything (i.e. the cluster-admin role)
1277// via the owner-admin binding.
1278func (c *Cluster) GetKubeClientSet() (kubernetes.Interface, error) {
1279 pkcs8Key, err := x509.MarshalPKCS8PrivateKey(c.Owner.PrivateKey)
1280 if err != nil {
1281 // We explicitly pass an Ed25519 private key in, so this can't happen
1282 panic(err)
1283 }
1284
1285 host := net.JoinHostPort(c.NodeIDs[0], node.KubernetesAPIWrappedPort.PortString())
Lorenz Brun150f24a2023-07-13 20:11:06 +02001286 clientConfig := rest.Config{
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001287 Host: host,
1288 TLSClientConfig: rest.TLSClientConfig{
1289 // TODO(q3k): use CA certificate
1290 Insecure: true,
1291 ServerName: "kubernetes.default.svc",
1292 CertData: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.Owner.Certificate[0]}),
1293 KeyData: pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8Key}),
1294 },
1295 Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
1296 return c.DialNode(ctx, address)
1297 },
1298 }
1299 return kubernetes.NewForConfig(&clientConfig)
1300}
1301
Serge Bazanski1f8cad72023-03-20 16:58:10 +01001302// KubernetesControllerNodeAddresses returns the list of IP addresses of nodes
1303// which are currently Kubernetes controllers, ie. run an apiserver. This list
1304// might be empty if no node is currently configured with the
1305// 'KubernetesController' node.
1306func (c *Cluster) KubernetesControllerNodeAddresses(ctx context.Context) ([]string, error) {
1307 curC, err := c.CuratorClient()
1308 if err != nil {
1309 return nil, err
1310 }
1311 mgmt := apb.NewManagementClient(curC)
1312 srv, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{
1313 Filter: "has(node.roles.kubernetes_controller)",
1314 })
1315 if err != nil {
1316 return nil, err
1317 }
1318 defer srv.CloseSend()
1319 var res []string
1320 for {
1321 n, err := srv.Recv()
1322 if err == io.EOF {
1323 break
1324 }
1325 if err != nil {
1326 return nil, err
1327 }
1328 if n.Status == nil || n.Status.ExternalAddress == "" {
1329 continue
1330 }
1331 res = append(res, n.Status.ExternalAddress)
1332 }
1333 return res, nil
1334}
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001335
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001336// AllNodesHealthy returns nil if all the nodes in the cluster are seemingly
1337// healthy.
Serge Bazanski630fb5c2023-04-06 10:50:24 +02001338func (c *Cluster) AllNodesHealthy(ctx context.Context) error {
1339 // Get an authenticated owner client within the cluster.
1340 curC, err := c.CuratorClient()
1341 if err != nil {
1342 return err
1343 }
1344 mgmt := apb.NewManagementClient(curC)
1345 nodes, err := getNodes(ctx, mgmt)
1346 if err != nil {
1347 return err
1348 }
1349
1350 var unhealthy []string
1351 for _, node := range nodes {
1352 if node.Health == apb.Node_HEALTHY {
1353 continue
1354 }
1355 unhealthy = append(unhealthy, node.Id)
1356 }
1357 if len(unhealthy) == 0 {
1358 return nil
1359 }
1360 return fmt.Errorf("nodes unhealthy: %s", strings.Join(unhealthy, ", "))
1361}
Serge Bazanskia0bc6d32023-06-28 18:57:40 +02001362
1363// ApproveNode approves a node by ID, waiting for it to become UP.
1364func (c *Cluster) ApproveNode(ctx context.Context, id string) error {
1365 curC, err := c.CuratorClient()
1366 if err != nil {
1367 return err
1368 }
1369 mgmt := apb.NewManagementClient(curC)
1370
1371 _, err = mgmt.ApproveNode(ctx, &apb.ApproveNodeRequest{
1372 Pubkey: c.Nodes[id].Pubkey,
1373 })
1374 if err != nil {
1375 return fmt.Errorf("ApproveNode: %w", err)
1376 }
1377 launch.Log("Cluster: %s: approved, waiting for UP", id)
1378 for {
1379 nodes, err := mgmt.GetNodes(ctx, &apb.GetNodesRequest{})
1380 if err != nil {
1381 return fmt.Errorf("GetNodes: %w", err)
1382 }
1383 found := false
1384 for {
1385 node, err := nodes.Recv()
1386 if errors.Is(err, io.EOF) {
1387 break
1388 }
1389 if err != nil {
1390 return fmt.Errorf("Nodes.Recv: %w", err)
1391 }
1392 if node.Id != id {
1393 continue
1394 }
1395 if node.State != cpb.NodeState_NODE_STATE_UP {
1396 continue
1397 }
1398 found = true
1399 break
1400 }
1401 nodes.CloseSend()
1402
1403 if found {
1404 break
1405 }
1406 time.Sleep(time.Second)
1407 }
1408 launch.Log("Cluster: %s: UP", id)
1409 return nil
1410}
1411
1412// MakeKubernetesWorker adds the KubernetesWorker role to a node by ID.
1413func (c *Cluster) MakeKubernetesWorker(ctx context.Context, id string) error {
1414 curC, err := c.CuratorClient()
1415 if err != nil {
1416 return err
1417 }
1418 mgmt := apb.NewManagementClient(curC)
1419
1420 tr := true
1421 launch.Log("Cluster: %s: adding KubernetesWorker", id)
1422 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1423 Node: &apb.UpdateNodeRolesRequest_Id{
1424 Id: id,
1425 },
1426 KubernetesWorker: &tr,
1427 })
1428 return err
1429}
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001430
Jan Schära9b060b2024-08-07 10:42:29 +02001431// MakeKubernetesController adds the KubernetesController role to a node by ID.
1432func (c *Cluster) MakeKubernetesController(ctx context.Context, id string) error {
1433 curC, err := c.CuratorClient()
1434 if err != nil {
1435 return err
1436 }
1437 mgmt := apb.NewManagementClient(curC)
1438
1439 tr := true
1440 launch.Log("Cluster: %s: adding KubernetesController", id)
1441 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1442 Node: &apb.UpdateNodeRolesRequest_Id{
1443 Id: id,
1444 },
1445 KubernetesController: &tr,
1446 })
1447 return err
1448}
1449
Serge Bazanski37cfcc12024-03-21 11:59:07 +01001450// MakeConsensusMember adds the ConsensusMember role to a node by ID.
1451func (c *Cluster) MakeConsensusMember(ctx context.Context, id string) error {
1452 curC, err := c.CuratorClient()
1453 if err != nil {
1454 return err
1455 }
1456 mgmt := apb.NewManagementClient(curC)
1457 cur := ipb.NewCuratorClient(curC)
1458
1459 tr := true
1460 launch.Log("Cluster: %s: adding ConsensusMember", id)
1461 bo := backoff.NewExponentialBackOff()
1462 bo.MaxElapsedTime = 10 * time.Second
1463
1464 backoff.Retry(func() error {
1465 _, err = mgmt.UpdateNodeRoles(ctx, &apb.UpdateNodeRolesRequest{
1466 Node: &apb.UpdateNodeRolesRequest_Id{
1467 Id: id,
1468 },
1469 ConsensusMember: &tr,
1470 })
1471 if err != nil {
1472 launch.Log("Cluster: %s: UpdateNodeRoles failed: %v", id, err)
1473 }
1474 return err
1475 }, backoff.WithContext(bo, ctx))
1476 if err != nil {
1477 return err
1478 }
1479
1480 launch.Log("Cluster: %s: waiting for learner/full members...", id)
1481
1482 learner := false
1483 for {
1484 res, err := cur.GetConsensusStatus(ctx, &ipb.GetConsensusStatusRequest{})
1485 if err != nil {
1486 return fmt.Errorf("GetConsensusStatus: %w", err)
1487 }
1488 for _, member := range res.EtcdMember {
1489 if member.Id != id {
1490 continue
1491 }
1492 switch member.Status {
1493 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_LEARNER:
1494 if !learner {
1495 learner = true
1496 launch.Log("Cluster: %s: became a learner, waiting for full member...", id)
1497 }
1498 case ipb.GetConsensusStatusResponse_EtcdMember_STATUS_FULL:
1499 launch.Log("Cluster: %s: became a full member", id)
1500 return nil
1501 }
1502 }
1503 time.Sleep(100 * time.Millisecond)
1504 }
1505}