-
Notifications
You must be signed in to change notification settings - Fork 20
/
config.go
503 lines (462 loc) · 20.3 KB
/
config.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
)
type Config struct {
Action string
ConfigFile string
Driver string
LogLevel string
Debug string
Interactive string
RemoveContainers string
WorkDirInner string
WorkDirOuter string
IdentityDirOuter string
BlacklistVariables string
RunCommand string
DockerImage string
DockerOptions string
DockerComposeFile string
DockerComposeOptions string
PreserveEnvironmentToAllContainers string
ExitBehavior string
Test string
PrintLogs string
PrintLogsTarget string
}
func (c Config) String() string {
str := ""
str += fmt.Sprintf("{ Action: %s }", c.Action)
str += fmt.Sprintf("{ ConfigFile: %s }", c.ConfigFile)
str += fmt.Sprintf("{ Driver: %s }", c.Driver)
str += fmt.Sprintf("{ LogLevel: %s }", c.LogLevel)
str += fmt.Sprintf("{ Debug: %s }", c.Debug)
str += fmt.Sprintf("{ Interactive: %s }", c.Interactive)
str += fmt.Sprintf("{ RemoveContainers: %s }", c.RemoveContainers)
str += fmt.Sprintf("{ WorkDirInner: %s }", c.WorkDirInner)
str += fmt.Sprintf("{ WorkDirOuter: %s }", c.WorkDirOuter)
str += fmt.Sprintf("{ IdentityDirOuter: %s }", c.IdentityDirOuter)
str += fmt.Sprintf("{ BlacklistVariables: %s }", c.BlacklistVariables)
str += fmt.Sprintf("{ RunCommand: %s }", c.RunCommand)
str += fmt.Sprintf("{ DockerImage: %s }", c.DockerImage)
str += fmt.Sprintf("{ DockerOptions: %s }", c.DockerOptions)
str += fmt.Sprintf("{ DockerComposeFile: %s }", c.DockerComposeFile)
str += fmt.Sprintf("{ DockerComposeOptions: %s }", c.DockerComposeOptions)
str += fmt.Sprintf("{ PreserveEnvironmentToAllContainers: %s }", c.PreserveEnvironmentToAllContainers)
str += fmt.Sprintf("{ ExitBehavior: %s }", c.ExitBehavior)
str += fmt.Sprintf("{ Test: %s }", c.Test)
str += fmt.Sprintf("{ PrintLogs: %s }", c.PrintLogs)
str += fmt.Sprintf("{ PrintLogsTarget: %s }", c.PrintLogsTarget)
return str
}
func getCLIConfig() Config {
// let's use use a custom flagSet, so that we don't mutate global state
flagSet := flag.NewFlagSet("flagSet", flag.PanicOnError)
var help bool
const usageHelp = "Print help and exit 0"
flagSet.BoolVar(&help, "help", false, usageHelp)
flagSet.BoolVar(&help, "h", false, usageHelp+" (shorthand)")
var version bool
const usageVersion = "Print version and exit 0"
flagSet.BoolVar(&version, "version", false, usageVersion)
flagSet.BoolVar(&version, "v", false, usageVersion+" (shorthand)")
var action string
const usageAction = "Action: run, pull. Default: run"
flagSet.StringVar(&action, "action", "", usageAction)
flagSet.StringVar(&action, "a", "", usageAction+" (shorthand)")
var config string
const usageConfig = "Config file. Default: ./Dojofile"
flagSet.StringVar(&config, "config", "", usageConfig)
flagSet.StringVar(&config, "c", "", usageConfig+" (shorthand)")
var driver string
const usageDriver = "Driver: docker or docker-compose (dc for short). Default: docker"
flagSet.StringVar(&driver, "driver", "", usageDriver)
flagSet.StringVar(&driver, "d", "", usageDriver+" (shorthand)")
var image string
const usageImage = "Docker image name and tag, e.g. alpine:3.15"
flagSet.StringVar(&image, "image", "", usageImage)
var logLevel string
const usageLogLevel = "Set log level to: silent, error, info, debug. Default: info"
flagSet.StringVar(&logLevel, "log-level", "", usageLogLevel)
flagSet.StringVar(&logLevel, "ll", "", usageLogLevel+" (shorthand)")
flagSet.StringVar(&logLevel, "loglevel", "", usageLogLevel+" (alternative)")
// this is not bool, because we need to know if it was set or not
var debug string
const usageDebug = "Set logLevel to debug (verbose). Prefer the newer option '--log-level' instead. Default: false"
flagSet.StringVar(&debug, "debug", "", usageDebug)
// this is not bool, because we need to know if it was set or not
var interactive string
const usageInteractive = "Set to false if you want to force not interactive docker run"
flagSet.StringVar(&interactive, "interactive", "", usageInteractive)
flagSet.StringVar(&interactive, "i", "", usageInteractive)
// this is not bool, because we need to know if it was set or not
var removeContainers string
const usageRm = "Set to true if you want to not remove docker containers. Default: true"
flagSet.StringVar(&removeContainers, "remove-containers", "", usageRm)
flagSet.StringVar(&removeContainers, "rm", "", usageRm)
var workDirInner string
const usageWorkDirInner = "Directory in a docker container, to which we bind mount from host. Default: /dojo/work"
flagSet.StringVar(&workDirInner, "work-dir-inner", "", usageWorkDirInner)
flagSet.StringVar(&workDirInner, "w", "", usageWorkDirInner+" (shorthand)")
var workDirOuter string
const usageWworkDirOuter = "Directory on host, to be mounted into a docker container. Default: current directory"
flagSet.StringVar(&workDirOuter, "work-dir-outer", "", usageWworkDirOuter)
var identityDirOuter string
const usageIdentityDirOuter = "Directory on host, to be mounted into a docker container to /dojo/identity. Default: $HOME"
flagSet.StringVar(&identityDirOuter, "identity-dir-outer", "", usageIdentityDirOuter)
var blacklistVariables string
const usageBlackilstVariables = "List of variables, split by commas, to be blacklisted in a docker container"
flagSet.StringVar(&blacklistVariables, "blacklist", "", usageBlackilstVariables)
var dockerOptions string
const usageDockerOptions = "Options to the docker run command. E.g. \"--init\""
flagSet.StringVar(&dockerOptions, "docker-options", "", usageDockerOptions)
var preserveEnvToAllContainers string
const preserveEnvToAll = "Set to false, if you want to preserve current environment only to default container. Default: true (preserves to all containers)."
flagSet.StringVar(&dockerOptions, "preserve-env-to-all", "", preserveEnvToAllContainers)
var dockerComposeFile string
const usageDCFile = "Docker-compose file. Default: ./docker-compose.yml. Only for driver: docker-compose"
flagSet.StringVar(&dockerComposeFile, "docker-compose-file", "", usageDCFile)
flagSet.StringVar(&dockerComposeFile, "dcf", "", usageDCFile+" (shorthand)")
var exitBehavior string
const usageExitBehavior = "How to react when a container (not the default one) exits. Possible values: ignore, abort (default), restart. Only for driver: docker-compose"
flagSet.StringVar(&exitBehavior, "exit-behavior", "", usageExitBehavior)
var printLogs string
const usagePrintLogs = "Decide when to print the logs of non-default containers. Possible values: always, failure (default), never. Only for driver: docker-compose"
flagSet.StringVar(&printLogs, "print-logs", "", usagePrintLogs)
var printLogsTarget string
const usagePrintLogsTarget = "Decide where to print the logs of non-default containers. Possible values: console (default, stderr), file. Only for driver: docker-compose"
flagSet.StringVar(&printLogsTarget, "print-logs-target", "", usagePrintLogsTarget)
var test string
const usageTest = "Set this to true when integration testing. This turns writing env files to a test directory"
flagSet.StringVar(&test, "test", "", usageTest)
flagSet.Parse(os.Args[1:])
runCommandArr := flagSet.Args()
runCommand := smartJoinCommandArgs(runCommandArr)
flagSet.Usage = func() {
fmt.Fprint(os.Stderr, "Usage of dojo <flags> [--] <CMD>:\n")
flagSet.PrintDefaults()
}
if help {
flagSet.Usage()
os.Exit(0)
}
if version {
fmt.Println(fmt.Sprintf("Dojo version %s", DojoVersion))
os.Exit(0)
}
workDirInnerAbs := getAbsPathOrPanic(workDirInner)
workDirOuterAbs := getAbsPathOrPanic(workDirOuter)
identityDirOuterAbs := getAbsPathOrPanic(identityDirOuter)
return Config{
Action: action,
ConfigFile: config,
Driver: driver,
LogLevel: logLevel,
Debug: debug,
Interactive: interactive,
RemoveContainers: removeContainers,
WorkDirInner: workDirInnerAbs,
WorkDirOuter: workDirOuterAbs,
IdentityDirOuter: identityDirOuterAbs,
BlacklistVariables: blacklistVariables,
RunCommand: runCommand,
DockerImage: image,
DockerOptions: dockerOptions,
PreserveEnvironmentToAllContainers: preserveEnvToAllContainers,
DockerComposeFile: dockerComposeFile,
ExitBehavior: exitBehavior,
Test: test,
PrintLogs: printLogs,
PrintLogsTarget: printLogsTarget,
}
}
func getAbsPathOrPanic(path string) string {
if path == "" {
return path
} else {
absPath, err := filepath.Abs(path)
if err != nil {
panic(err)
}
return absPath
}
}
// While parsing CLI arguments, after all the flags are handled, we want to treat the rest of the arguments
// as 1 element, as docker or docker-compose run command.
// We cannot just use strings.Join(runCommandArr, " ") because this would result in missing quotes.
func smartJoinCommandArgs(commandArgs []string) string {
quotedArgs := make([]string, 0)
for _, v := range commandArgs {
// It is safe to assume that an argument that contains white space(s) must have been (and should be) quoted
// http://stackoverflow.com/a/1669493/4457564
// Otherwise, this input command: -c "echo aaa"
// would result in an output command: -c echo aaa.
updatedStr := v
if strings.Contains(v, " ") {
// If quotes were used 2 times, we have to escape the inner quotes. E.g. input command was:
// "/bin/bash -c \"echo aaa\" && echo bbb".
// Notice that, the shell strips outer quotes of an argument, so that argument (here: v) will
// never have outer quotes. Thus, by checking if v contains quotes, we check for the quotes
// which are not at the first or last string char (we check for the inner quotes).
if strings.Contains(v, "\"") {
updatedStr = strings.Replace(updatedStr, "\"", "\\\"", -1)
}
// and now let's quote it
updatedStr = fmt.Sprintf("\"%s\"", updatedStr)
}
quotedArgs = append(quotedArgs, updatedStr)
}
return strings.Join(quotedArgs, " ")
}
func MapToConfig(configMap map[string]string) Config {
config := Config{}
config.Action = configMap["action"]
config.ConfigFile = configMap["config"]
config.Driver = configMap["driver"]
config.LogLevel = configMap["logLevel"]
config.Debug = configMap["debug"]
config.Interactive = configMap["interactive"]
config.RemoveContainers = configMap["removeContainers"]
config.WorkDirInner = configMap["workDirInner"]
config.WorkDirOuter = configMap["workDirOuter"]
config.IdentityDirOuter = configMap["identityDirOuter"]
config.BlacklistVariables = configMap["blacklistVariables"]
config.RunCommand = configMap["runCommand"]
config.DockerImage = configMap["dockerImage"]
config.DockerOptions = configMap["dockerOptions"]
config.DockerComposeFile = configMap["dockerComposeFile"]
config.DockerComposeOptions = configMap["dockerComposeOptions"]
config.PreserveEnvironmentToAllContainers = configMap["preserveEnvironmentToAllContainers"]
config.ExitBehavior = configMap["exitBehavior"]
config.Test = configMap["test"]
config.PrintLogs = configMap["printLogs"]
config.PrintLogsTarget = configMap["printLogsTarget"]
return config
}
func ConfigToMap(config Config) map[string]string {
configMap := make(map[string]string, 0)
configMap["action"] = config.Action
configMap["config"] = config.ConfigFile
configMap["driver"] = config.Driver
configMap["debug"] = config.Debug
configMap["logLevel"] = config.LogLevel
configMap["interactive"] = config.Interactive
configMap["removeContainers"] = config.RemoveContainers
configMap["workDirInner"] = config.WorkDirInner
configMap["workDirOuter"] = config.WorkDirOuter
configMap["identityDirOuter"] = config.IdentityDirOuter
configMap["blacklistVariables"] = config.BlacklistVariables
configMap["runCommand"] = config.RunCommand
configMap["dockerImage"] = config.DockerImage
configMap["dockerOptions"] = config.DockerOptions
configMap["dockerComposeFile"] = config.DockerComposeFile
configMap["dockerComposeOptions"] = config.DockerComposeOptions
configMap["preserveEnvironmentToAllContainers"] = config.PreserveEnvironmentToAllContainers
configMap["exitBehavior"] = config.ExitBehavior
configMap["test"] = config.Test
configMap["printLogs"] = config.PrintLogs
configMap["printLogsTarget"] = config.PrintLogsTarget
return configMap
}
func ensureNoOuterQuotes(input string) string {
if strings.HasPrefix(input, "\"") && strings.HasSuffix(input, "\"") {
output := strings.TrimPrefix(input, "\"")
output = strings.TrimSuffix(output, "\"")
return output
}
if strings.HasPrefix(input, "'") && strings.HasSuffix(input, "'") {
output := strings.TrimPrefix(input, "'")
output = strings.TrimSuffix(output, "'")
return output
}
return input
}
// getFileConfig never returns error. If config file does not exist,
// it returns Config object with default values.
func getFileConfig(logger *Logger, pathToFile string) Config {
config := Config{}
if _, err := os.Stat(pathToFile); err == nil {
contents, err := ioutil.ReadFile(pathToFile)
if err != nil {
panic(err)
}
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if !strings.HasPrefix(line, "#") && line != "" {
// the file line is not a comment
// there may be many "=" signs in this line, let's just consider the 1st one
kv := strings.SplitN(line, "=", 2)
key := kv[0]
value := kv[1]
value = ensureNoOuterQuotes(value)
switch key {
case "DOJO_DRIVER":
config.Driver = value
case "DOJO_DOCKER_IMAGE":
config.DockerImage = value
case "DOJO_DOCKER_OPTIONS":
config.DockerOptions = value
case "DOJO_DOCKER_COMPOSE_FILE":
config.DockerComposeFile = value
case "DOJO_DOCKER_COMPOSE_OPTIONS":
config.DockerComposeOptions = value
case "DOJO_DOCKER_COMPOSE_PRINT_LOGS":
config.PrintLogs = value
case "DOJO_DOCKER_COMPOSE_PRINT_LOGS_TARGET":
config.PrintLogsTarget = value
case "DOJO_PRESERVE_ENV_TO_ALL_CONTAINERS":
config.PreserveEnvironmentToAllContainers = value
case "DOJO_WORK_OUTER":
dir := getAbsPathOrPanic(value)
config.WorkDirOuter = dir
case "DOJO_WORK_INNER":
dir := getAbsPathOrPanic(value)
config.WorkDirInner = dir
case "DOJO_IDENTITY_OUTER":
dir := getAbsPathOrPanic(value)
config.IdentityDirOuter = dir
case "DOJO_EXIT_BEHAVIOR":
config.ExitBehavior = value
case "DOJO_BLACKLIST_VARIABLES":
config.BlacklistVariables = value
case "DOJO_LOG_LEVEL":
if value == "debug" || value == "DEBUG" {
config.Debug = "true"
// the stronger option value (the more verbose) wins
config.LogLevel = "debug"
} else {
config.Debug = "false"
config.LogLevel = value
}
}
}
}
} else {
logger.Log("debug", fmt.Sprintf("Config file does not exist: %s", pathToFile))
}
return config
}
func getDefaultConfig(configFile string) Config {
currentDirectory, err := os.Getwd()
if err != nil {
panic(err)
}
currentUser, err := user.Current()
if err != nil {
panic(err)
}
defaultConfig := Config{
Action: "run",
ConfigFile: configFile,
Driver: "docker",
LogLevel: "info",
Debug: "false",
RemoveContainers: "true",
WorkDirOuter: currentDirectory,
WorkDirInner: "/dojo/work",
IdentityDirOuter: currentUser.HomeDir,
BlacklistVariables: "BASH*,HOME,USERNAME,USER,LOGNAME,PATH,TERM,SHELL,MAIL,SUDO_*,WINDOWID,SSH_*,SESSION_*,GEM_HOME,GEM_PATH,GEM_ROOT,HOSTNAME,HOSTTYPE,IFS,PPID,PWD,OLDPWD,LC*,TMPDIR",
DockerComposeFile: "docker-compose.yml",
ExitBehavior: "abort",
PreserveEnvironmentToAllContainers: "true",
PrintLogs: "failure",
PrintLogsTarget: "console",
}
return defaultConfig
}
func getMergedConfig(moreImportantConfig Config, lessImportantConfig Config, leastImportantConfig Config) Config {
leastImportantConfigMap := ConfigToMap(leastImportantConfig)
moreImportantConfigMap := ConfigToMap(moreImportantConfig)
lessImportantConfigMap := ConfigToMap(lessImportantConfig)
mergedConfigMap := make(map[string]string, 0)
for k, v := range moreImportantConfigMap {
if v != "" {
mergedConfigMap[k] = v
} else if lessImportantConfigMap[k] != "" {
mergedConfigMap[k] = lessImportantConfigMap[k]
} else {
mergedConfigMap[k] = leastImportantConfigMap[k]
}
}
config := MapToConfig(mergedConfigMap)
return config
}
func verifyConfig(logger *Logger, config *Config) error {
if config.Driver == "dc" {
config.Driver = "docker-compose"
}
if config.Action != "run" && config.Action != "pull" {
return fmt.Errorf("Invalid configuration, unsupported Action: %s. Supported: run, pull", config.Action)
}
if config.Driver != "docker" && config.Driver != "docker-compose" {
return fmt.Errorf("Invalid configuration, unsupported Driver: %s. Supported: docker, docker-compose", config.Driver)
}
if config.Debug != "true" && config.Debug != "false" {
return fmt.Errorf("Invalid configuration, unsupported Debug: %s. Supported: true, false", config.Debug)
}
if config.LogLevel != "silent" && config.LogLevel != "error" && config.LogLevel != "warn" &&
config.LogLevel != "info" && config.LogLevel != "debug" {
return fmt.Errorf("Invalid configuration, unsupported LogLevel: %s. Supported: silent, error, warn, info, debug", config.LogLevel)
}
if config.Debug == "true" {
// the more verbose option takes precedence
config.LogLevel = "debug"
}
if config.LogLevel == "debug" {
// the more verbose option takes precedence
config.Debug = "true"
}
if config.DockerComposeOptions != "" && config.Driver == "docker" {
return fmt.Errorf("DockerComposeOptions option is unsupported for driver: docker")
}
if config.DockerOptions != "" && config.Driver == "docker-compose" {
return fmt.Errorf("DockerOptions option is unsupported for driver: docker-compose")
}
if config.RemoveContainers == "false" && config.Driver == "docker-compose" {
logger.Log("warn", "RemoveContainers=false is unsupported for driver: docker-compose")
}
if config.RemoveContainers != "true" && config.RemoveContainers != "false" {
return fmt.Errorf("Invalid configuration, unsupported RemoveContainers: %s. Supported: true, false", config.RemoveContainers)
}
if config.Interactive != "true" && config.Interactive != "false" && config.Interactive != "" {
return fmt.Errorf("Invalid configuration, unsupported Interactive: %s. Supported: true, false, empty string", config.Interactive)
}
if config.PreserveEnvironmentToAllContainers != "true" && config.PreserveEnvironmentToAllContainers != "false" {
return fmt.Errorf("Invalid configuration, unsupported PreserveEnvironmentToAllContainers: %s. Supported: true, false", config.PreserveEnvironmentToAllContainers)
}
if config.PrintLogs != "always" && config.PrintLogs != "failure" && config.PrintLogs != "never" {
return fmt.Errorf(
"Invalid configuration, PrintLogs supported values are: always, failure, never. It was set to: %s",
config.PrintLogs)
}
if config.PrintLogsTarget != "console" && config.PrintLogsTarget != "file" {
return fmt.Errorf(
"Invalid configuration, PrintLogsTarget supported values are: console, file. It was set to: %s",
config.PrintLogsTarget)
}
if config.DockerImage == "" {
return fmt.Errorf("Invalid configuration, DockerImage is unset")
}
if config.Driver == "docker-compose" {
if config.DockerComposeFile == "" {
return fmt.Errorf("Invalid configuration, DockerComposeFile is unset")
}
dcFile := config.DockerComposeFile
if _, err := os.Stat(dcFile); err != nil {
return fmt.Errorf("docker-compose config file: %s does not exist", dcFile)
}
if config.ExitBehavior != "abort" && config.ExitBehavior != "ignore" && config.ExitBehavior != "restart" {
return fmt.Errorf(
"Invalid configuration, ExitBehavior supported values are: abort, ignore, restart. It was set to: %s",
config.ExitBehavior)
}
}
return nil
}