forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.go
455 lines (398 loc) · 11.7 KB
/
commands.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package commands
import (
"errors"
"fmt"
"os"
"strings"
"github.com/codegangsta/cli"
"github.com/docker/machine/commands/mcndirs"
"github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/crashreport"
"github.com/docker/machine/libmachine/host"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnerror"
"github.com/docker/machine/libmachine/mcnutils"
"github.com/docker/machine/libmachine/persist"
"github.com/docker/machine/libmachine/ssh"
)
const (
defaultMachineName = "default"
)
var (
ErrHostLoad = errors.New("All specified hosts had errors loading their configuration.")
ErrNoDefault = fmt.Errorf("Error: No machine name(s) specified and no %q machine exists.", defaultMachineName)
ErrNoMachineSpecified = errors.New("Error: Expected to get one or more machine names as arguments")
ErrExpectedOneMachine = errors.New("Error: Expected one machine name as an argument")
ErrTooManyArguments = errors.New("Error: Too many arguments given")
osExit = func(code int) { os.Exit(code) }
)
// CommandLine contains all the information passed to the commands on the command line.
type CommandLine interface {
ShowHelp()
ShowVersion()
Application() *cli.App
Args() cli.Args
Bool(name string) bool
Int(name string) int
String(name string) string
StringSlice(name string) []string
GlobalString(name string) string
FlagNames() (names []string)
Generic(name string) interface{}
}
type contextCommandLine struct {
*cli.Context
}
func (c *contextCommandLine) ShowHelp() {
cli.ShowCommandHelp(c.Context, c.Command.Name)
}
func (c *contextCommandLine) ShowVersion() {
cli.ShowVersion(c.Context)
}
func (c *contextCommandLine) Application() *cli.App {
return c.App
}
// targetHost returns a specific host name if one is indicated by the first CLI
// arg, or the default host name if no host is specified.
func targetHost(c CommandLine, api libmachine.API) (string, error) {
if len(c.Args()) == 0 {
defaultExists, err := api.Exists(defaultMachineName)
if err != nil {
return "", fmt.Errorf("Error checking if host %q exists: %s", defaultMachineName, err)
}
if defaultExists {
return defaultMachineName, nil
}
return "", ErrNoDefault
}
return c.Args()[0], nil
}
func runAction(actionName string, c CommandLine, api libmachine.API) error {
var (
hostsToLoad []string
)
// If user did not specify a machine name explicitly, use the 'default'
// machine if it exists. This allows short form commands such as
// 'docker-machine stop' for convenience.
if len(c.Args()) == 0 {
target, err := targetHost(c, api)
if err != nil {
return err
}
hostsToLoad = []string{target}
} else {
hostsToLoad = c.Args()
}
hosts, hostsInError := persist.LoadHosts(api, hostsToLoad)
if len(hostsInError) > 0 {
errs := []error{}
for _, err := range hostsInError {
errs = append(errs, err)
}
return consolidateErrs(errs)
}
if len(hosts) == 0 {
return ErrHostLoad
}
if errs := runActionForeachMachine(actionName, hosts); len(errs) > 0 {
return consolidateErrs(errs)
}
for _, h := range hosts {
if err := api.Save(h); err != nil {
return fmt.Errorf("Error saving host to store: %s", err)
}
}
return nil
}
func runCommand(command func(commandLine CommandLine, api libmachine.API) error) func(context *cli.Context) {
return func(context *cli.Context) {
api := libmachine.NewClient(mcndirs.GetBaseDir(), mcndirs.GetMachineCertDir())
defer api.Close()
if context.GlobalBool("native-ssh") {
api.SSHClientType = ssh.Native
}
api.GithubAPIToken = context.GlobalString("github-api-token")
api.Filestore.Path = context.GlobalString("storage-path")
// TODO (nathanleclaire): These should ultimately be accessed
// through the libmachine client by the rest of the code and
// not through their respective modules. For now, however,
// they are also being set the way that they originally were
// set to preserve backwards compatibility.
mcndirs.BaseDir = api.Filestore.Path
mcnutils.GithubAPIToken = api.GithubAPIToken
ssh.SetDefaultClient(api.SSHClientType)
if err := command(&contextCommandLine{context}, api); err != nil {
log.Error(err)
if crashErr, ok := err.(crashreport.CrashError); ok {
crashReporter := crashreport.NewCrashReporter(mcndirs.GetBaseDir(), context.GlobalString("bugsnag-api-token"))
crashReporter.Send(crashErr)
if _, ok := crashErr.Cause.(mcnerror.ErrDuringPreCreate); ok {
osExit(3)
return
}
}
osExit(1)
return
}
}
}
func confirmInput(msg string) (bool, error) {
fmt.Printf("%s (y/n): ", msg)
var resp string
_, err := fmt.Scanln(&resp)
if err != nil {
return false, err
}
confirmed := strings.Index(strings.ToLower(resp), "y") == 0
return confirmed, nil
}
var Commands = []cli.Command{
{
Name: "active",
Usage: "Print which machine is active",
Action: runCommand(cmdActive),
},
{
Name: "config",
Usage: "Print the connection config for machine",
Description: "Argument is a machine name.",
Action: runCommand(cmdConfig),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "swarm",
Usage: "Display the Swarm config instead of the Docker daemon",
},
},
},
{
Flags: sharedCreateFlags,
Name: "create",
Usage: "Create a machine",
Description: fmt.Sprintf("Run '%s create --driver name' to include the create flags for that driver in the help text.", os.Args[0]),
Action: runCommand(cmdCreateOuter),
SkipFlagParsing: true,
},
{
Name: "env",
Usage: "Display the commands to set up the environment for the Docker client",
Description: "Argument is a machine name.",
Action: runCommand(cmdEnv),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "swarm",
Usage: "Display the Swarm config instead of the Docker daemon",
},
cli.StringFlag{
Name: "shell",
Usage: "Force environment to be configured for a specified shell: [fish, cmd, powershell], default is auto-detect",
},
cli.BoolFlag{
Name: "unset, u",
Usage: "Unset variables instead of setting them",
},
cli.BoolFlag{
Name: "no-proxy",
Usage: "Add machine IP to NO_PROXY environment variable",
},
},
},
{
Name: "inspect",
Usage: "Inspect information about a machine",
Description: "Argument is a machine name.",
Action: runCommand(cmdInspect),
Flags: []cli.Flag{
cli.StringFlag{
Name: "format, f",
Usage: "Format the output using the given go template.",
Value: "",
},
},
},
{
Name: "ip",
Usage: "Get the IP address of a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdIP),
},
{
Name: "kill",
Usage: "Kill a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdKill),
},
{
Name: "ls",
Usage: "List machines",
Action: runCommand(cmdLs),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "quiet, q",
Usage: "Enable quiet mode",
},
cli.StringSliceFlag{
Name: "filter",
Usage: "Filter output based on conditions provided",
Value: &cli.StringSlice{},
},
cli.IntFlag{
Name: "timeout, t",
Usage: fmt.Sprintf("Timeout in seconds, default to %s", stateTimeoutDuration),
Value: lsDefaultTimeout,
},
cli.StringFlag{
Name: "format, f",
Usage: "Pretty-print machines using a Go template",
},
},
},
{
Name: "provision",
Usage: "Re-provision existing machines",
Action: runCommand(cmdProvision),
},
{
Name: "regenerate-certs",
Usage: "Regenerate TLS Certificates for a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdRegenerateCerts),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "force, f",
Usage: "Force rebuild and do not prompt",
},
},
},
{
Name: "restart",
Usage: "Restart a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdRestart),
},
{
Flags: []cli.Flag{
cli.BoolFlag{
Name: "force, f",
Usage: "Remove local configuration even if machine cannot be removed, also implies an automatic yes (`-y`)",
},
cli.BoolFlag{
Name: "y",
Usage: "Assumes automatic yes to proceed with remove, without prompting further user confirmation",
},
},
Name: "rm",
Usage: "Remove a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdRm),
},
{
Name: "ssh",
Usage: "Log into or run a command on a machine with SSH.",
Description: "Arguments are [machine-name] [command]",
Action: runCommand(cmdSSH),
SkipFlagParsing: true,
},
{
Name: "scp",
Usage: "Copy files between machines",
Description: "Arguments are [machine:][path] [machine:][path].",
Action: runCommand(cmdScp),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "Copy files recursively (required to copy directories)",
},
},
},
{
Name: "start",
Usage: "Start a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdStart),
},
{
Name: "status",
Usage: "Get the status of a machine",
Description: "Argument is a machine name.",
Action: runCommand(cmdStatus),
},
{
Name: "stop",
Usage: "Stop a machine",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdStop),
},
{
Name: "upgrade",
Usage: "Upgrade a machine to the latest version of Docker",
Description: "Argument(s) are one or more machine names.",
Action: runCommand(cmdUpgrade),
},
{
Name: "url",
Usage: "Get the URL of a machine",
Description: "Argument is a machine name.",
Action: runCommand(cmdURL),
},
{
Name: "version",
Usage: "Show the Docker Machine version or a machine docker version",
Action: runCommand(cmdVersion),
},
}
func printIP(h *host.Host) func() error {
return func() error {
ip, err := h.Driver.GetIP()
if err != nil {
return fmt.Errorf("Error getting IP address: %s", err)
}
fmt.Println(ip)
return nil
}
}
// machineCommand maps the command name to the corresponding machine command.
// We run commands concurrently and communicate back an error if there was one.
func machineCommand(actionName string, host *host.Host, errorChan chan<- error) {
// TODO: These actions should have their own type.
commands := map[string](func() error){
"configureAuth": host.ConfigureAuth,
"start": host.Start,
"stop": host.Stop,
"restart": host.Restart,
"kill": host.Kill,
"upgrade": host.Upgrade,
"ip": printIP(host),
"provision": host.Provision,
}
log.Debugf("command=%s machine=%s", actionName, host.Name)
errorChan <- commands[actionName]()
}
// runActionForeachMachine will run the command across multiple machines
func runActionForeachMachine(actionName string, machines []*host.Host) []error {
var (
numConcurrentActions = 0
errorChan = make(chan error)
errs = []error{}
)
for _, machine := range machines {
numConcurrentActions++
go machineCommand(actionName, machine, errorChan)
}
// TODO: We should probably only do 5-10 of these
// at a time, since otherwise cloud providers might
// rate limit us.
for i := 0; i < numConcurrentActions; i++ {
if err := <-errorChan; err != nil {
errs = append(errs, err)
}
}
close(errorChan)
return errs
}
func consolidateErrs(errs []error) error {
finalErr := ""
for _, err := range errs {
finalErr = fmt.Sprintf("%s\n%s", finalErr, err)
}
return errors.New(strings.TrimSpace(finalErr))
}