21572: Avoid using lsb_release in Debian repository
[arvados.git] / lib / cloud / cloudtest / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package cloudtest
6
7 import (
8         "bufio"
9         "errors"
10         "flag"
11         "fmt"
12         "io"
13         "os"
14
15         "git.arvados.org/arvados.git/lib/cloud"
16         "git.arvados.org/arvados.git/lib/cmd"
17         "git.arvados.org/arvados.git/lib/config"
18         "git.arvados.org/arvados.git/lib/dispatchcloud"
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "git.arvados.org/arvados.git/sdk/go/ctxlog"
21 )
22
23 var Command command
24
25 type command struct{}
26
27 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
28         var err error
29         defer func() {
30                 if err != nil {
31                         fmt.Fprintf(stderr, "%s\n", err)
32                 }
33         }()
34
35         flags := flag.NewFlagSet("", flag.ContinueOnError)
36         flags.SetOutput(stderr)
37         configFile := flags.String("config", arvados.DefaultConfigFile, "Site configuration `file`")
38         instanceSetID := flags.String("instance-set-id", "zzzzz-zzzzz-zzzzzzcloudtest", "InstanceSetID tag `value` to use on the test instance")
39         imageID := flags.String("image-id", "", "Image ID to use when creating the test instance (if empty, use cluster config)")
40         instanceType := flags.String("instance-type", "", "Instance type to create (if empty, use cheapest type in config)")
41         destroyExisting := flags.Bool("destroy-existing", false, "Destroy any existing instances tagged with our InstanceSetID, instead of erroring out")
42         shellCommand := flags.String("command", "", "Run an interactive shell command on the test instance when it boots")
43         pauseBeforeDestroy := flags.Bool("pause-before-destroy", false, "Prompt and wait before destroying the test instance")
44         if ok, code := cmd.ParseFlags(flags, prog, args, "", stderr); !ok {
45                 return code
46         }
47         logger := ctxlog.New(stderr, "text", "info")
48         defer func() {
49                 if err != nil {
50                         logger.WithError(err).Error("fatal")
51                         // suppress output from the other error-printing func
52                         err = nil
53                 }
54                 logger.Info("exiting")
55         }()
56
57         loader := config.NewLoader(stdin, logger)
58         loader.Path = *configFile
59         cfg, err := loader.Load()
60         if err != nil {
61                 return 1
62         }
63         cluster, err := cfg.GetCluster("")
64         if err != nil {
65                 return 1
66         }
67         key, err := config.LoadSSHKey(cluster.Containers.DispatchPrivateKey)
68         if err != nil {
69                 err = fmt.Errorf("error loading Containers.DispatchPrivateKey: %s", err)
70                 return 1
71         }
72         driver, ok := dispatchcloud.Drivers[cluster.Containers.CloudVMs.Driver]
73         if !ok {
74                 err = fmt.Errorf("unsupported cloud driver %q", cluster.Containers.CloudVMs.Driver)
75                 return 1
76         }
77         if *imageID == "" {
78                 *imageID = cluster.Containers.CloudVMs.ImageID
79         }
80         it, err := chooseInstanceType(cluster, *instanceType)
81         if err != nil {
82                 return 1
83         }
84         tags := cloud.SharedResourceTags(cluster.Containers.CloudVMs.ResourceTags)
85         tagKeyPrefix := cluster.Containers.CloudVMs.TagKeyPrefix
86         tags[tagKeyPrefix+"CloudTestPID"] = fmt.Sprintf("%d", os.Getpid())
87         if !(&tester{
88                 Logger:              logger,
89                 Tags:                tags,
90                 TagKeyPrefix:        tagKeyPrefix,
91                 SetID:               cloud.InstanceSetID(*instanceSetID),
92                 DestroyExisting:     *destroyExisting,
93                 ProbeInterval:       cluster.Containers.CloudVMs.ProbeInterval.Duration(),
94                 SyncInterval:        cluster.Containers.CloudVMs.SyncInterval.Duration(),
95                 TimeoutBooting:      cluster.Containers.CloudVMs.TimeoutBooting.Duration(),
96                 Driver:              driver,
97                 DriverParameters:    cluster.Containers.CloudVMs.DriverParameters,
98                 ImageID:             cloud.ImageID(*imageID),
99                 InstanceType:        it,
100                 SSHKey:              key,
101                 SSHPort:             cluster.Containers.CloudVMs.SSHPort,
102                 DeployPublicKey:     cluster.Containers.CloudVMs.DeployPublicKey,
103                 BootProbeCommand:    cluster.Containers.CloudVMs.BootProbeCommand,
104                 InstanceInitCommand: cloud.InitCommand(cluster.Containers.CloudVMs.InstanceInitCommand),
105                 ShellCommand:        *shellCommand,
106                 PauseBeforeDestroy: func() {
107                         if *pauseBeforeDestroy {
108                                 logger.Info("waiting for operator to press Enter")
109                                 fmt.Fprint(stderr, "Press Enter to continue: ")
110                                 bufio.NewReader(stdin).ReadString('\n')
111                         }
112                 },
113         }).Run() {
114                 return 1
115         }
116         return 0
117 }
118
119 // Return the named instance type, or the cheapest type if name=="".
120 func chooseInstanceType(cluster *arvados.Cluster, name string) (arvados.InstanceType, error) {
121         if len(cluster.InstanceTypes) == 0 {
122                 return arvados.InstanceType{}, errors.New("no instance types are configured")
123         } else if name == "" {
124                 first := true
125                 var best arvados.InstanceType
126                 for _, it := range cluster.InstanceTypes {
127                         if first || best.Price > it.Price {
128                                 best = it
129                                 first = false
130                         }
131                 }
132                 return best, nil
133         } else if it, ok := cluster.InstanceTypes[name]; !ok {
134                 return it, fmt.Errorf("requested instance type %q is not configured", name)
135         } else {
136                 return it, nil
137         }
138 }