blob: 711855b54e2a9f3a2b16bf52deca2482b3f4b597 [file] [log] [blame]
Tim Windelschmidt9f21f532024-05-07 15:14:20 +02001package launch
Serge Bazanski1f8cad72023-03-20 16:58:10 +01002
3import (
Serge Bazanski7eeef0f2024-02-05 14:40:15 +01004 "context"
5 "crypto/x509"
Serge Bazanski1f8cad72023-03-20 16:58:10 +01006 "fmt"
7 "net"
8 "os"
9 "path"
10 "sort"
11
12 "github.com/kballard/go-shellquote"
13
14 metroctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski1f8cad72023-03-20 16:58:10 +010015)
16
Serge Bazanski7eeef0f2024-02-05 14:40:15 +010017type acceptall struct{}
18
19func (a *acceptall) Ask(ctx context.Context, _ *metroctl.ConnectOptions, _ *x509.Certificate) (bool, error) {
20 return true, nil
21}
22
Serge Bazanski1f8cad72023-03-20 16:58:10 +010023// ConnectOptions returns metroctl.ConnectOptions that describe connectivity to
24// the launched cluster.
25func (c *Cluster) ConnectOptions() *metroctl.ConnectOptions {
26 // Use all metropolis nodes as endpoints. That's fine, metroctl's resolver will
27 // figure out what to actually use.
28 var endpoints []string
29 for _, n := range c.Nodes {
30 endpoints = append(endpoints, n.ManagementAddress)
31 }
32 sort.Strings(endpoints)
33 return &metroctl.ConnectOptions{
34 ConfigPath: c.metroctlDir,
35 ProxyServer: net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", c.Ports[SOCKSPort])),
36 Endpoints: endpoints,
Serge Bazanski7eeef0f2024-02-05 14:40:15 +010037 TOFU: &acceptall{},
Serge Bazanski1f8cad72023-03-20 16:58:10 +010038 }
39}
40
41// MetroctlFlags return stringified flags to pass to a metroctl binary to connect
42// to the launched cluster.
43func (c *Cluster) MetroctlFlags() string {
44 return shellquote.Join(c.ConnectOptions().ToFlags()...)
45}
46
47// MakeMetroctlWrapper builds and returns the path to a shell script which calls
48// metroctl (from //metropolis/cli/metroctl, which must be included as a data
49// dependency of the built target) with all the required flags to connect to the
50// launched cluster.
51func (c *Cluster) MakeMetroctlWrapper() (string, error) {
Serge Bazanski1f8cad72023-03-20 16:58:10 +010052 wpath := path.Join(c.metroctlDir, "metroctl.sh")
53
54 // Don't create wrapper if it already exists.
55 if _, err := os.Stat(wpath); err == nil {
56 return wpath, nil
57 }
58
Tim Windelschmidt82e6af72024-07-23 00:05:42 +000059 wrapper := fmt.Sprintf("#!/usr/bin/env bash\nexec %s %s \"$@\"", xMetroctlPath, c.MetroctlFlags())
Serge Bazanski1f8cad72023-03-20 16:58:10 +010060 if err := os.WriteFile(wpath, []byte(wrapper), 0555); err != nil {
61 return "", fmt.Errorf("could not write wrapper: %w", err)
62 }
63 return wpath, nil
64}