blob: 4f572a170f554eaa4d3dd1eff6b9fe2d15bde65e [file] [log] [blame]
Mateusz Zalegafed8fe52022-07-14 16:19:35 +02001package test
2
3import (
4 "context"
5 "encoding/pem"
6 "fmt"
7 "log"
8 "os"
9 "strings"
10 "testing"
11 "time"
12
13 "source.monogon.dev/metropolis/cli/pkg/datafile"
14 "source.monogon.dev/metropolis/pkg/cmd"
15 "source.monogon.dev/metropolis/test/launch/cluster"
16 "source.monogon.dev/metropolis/test/util"
17)
18
19func expectMetroctl(t *testing.T, ctx context.Context, args []string, expect string) error {
20 t.Helper()
21
22 path, err := datafile.ResolveRunfile("metropolis/cli/metroctl/metroctl_/metroctl")
23 if err != nil {
24 return fmt.Errorf("couldn't resolve metroctl binary: %v", err)
25 }
26
27 log.Printf("$ metroctl %s", strings.Join(args, " "))
Mateusz Zalega6cdc9762022-08-03 17:15:01 +020028 // Terminate metroctl as soon as the expected output is found.
29 found, err := cmd.RunCommand(ctx, path, args, cmd.TerminateIfFound(expect))
Mateusz Zalegafed8fe52022-07-14 16:19:35 +020030 if err != nil {
31 return fmt.Errorf("while running metroctl: %v", err)
32 }
33 if !found {
34 return fmt.Errorf("expected string wasn't found while running metroctl.")
35 }
36 return nil
37}
38
39func TestMetroctl(t *testing.T) {
40 ctx, ctxC := context.WithCancel(context.Background())
41 defer ctxC()
42
43 co := cluster.ClusterOptions{
44 NumNodes: 2,
45 }
46 cl, err := cluster.LaunchCluster(context.Background(), co)
47 if err != nil {
48 t.Fatalf("LaunchCluster failed: %v", err)
49 }
50 defer func() {
51 err := cl.Close()
52 if err != nil {
53 t.Fatalf("cluster Close failed: %v", err)
54 }
55 }()
56
57 socksRemote := fmt.Sprintf("localhost:%d", cl.Ports[cluster.SOCKSPort])
58 var clusterEndpoints []string
59 for _, ep := range cl.Nodes {
60 clusterEndpoints = append(clusterEndpoints, ep.ManagementAddress)
61 }
62
63 ownerPem := pem.EncodeToMemory(&pem.Block{
64 Type: "METROPOLIS INITIAL OWNER PRIVATE KEY",
65 Bytes: cluster.InsecurePrivateKey,
66 })
67 if err := os.WriteFile("owner-key.pem", ownerPem, 0644); err != nil {
68 log.Fatal("Couldn't write owner-key.pem")
69 }
70
71 commonOpts := []string{
72 "--proxy=" + socksRemote,
73 "--config=.",
74 }
75
76 var endpointOpts []string
77 for _, ep := range clusterEndpoints {
78 endpointOpts = append(endpointOpts, "--endpoints="+ep)
79 }
80
81 log.Printf("metroctl: Cluster's running, starting tests...")
82 st := t.Run("Init", func(t *testing.T) {
83 util.TestEventual(t, "metroctl takeownership", ctx, 30*time.Second, func(ctx context.Context) error {
84 // takeownership needs just a single endpoint pointing at the initial node.
85 var args []string
86 args = append(args, commonOpts...)
87 args = append(args, endpointOpts[0])
88 args = append(args, "takeownership")
89 return expectMetroctl(t, ctx, args, "Successfully retrieved owner credentials")
90 })
91 })
92 if !st {
93 t.Fatalf("metroctl: Couldn't get cluster ownership.")
94 }
95}