blob: 41cd2b5a704f52ce0e8538249069fc7756996b77 [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, " "))
28 found, err := cmd.RunCommand(ctx, path, args, expect)
29 if err != nil {
30 return fmt.Errorf("while running metroctl: %v", err)
31 }
32 if !found {
33 return fmt.Errorf("expected string wasn't found while running metroctl.")
34 }
35 return nil
36}
37
38func TestMetroctl(t *testing.T) {
39 ctx, ctxC := context.WithCancel(context.Background())
40 defer ctxC()
41
42 co := cluster.ClusterOptions{
43 NumNodes: 2,
44 }
45 cl, err := cluster.LaunchCluster(context.Background(), co)
46 if err != nil {
47 t.Fatalf("LaunchCluster failed: %v", err)
48 }
49 defer func() {
50 err := cl.Close()
51 if err != nil {
52 t.Fatalf("cluster Close failed: %v", err)
53 }
54 }()
55
56 socksRemote := fmt.Sprintf("localhost:%d", cl.Ports[cluster.SOCKSPort])
57 var clusterEndpoints []string
58 for _, ep := range cl.Nodes {
59 clusterEndpoints = append(clusterEndpoints, ep.ManagementAddress)
60 }
61
62 ownerPem := pem.EncodeToMemory(&pem.Block{
63 Type: "METROPOLIS INITIAL OWNER PRIVATE KEY",
64 Bytes: cluster.InsecurePrivateKey,
65 })
66 if err := os.WriteFile("owner-key.pem", ownerPem, 0644); err != nil {
67 log.Fatal("Couldn't write owner-key.pem")
68 }
69
70 commonOpts := []string{
71 "--proxy=" + socksRemote,
72 "--config=.",
73 }
74
75 var endpointOpts []string
76 for _, ep := range clusterEndpoints {
77 endpointOpts = append(endpointOpts, "--endpoints="+ep)
78 }
79
80 log.Printf("metroctl: Cluster's running, starting tests...")
81 st := t.Run("Init", func(t *testing.T) {
82 util.TestEventual(t, "metroctl takeownership", ctx, 30*time.Second, func(ctx context.Context) error {
83 // takeownership needs just a single endpoint pointing at the initial node.
84 var args []string
85 args = append(args, commonOpts...)
86 args = append(args, endpointOpts[0])
87 args = append(args, "takeownership")
88 return expectMetroctl(t, ctx, args, "Successfully retrieved owner credentials")
89 })
90 })
91 if !st {
92 t.Fatalf("metroctl: Couldn't get cluster ownership.")
93 }
94}