forked from docker/machine
/
commands.go
683 lines (614 loc) · 17 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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
package commands
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"github.com/codegangsta/cli"
"github.com/skarademir/naturalsort"
"github.com/docker/machine/drivers"
_ "github.com/docker/machine/drivers/amazonec2"
_ "github.com/docker/machine/drivers/azure"
_ "github.com/docker/machine/drivers/digitalocean"
_ "github.com/docker/machine/drivers/exoscale"
_ "github.com/docker/machine/drivers/generic"
_ "github.com/docker/machine/drivers/google"
_ "github.com/docker/machine/drivers/hyperv"
_ "github.com/docker/machine/drivers/none"
_ "github.com/docker/machine/drivers/openstack"
_ "github.com/docker/machine/drivers/rackspace"
_ "github.com/docker/machine/drivers/softlayer"
_ "github.com/docker/machine/drivers/virtualbox"
_ "github.com/docker/machine/drivers/vmwarefusion"
_ "github.com/docker/machine/drivers/vmwarevcloudair"
_ "github.com/docker/machine/drivers/vmwarevsphere"
"github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/auth"
"github.com/docker/machine/libmachine/swarm"
"github.com/docker/machine/log"
"github.com/docker/machine/utils"
)
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.")
)
type machineConfig struct {
machineName string
machineDir string
machineUrl string
clientKeyPath string
serverCertPath string
clientCertPath string
caCertPath string
caKeyPath string
serverKeyPath string
AuthOptions auth.AuthOptions
SwarmOptions swarm.SwarmOptions
}
func sortHostListItemsByName(items []libmachine.HostListItem) {
m := make(map[string]libmachine.HostListItem, len(items))
s := make([]string, len(items))
for i, v := range items {
name := strings.ToLower(v.Name)
m[name] = v
s[i] = name
}
sort.Sort(naturalsort.NaturalSort(s))
for i, v := range s {
items[i] = m[v]
}
}
func confirmInput(msg string) bool {
fmt.Printf("%s (y/n): ", msg)
var resp string
_, err := fmt.Scanln(&resp)
if err != nil {
log.Fatal(err)
}
if strings.Index(strings.ToLower(resp), "y") == 0 {
return true
}
return false
}
func newProvider(store libmachine.Store) (*libmachine.Provider, error) {
return libmachine.New(store)
}
func getMachineDir(rootPath string) string {
return filepath.Join(rootPath, "machines")
}
func getDefaultStore(rootPath, caCertPath, privateKeyPath string) (libmachine.Store, error) {
return libmachine.NewFilestore(
rootPath,
caCertPath,
privateKeyPath,
), nil
}
func setupCertificates(caCertPath, caKeyPath, clientCertPath, clientKeyPath string) error {
org := utils.GetUsername()
bits := 2048
if _, err := os.Stat(utils.GetMachineCertDir()); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(utils.GetMachineCertDir(), 0700); err != nil {
log.Fatalf("Error creating machine config dir: %s", err)
}
} else {
log.Fatal(err)
}
}
if _, err := os.Stat(caCertPath); os.IsNotExist(err) {
log.Infof("Creating CA: %s", caCertPath)
// check if the key path exists; if so, error
if _, err := os.Stat(caKeyPath); err == nil {
log.Fatalf("The CA key already exists. Please remove it or specify a different key/cert.")
}
if err := utils.GenerateCACertificate(caCertPath, caKeyPath, org, bits); err != nil {
log.Infof("Error generating CA certificate: %s", err)
}
}
if _, err := os.Stat(clientCertPath); os.IsNotExist(err) {
log.Infof("Creating client certificate: %s", clientCertPath)
if _, err := os.Stat(utils.GetMachineCertDir()); err != nil {
if os.IsNotExist(err) {
if err := os.Mkdir(utils.GetMachineCertDir(), 0700); err != nil {
log.Fatalf("Error creating machine client cert dir: %s", err)
}
} else {
log.Fatal(err)
}
}
// check if the key path exists; if so, error
if _, err := os.Stat(clientKeyPath); err == nil {
log.Fatalf("The client key already exists. Please remove it or specify a different key/cert.")
}
if err := utils.GenerateCert([]string{""}, clientCertPath, clientKeyPath, caCertPath, caKeyPath, org, bits); err != nil {
log.Fatalf("Error generating client certificate: %s", err)
}
}
return nil
}
var sharedCreateFlags = []cli.Flag{
cli.StringFlag{
Name: "driver, d",
Usage: fmt.Sprintf(
"Driver to create machine with. Available drivers: %s",
strings.Join(drivers.GetDriverNames(), ", "),
),
Value: "none",
},
cli.StringFlag{
Name: "engine-install-url",
Usage: "Custom URL to use for engine installation",
Value: "https://get.docker.com",
EnvVar: "MACHINE_DOCKER_INSTALL_URL",
},
cli.StringSliceFlag{
Name: "engine-opt",
Usage: "Specify arbitrary flags to include with the created engine in the form flag=value",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "engine-insecure-registry",
Usage: "Specify insecure registries to allow with the created engine",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "engine-registry-mirror",
Usage: "Specify registry mirrors to use",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "engine-label",
Usage: "Specify labels for the created engine",
Value: &cli.StringSlice{},
},
cli.StringFlag{
Name: "engine-storage-driver",
Usage: "Specify a storage driver to use with the engine",
},
cli.StringSliceFlag{
Name: "engine-env",
Usage: "Specify environment variables to set in the engine",
Value: &cli.StringSlice{},
},
cli.BoolFlag{
Name: "swarm",
Usage: "Configure Machine with Swarm",
},
cli.StringFlag{
Name: "swarm-image",
Usage: "Specify Docker image to use for Swarm",
Value: "swarm:latest",
EnvVar: "MACHINE_SWARM_IMAGE",
},
cli.BoolFlag{
Name: "swarm-master",
Usage: "Configure Machine to be a Swarm master",
},
cli.StringFlag{
Name: "swarm-discovery",
Usage: "Discovery service to use with Swarm",
Value: "",
},
cli.StringFlag{
Name: "swarm-strategy",
Usage: "Define a default scheduling strategy for Swarm",
Value: "spread",
},
cli.StringSliceFlag{
Name: "swarm-opt",
Usage: "Define arbitrary flags for swarm",
Value: &cli.StringSlice{},
},
cli.StringFlag{
Name: "swarm-host",
Usage: "ip/socket to listen on for Swarm master",
Value: "tcp://0.0.0.0:3376",
},
cli.StringFlag{
Name: "swarm-addr",
Usage: "addr to advertise for Swarm (default: detect and use the machine IP)",
Value: "",
},
}
var Commands = []cli.Command{
{
Name: "active",
Usage: "Print which machine is active",
Action: cmdActive,
},
{
Name: "config",
Usage: "Print the connection config for machine",
Description: "Argument is a machine name.",
Action: cmdConfig,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "swarm",
Usage: "Display the Swarm config instead of the Docker daemon",
},
},
},
{
Flags: append(
drivers.GetCreateFlags(),
sharedCreateFlags...,
),
Name: "create",
Usage: "Create a machine",
Action: cmdCreate,
},
{
Name: "env",
Usage: "Display the commands to set up the environment for the Docker client",
Description: "Argument is a machine name.",
Action: 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",
},
},
},
{
Name: "inspect",
Usage: "Inspect information about a machine",
Description: "Argument is a machine name.",
Action: 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: cmdIp,
},
{
Name: "kill",
Usage: "Kill a machine",
Description: "Argument(s) are one or more machine names.",
Action: 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: cmdLs,
},
{
Name: "regenerate-certs",
Usage: "Regenerate TLS Certificates for a machine",
Description: "Argument(s) are one or more machine names.",
Action: 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: 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: cmdRm,
},
{
Name: "ssh",
Usage: "Log into or run a command on a machine with SSH.",
Description: "Arguments are [machine-name] [command]",
Action: cmdSsh,
},
{
Name: "scp",
Usage: "Copy files between machines",
Description: "Arguments are [machine:][path] [machine:][path].",
Action: 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: cmdStart,
},
{
Name: "status",
Usage: "Get the status of a machine",
Description: "Argument is a machine name.",
Action: cmdStatus,
},
{
Name: "stop",
Usage: "Stop a machine",
Description: "Argument(s) are one or more machine names.",
Action: cmdStop,
},
{
Name: "upgrade",
Usage: "Upgrade a machine to the latest version of Docker",
Description: "Argument(s) are one or more machine names.",
Action: cmdUpgrade,
},
{
Name: "url",
Usage: "Get the URL of a machine",
Description: "Argument is a machine name.",
Action: cmdUrl,
},
}
// 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 *libmachine.Host, errorChan chan<- error) {
commands := map[string](func() error){
"configureAuth": host.ConfigureAuth,
"start": host.Start,
"stop": host.Stop,
"restart": host.Restart,
"kill": host.Kill,
"upgrade": host.Upgrade,
"ip": host.PrintIP,
}
log.Debugf("command=%s machine=%s", actionName, host.Name)
if err := commands[actionName](); err != nil {
errorChan <- err
return
}
errorChan <- nil
}
// runActionForeachMachine will run the command across multiple machines
func runActionForeachMachine(actionName string, machines []*libmachine.Host) {
var (
numConcurrentActions = 0
serialMachines = []*libmachine.Host{}
errorChan = make(chan 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 {
log.Errorln(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 {
log.Errorln(err)
}
}
close(errorChan)
}
func runActionWithContext(actionName string, c *cli.Context) error {
machines, err := getHosts(c)
if err != nil {
return err
}
if len(machines) == 0 {
log.Fatal(ErrNoMachineSpecified)
}
runActionForeachMachine(actionName, machines)
return nil
}
func getHosts(c *cli.Context) ([]*libmachine.Host, error) {
machines := []*libmachine.Host{}
for _, n := range c.Args() {
machine, err := loadMachine(n, c)
if err != nil {
return nil, err
}
machines = append(machines, machine)
}
return machines, nil
}
func loadMachine(name string, c *cli.Context) (*libmachine.Host, error) {
certInfo := getCertPathInfo(c)
defaultStore, err := getDefaultStore(
c.GlobalString("storage-path"),
certInfo.CaCertPath,
certInfo.CaKeyPath,
)
if err != nil {
log.Fatal(err)
}
provider, err := newProvider(defaultStore)
if err != nil {
log.Fatal(err)
}
host, err := provider.Get(name)
if err != nil {
return nil, err
}
return host, nil
}
func getHost(c *cli.Context) *libmachine.Host {
name := c.Args().First()
defaultStore, err := getDefaultStore(
c.GlobalString("storage-path"),
c.GlobalString("tls-ca-cert"),
c.GlobalString("tls-ca-key"),
)
if err != nil {
log.Fatal(err)
}
provider, err := newProvider(defaultStore)
if err != nil {
log.Fatal(err)
}
host, err := provider.Get(name)
if err != nil {
log.Fatalf("unable to load host: %v", err)
}
return host
}
func getDefaultProvider(c *cli.Context) *libmachine.Provider {
certInfo := getCertPathInfo(c)
defaultStore, err := getDefaultStore(
c.GlobalString("storage-path"),
certInfo.CaCertPath,
certInfo.CaKeyPath,
)
if err != nil {
log.Fatal(err)
}
provider, err := newProvider(defaultStore)
if err != nil {
log.Fatal(err)
}
return provider
}
func getMachineConfig(c *cli.Context) (*machineConfig, error) {
name := c.Args().First()
certInfo := getCertPathInfo(c)
defaultStore, err := getDefaultStore(
c.GlobalString("storage-path"),
certInfo.CaCertPath,
certInfo.CaKeyPath,
)
if err != nil {
log.Fatal(err)
}
provider, err := newProvider(defaultStore)
if err != nil {
log.Fatal(err)
}
m, err := provider.Get(name)
if err != nil {
return nil, err
}
machineDir := filepath.Join(utils.GetMachineDir(), m.Name)
caCert := filepath.Join(machineDir, "ca.pem")
caKey := filepath.Join(utils.GetMachineCertDir(), "ca-key.pem")
clientCert := filepath.Join(machineDir, "cert.pem")
clientKey := filepath.Join(machineDir, "key.pem")
serverCert := filepath.Join(machineDir, "server.pem")
serverKey := filepath.Join(machineDir, "server-key.pem")
machineUrl, err := m.GetURL()
if err != nil {
if err == drivers.ErrHostIsNotRunning {
machineUrl = ""
} else {
return nil, fmt.Errorf("Unexpected error getting machine url: %s", err)
}
}
return &machineConfig{
machineName: name,
machineDir: machineDir,
machineUrl: machineUrl,
clientKeyPath: clientKey,
clientCertPath: clientCert,
serverCertPath: serverCert,
caKeyPath: caKey,
caCertPath: caCert,
serverKeyPath: serverKey,
AuthOptions: *m.HostOptions.AuthOptions,
SwarmOptions: *m.HostOptions.SwarmOptions,
}, nil
}
// getCertPaths 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 getCertPathInfo(c *cli.Context) libmachine.CertPathInfo {
// setup cert paths
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(utils.GetMachineCertDir(), "ca.pem")
}
if caKeyPath == "" {
caKeyPath = filepath.Join(utils.GetMachineCertDir(), "ca-key.pem")
}
if clientCertPath == "" {
clientCertPath = filepath.Join(utils.GetMachineCertDir(), "cert.pem")
}
if clientKeyPath == "" {
clientKeyPath = filepath.Join(utils.GetMachineCertDir(), "key.pem")
}
return libmachine.CertPathInfo{
CaCertPath: caCertPath,
CaKeyPath: caKeyPath,
ClientCertPath: clientCertPath,
ClientKeyPath: clientKeyPath,
}
}
func detectShell() (string, error) {
// check for windows env and not bash (i.e. msysgit, etc)
// the SHELL env var is not set for processes in msysgit; we check
// for TERM instead
if runtime.GOOS == "windows" && os.Getenv("TERM") != "cygwin" {
log.Printf("On Windows, please specify either 'cmd' or 'powershell' with the --shell flag.\n\n")
return "", ErrUnknownShell
}
// attempt to get the SHELL env var
shell := filepath.Base(os.Getenv("SHELL"))
log.Debugf("shell: %s", shell)
if shell == "" {
return "", ErrUnknownShell
}
return shell, nil
}