-
Notifications
You must be signed in to change notification settings - Fork 26
/
commands.go
506 lines (448 loc) · 13.1 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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
package commands
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/docker/machine/cli"
"github.com/docker/machine/commands/mcndirs"
"github.com/docker/machine/drivers/errdriver"
"github.com/docker/machine/libmachine/cert"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/drivers/plugin/localbinary"
"github.com/docker/machine/libmachine/drivers/rpc"
"github.com/docker/machine/libmachine/host"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/persist"
)
var (
ErrUnknownShell = errors.New("Error: Unknown shell")
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")
)
func newPluginDriver(driverName string, rawContent []byte) (drivers.Driver, error) {
d, err := rpcdriver.NewRpcClientDriver(rawContent, driverName)
if err != nil {
// Not being able to find a driver binary is a "known error"
if _, ok := err.(localbinary.ErrPluginBinaryNotFound); ok {
return errdriver.NewDriver(driverName), nil
}
return nil, err
}
return d, nil
}
func fatalOnError(command func(context *cli.Context) error) func(context *cli.Context) {
return func(context *cli.Context) {
if err := command(context); err != nil {
log.Fatal(err)
}
}
}
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
}
func getStore(c *cli.Context) persist.Store {
certInfo := getCertPathInfoFromContext(c)
return &persist.Filestore{
Path: c.GlobalString("storage-path"),
CaCertPath: certInfo.CaCertPath,
CaPrivateKeyPath: certInfo.CaPrivateKeyPath,
}
}
func listHosts(store persist.Store) ([]*host.Host, error) {
cliHosts := []*host.Host{}
hosts, err := store.List()
if err != nil {
return nil, fmt.Errorf("Error attempting to list hosts from store: %s", err)
}
for _, h := range hosts {
d, err := newPluginDriver(h.DriverName, h.RawDriver)
if err != nil {
return nil, fmt.Errorf("Error attempting to invoke binary for plugin '%s': %s", h.DriverName, err)
}
h.Driver = d
cliHosts = append(cliHosts, h)
}
return cliHosts, nil
}
func loadHost(store persist.Store, hostName string) (*host.Host, error) {
h, err := store.Load(hostName)
if err != nil {
return nil, fmt.Errorf("Loading host from store failed: %s", err)
}
d, err := newPluginDriver(h.DriverName, h.RawDriver)
if err != nil {
return nil, fmt.Errorf("Error attempting to invoke binary for plugin: %s", err)
}
h.Driver = d
return h, nil
}
func saveHost(store persist.Store, h *host.Host) error {
if err := store.Save(h); err != nil {
return fmt.Errorf("Error attempting to save host to store: %s", err)
}
return nil
}
func getFirstArgHost(c *cli.Context) (*host.Host, error) {
store := getStore(c)
hostName := c.Args().First()
exists, err := store.Exists(hostName)
if err != nil {
return nil, fmt.Errorf("Error checking if host %q exists: %s", hostName, err)
}
if !exists {
return nil, fmt.Errorf("Host %q does not exist", hostName)
}
h, err := loadHost(store, hostName)
if err != nil {
// I guess I feel OK with bailing here since if we can't get
// the host reliably we're definitely not going to be able to
// do anything else interesting, but also this premature exit
// feels wrong to me. Let's revisit it later.
return nil, fmt.Errorf("Error trying to get host %q: %s", hostName, err)
}
return h, nil
}
func getHostsFromContext(c *cli.Context) ([]*host.Host, error) {
store := getStore(c)
hosts := []*host.Host{}
for _, hostName := range c.Args() {
h, err := loadHost(store, hostName)
if err != nil {
return nil, fmt.Errorf("Could not load host %q: %s", hostName, err)
}
hosts = append(hosts, h)
}
return hosts, nil
}
var Commands = []cli.Command{
{
Name: "active",
Usage: "Print which machine is active",
Action: fatalOnError(cmdActive),
},
{
Name: "config",
Usage: "Print the connection config for machine",
Description: "Argument is a machine name.",
Action: fatalOnError(cmdConfig),
Flags: []cli.Flag{
cli.BoolFlag{
Name: "swarm",
Usage: "Display the Swarm config instead of the Docker daemon",
},
},
},
{
Flags: sharedCreateFlags,
Name: "create",
Usage: fmt.Sprintf("Create a machine.\n\nRun '%s create --driver name' to include the create flags for that driver in the help text.", os.Args[0]),
Action: fatalOnError(cmdCreateOuter),
SkipFlagParsing: true,
},
{
Name: "deploy",
Usage: "Deploy a specific configuration to the machine",
Description: "Arguments are a machine name and configuration",
Action: fatalOnError(cmdDeploy),
Flags: []cli.Flag{
cli.StringFlag{
Name: "machine",
Usage: "The target machine of the deployment",
},
cli.StringFlag{
Name: "path",
Usage: "One of dns|helm|dashboard",
},
},
},
{
Name: "env",
Usage: "Display the commands to set up the environment for the Docker client",
Description: "Argument is a machine name.",
Action: fatalOnError(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 specified shell",
},
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: fatalOnError(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: fatalOnError(cmdIp),
},
{
Name: "kill",
Usage: "Kill a machine",
Description: "Argument(s) are one or more machine names.",
Action: fatalOnError(cmdKill),
},
{
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{},
},
},
Name: "ls",
Usage: "List machines",
Action: fatalOnError(cmdLs),
},
{
Name: "regenerate-certs",
Usage: "Regenerate TLS Certificates for a machine",
Description: "Argument(s) are one or more machine names.",
Action: fatalOnError(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: fatalOnError(cmdRestart),
},
{
Flags: []cli.Flag{
cli.BoolFlag{
Name: "force, f",
Usage: "Remove local configuration even if machine cannot be removed",
},
},
Name: "rm",
Usage: "Remove a machine",
Description: "Argument(s) are one or more machine names.",
Action: fatalOnError(cmdRm),
},
{
Name: "ssh",
Usage: "Log into or run a command on a machine with SSH.",
Description: "Arguments are [machine-name] [command]",
Action: fatalOnError(cmdSsh),
SkipFlagParsing: true,
},
{
Name: "scp",
Usage: "Copy files between machines",
Description: "Arguments are [machine:][path] [machine:][path].",
Action: fatalOnError(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: fatalOnError(cmdStart),
},
{
Name: "status",
Usage: "Get the status of a machine",
Description: "Argument is a machine name.",
Action: fatalOnError(cmdStatus),
},
{
Name: "stop",
Usage: "Stop a machine",
Description: "Argument(s) are one or more machine names.",
Action: fatalOnError(cmdStop),
},
{
Name: "upgrade",
Usage: "Upgrade a machine to the latest version of Docker",
Description: "Argument(s) are one or more machine names.",
Action: fatalOnError(cmdUpgrade),
},
{
Name: "url",
Usage: "Get the URL of a machine",
Description: "Argument is a machine name.",
Action: fatalOnError(cmdUrl),
},
}
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),
}
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
serialMachines = []*host.Host{}
errorChan = make(chan error)
errs = []error{}
)
for _, machine := range machines {
// Virtualbox is temperamental about doing things concurrently,
// so we schedule the actions in a "queue" to be executed serially
// after the concurrent actions are scheduled.
switch machine.DriverName {
case "virtualbox":
machine := machine
serialMachines = append(serialMachines, machine)
default:
numConcurrentActions++
go machineCommand(actionName, machine, errorChan)
}
}
// While the concurrent actions are running,
// do the serial actions. As the name implies,
// these run one at a time.
for _, machine := range serialMachines {
serialChan := make(chan error)
go machineCommand(actionName, machine, serialChan)
if err := <-serialChan; err != nil {
errs = append(errs, err)
}
close(serialChan)
}
// 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))
}
func runActionWithContext(actionName string, c *cli.Context) error {
store := getStore(c)
hosts, err := getHostsFromContext(c)
if err != nil {
return err
}
if len(hosts) == 0 {
return ErrNoMachineSpecified
}
if errs := runActionForeachMachine(actionName, hosts); len(errs) > 0 {
return consolidateErrs(errs)
}
for _, h := range hosts {
if err := saveHost(store, h); err != nil {
return fmt.Errorf("Error saving host to store: %s", err)
}
}
return nil
}
// Returns the cert paths.
// codegangsta/cli will not set the cert paths if the storage-path is set to
// something different so we cannot use the paths in the global options. le
// sigh.
func getCertPathInfoFromContext(c *cli.Context) cert.CertPathInfo {
caCertPath := c.GlobalString("tls-ca-cert")
caKeyPath := c.GlobalString("tls-ca-key")
clientCertPath := c.GlobalString("tls-client-cert")
clientKeyPath := c.GlobalString("tls-client-key")
if caCertPath == "" {
caCertPath = filepath.Join(mcndirs.GetMachineCertDir(), "ca.pem")
}
if caKeyPath == "" {
caKeyPath = filepath.Join(mcndirs.GetMachineCertDir(), "ca-key.pem")
}
if clientCertPath == "" {
clientCertPath = filepath.Join(mcndirs.GetMachineCertDir(), "cert.pem")
}
if clientKeyPath == "" {
clientKeyPath = filepath.Join(mcndirs.GetMachineCertDir(), "key.pem")
}
return cert.CertPathInfo{
CaCertPath: caCertPath,
CaPrivateKeyPath: caKeyPath,
ClientCertPath: clientCertPath,
ClientKeyPath: clientKeyPath,
}
}
func detectShell() (string, error) {
// attempt to get the SHELL env var
shell := filepath.Base(os.Getenv("SHELL"))
log.Debugf("shell: %s", shell)
if shell == "" {
// check for windows env and not bash (i.e. msysgit, etc)
if runtime.GOOS == "windows" {
log.Printf("On Windows, please specify either 'cmd' or 'powershell' with the --shell flag.\n\n")
}
return "", ErrUnknownShell
}
return shell, nil
}