forked from docker/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.go
465 lines (415 loc) · 13 KB
/
create.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
package commands
import (
"encoding/json"
"flag"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"errors"
"time"
"github.com/codegangsta/cli"
"github.com/docker/machine/commands/mcndirs"
"github.com/docker/machine/libmachine"
"github.com/docker/machine/libmachine/auth"
"github.com/docker/machine/libmachine/crashreport"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/drivers/rpc"
"github.com/docker/machine/libmachine/engine"
"github.com/docker/machine/libmachine/host"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnerror"
"github.com/docker/machine/libmachine/mcnflag"
"github.com/docker/machine/libmachine/swarm"
)
var (
errNoMachineName = errors.New("Error: No machine name specified")
)
var (
SharedCreateFlags = []cli.Flag{
cli.StringFlag{
Name: "driver, d",
Usage: fmt.Sprintf(
"Driver to create machine with.",
),
Value: "none",
EnvVar: "MACHINE_DRIVER",
},
cli.StringFlag{
Name: "engine-install-url",
Usage: "Custom URL to use for engine installation",
Value: drivers.DefaultEngineInstallURL,
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{},
EnvVar: "ENGINE_REGISTRY_MIRROR",
},
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 to join a Swarm cluster",
},
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 master",
Value: &cli.StringSlice{},
},
cli.StringSliceFlag{
Name: "swarm-join-opt",
Usage: "Define arbitrary flags for Swarm join",
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: "",
},
cli.BoolFlag{
Name: "swarm-experimental",
Usage: "Enable Swarm experimental features",
},
cli.StringSliceFlag{
Name: "tls-san",
Usage: "Support extra SANs for TLS certs",
Value: &cli.StringSlice{},
},
}
)
func cmdCreateInner(c CommandLine, api libmachine.API) error {
if len(c.Args()) > 1 {
return fmt.Errorf("Invalid command line. Found extra arguments %v", c.Args()[1:])
}
name := c.Args().First()
if name == "" {
c.ShowHelp()
return errNoMachineName
}
validName := host.ValidateHostName(name)
if !validName {
return fmt.Errorf("Error creating machine: %s", mcnerror.ErrInvalidHostname)
}
if err := validateSwarmDiscovery(c.String("swarm-discovery")); err != nil {
return fmt.Errorf("Error parsing swarm discovery: %s", err)
}
// TODO: Fix hacky JSON solution
rawDriver, err := json.Marshal(&drivers.BaseDriver{
MachineName: name,
StorePath: c.GlobalString("storage-path"),
})
if err != nil {
return fmt.Errorf("Error attempting to marshal bare driver data: %s", err)
}
driverName := c.String("driver")
h, err := api.NewHost(driverName, rawDriver)
if err != nil {
return fmt.Errorf("Error getting new host: %s", err)
}
h.HostOptions = &host.Options{
AuthOptions: &auth.Options{
CertDir: mcndirs.GetMachineCertDir(),
CaCertPath: tlsPath(c, "tls-ca-cert", "ca.pem"),
CaPrivateKeyPath: tlsPath(c, "tls-ca-key", "ca-key.pem"),
ClientCertPath: tlsPath(c, "tls-client-cert", "cert.pem"),
ClientKeyPath: tlsPath(c, "tls-client-key", "key.pem"),
ServerCertPath: filepath.Join(mcndirs.GetMachineDir(), name, "server.pem"),
ServerKeyPath: filepath.Join(mcndirs.GetMachineDir(), name, "server-key.pem"),
StorePath: filepath.Join(mcndirs.GetMachineDir(), name),
ServerCertSANs: c.StringSlice("tls-san"),
},
EngineOptions: &engine.Options{
ArbitraryFlags: c.StringSlice("engine-opt"),
Env: c.StringSlice("engine-env"),
InsecureRegistry: c.StringSlice("engine-insecure-registry"),
Labels: c.StringSlice("engine-label"),
RegistryMirror: c.StringSlice("engine-registry-mirror"),
StorageDriver: c.String("engine-storage-driver"),
TLSVerify: true,
InstallURL: c.String("engine-install-url"),
},
SwarmOptions: &swarm.Options{
IsSwarm: c.Bool("swarm") || c.Bool("swarm-master"),
Image: c.String("swarm-image"),
Agent: c.Bool("swarm"),
Master: c.Bool("swarm-master"),
Discovery: c.String("swarm-discovery"),
Address: c.String("swarm-addr"),
Host: c.String("swarm-host"),
Strategy: c.String("swarm-strategy"),
ArbitraryFlags: c.StringSlice("swarm-opt"),
ArbitraryJoinFlags: c.StringSlice("swarm-join-opt"),
IsExperimental: c.Bool("swarm-experimental"),
},
}
exists, err := api.Exists(h.Name)
if err != nil {
return fmt.Errorf("Error checking if host exists: %s", err)
}
if exists {
return mcnerror.ErrHostAlreadyExists{
Name: h.Name,
}
}
// driverOpts is the actual data we send over the wire to set the
// driver parameters (an interface fulfilling drivers.DriverOptions,
// concrete type rpcdriver.RpcFlags).
mcnFlags := h.Driver.GetCreateFlags()
driverOpts := getDriverOpts(c, mcnFlags)
if err := h.Driver.SetConfigFromFlags(driverOpts); err != nil {
return fmt.Errorf("Error setting machine configuration from flags provided: %s", err)
}
if err := api.Create(h); err != nil {
// Wait for all the logs to reach the client
time.Sleep(2 * time.Second)
vBoxLog := ""
if h.DriverName == "virtualbox" {
vBoxLog = filepath.Join(api.GetMachinesDir(), h.Name, h.Name, "Logs", "VBox.log")
}
return crashreport.CrashError{
Cause: err,
Command: "Create",
Context: "api.performCreate",
DriverName: h.DriverName,
LogFilePath: vBoxLog,
}
}
if err := api.Save(h); err != nil {
return fmt.Errorf("Error attempting to save store: %s", err)
}
log.Infof("To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: %s env %s", os.Args[0], name)
return nil
}
// The following function is needed because the CLI acrobatics that we're doing
// (with having an "outer" and "inner" function each with their own custom
// settings and flag parsing needs) are not well supported by codegangsta/cli.
//
// Instead of trying to make a convoluted series of flag parsing and relying on
// codegangsta/cli internals work well, we simply read the flags we're
// interested in from the outer function into module-level variables, and then
// use them from the "inner" function.
//
// I'm not very pleased about this, but it seems to be the only decent
// compromise without drastically modifying codegangsta/cli internals or our
// own CLI.
func flagHackLookup(flagName string) string {
// e.g. "-d" for "--driver"
flagPrefix := flagName[1:3]
// TODO: Should we support -flag-name (single hyphen) syntax as well?
for i, arg := range os.Args {
if strings.Contains(arg, flagPrefix) {
// format '--driver foo' or '-d foo'
if arg == flagPrefix || arg == flagName {
if i+1 < len(os.Args) {
return os.Args[i+1]
}
}
// format '--driver=foo' or '-d=foo'
if strings.HasPrefix(arg, flagPrefix+"=") || strings.HasPrefix(arg, flagName+"=") {
return strings.Split(arg, "=")[1]
}
}
}
return ""
}
func cmdCreateOuter(c CommandLine, api libmachine.API) error {
const (
flagLookupMachineName = "flag-lookup"
)
// We didn't recognize the driver name.
driverName := flagHackLookup("--driver")
if driverName == "" {
//TODO: Check Environment have to include flagHackLookup function.
driverName = os.Getenv("MACHINE_DRIVER")
if driverName == "" {
c.ShowHelp()
return nil // ?
}
}
// TODO: Fix hacky JSON solution
rawDriver, err := json.Marshal(&drivers.BaseDriver{
MachineName: flagLookupMachineName,
})
if err != nil {
return fmt.Errorf("Error attempting to marshal bare driver data: %s", err)
}
h, err := api.NewHost(driverName, rawDriver)
if err != nil {
return err
}
// TODO: So much flag manipulation and voodoo here, it seems to be
// asking for trouble.
//
// mcnFlags is the data we get back over the wire (type mcnflag.Flag)
// to indicate which parameters are available.
mcnFlags := h.Driver.GetCreateFlags()
// This bit will actually make "create" display the correct flags based
// on the requested driver.
cliFlags, err := convertMcnFlagsToCliFlags(mcnFlags)
if err != nil {
return fmt.Errorf("Error trying to convert provided driver flags to cli flags: %s", err)
}
for i := range c.Application().Commands {
cmd := &c.Application().Commands[i]
if cmd.HasName("create") {
cmd = addDriverFlagsToCommand(cliFlags, cmd)
}
}
return c.Application().Run(os.Args)
}
func getDriverOpts(c CommandLine, mcnflags []mcnflag.Flag) drivers.DriverOptions {
// TODO: This function is pretty damn YOLO and would benefit from some
// sanity checking around types and assertions.
//
// But, we need it so that we can actually send the flags for creating
// a machine over the wire (cli.Context is a no go since there is so
// much stuff in it).
driverOpts := rpcdriver.RPCFlags{
Values: make(map[string]interface{}),
}
for _, f := range mcnflags {
driverOpts.Values[f.String()] = f.Default()
// Hardcoded logic for boolean... :(
if f.Default() == nil {
driverOpts.Values[f.String()] = false
}
}
for _, name := range c.FlagNames() {
getter, ok := c.Generic(name).(flag.Getter)
if ok {
driverOpts.Values[name] = getter.Get()
} else {
// TODO: This is pretty hacky. StringSlice is the only
// type so far we have to worry about which is not a
// Getter, though.
if c.IsSet(name) {
driverOpts.Values[name] = c.StringSlice(name)
}
}
}
return driverOpts
}
func convertMcnFlagsToCliFlags(mcnFlags []mcnflag.Flag) ([]cli.Flag, error) {
cliFlags := []cli.Flag{}
for _, f := range mcnFlags {
switch t := f.(type) {
// TODO: It seems pretty wrong to just default "nil" to this,
// but cli.BoolFlag doesn't have a "Value" field (false is
// always the default)
case *mcnflag.BoolFlag:
f := f.(*mcnflag.BoolFlag)
cliFlags = append(cliFlags, cli.BoolFlag{
Name: f.Name,
EnvVar: f.EnvVar,
Usage: f.Usage,
})
case *mcnflag.IntFlag:
f := f.(*mcnflag.IntFlag)
cliFlags = append(cliFlags, cli.IntFlag{
Name: f.Name,
EnvVar: f.EnvVar,
Usage: f.Usage,
Value: f.Value,
})
case *mcnflag.StringFlag:
f := f.(*mcnflag.StringFlag)
cliFlags = append(cliFlags, cli.StringFlag{
Name: f.Name,
EnvVar: f.EnvVar,
Usage: f.Usage,
Value: f.Value,
})
case *mcnflag.StringSliceFlag:
f := f.(*mcnflag.StringSliceFlag)
cliFlags = append(cliFlags, cli.StringSliceFlag{
Name: f.Name,
EnvVar: f.EnvVar,
Usage: f.Usage,
//TODO: Is this used with defaults? Can we convert the literal []string to cli.StringSlice properly?
Value: &cli.StringSlice{},
})
default:
log.Warn("Flag is ", f)
return nil, fmt.Errorf("Flag is unrecognized flag type: %T", t)
}
}
return cliFlags, nil
}
func addDriverFlagsToCommand(cliFlags []cli.Flag, cmd *cli.Command) *cli.Command {
cmd.Flags = append(SharedCreateFlags, cliFlags...)
cmd.SkipFlagParsing = false
cmd.Action = runCommand(cmdCreateInner)
sort.Sort(ByFlagName(cmd.Flags))
return cmd
}
func validateSwarmDiscovery(discovery string) error {
if discovery == "" {
return nil
}
matched, err := regexp.MatchString(`[^:]*://.*`, discovery)
if err != nil {
return err
}
if matched {
return nil
}
return fmt.Errorf("Swarm Discovery URL was in the wrong format: %s", discovery)
}
func tlsPath(c CommandLine, flag string, defaultName string) string {
path := c.GlobalString(flag)
if path != "" {
return path
}
return filepath.Join(mcndirs.GetMachineCertDir(), defaultName)
}