-
Notifications
You must be signed in to change notification settings - Fork 189
/
config.go
718 lines (596 loc) · 16.5 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
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/hashicorp/consul-template/config"
"github.com/hashicorp/consul-template/signals"
"github.com/hashicorp/hcl"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
)
const (
// DefaultLogLevel is the default logging level.
DefaultLogLevel = "WARN"
// DefaultMaxStale is the default staleness permitted. This enables stale
// queries by default for performance reasons.
DefaultMaxStale = 2 * time.Second
// DefaultReloadSignal is the default signal for reload.
DefaultReloadSignal = syscall.SIGHUP
// DefaultKillSignal is the default signal for termination.
DefaultKillSignal = syscall.SIGINT
)
// Config is used to configure Consul ENV
type Config struct {
// Consul is the configuration for connecting to a Consul cluster.
Consul *config.ConsulConfig `mapstructure:"consul"`
// Exec is the configuration for exec/supervise mode.
Exec *config.ExecConfig `mapstructure:"exec"`
// KillSignal is the signal to listen for a graceful terminate event.
KillSignal *os.Signal `mapstructure:"kill_signal"`
// LogLevel is the level with which to log for this config.
LogLevel *string `mapstructure:"log_level"`
// MaxStale is the maximum amount of time for staleness from Consul as given
// by LastContact.
MaxStale *time.Duration `mapstructure:"max_stale"`
// PidFile is the path on disk where a PID file should be written containing
// this processes PID.
PidFile *string `mapstructure:"pid_file"`
// Prefixes is the list of all prefix dependencies (consul)
// in merge order.
Prefixes *PrefixConfigs `mapstructure:"prefix"`
// Pristine indicates that we want a clean environment only
// composed of consul config variables, not inheriting from exising
// environment
Pristine *bool `mapstructure:"pristine"`
// ReloadSignal is the signal to listen for a reload event.
ReloadSignal *os.Signal `mapstructure:"reload_signal"`
// Sanitize converts any "bad" characters in key values to underscores
Sanitize *bool `mapstructure:"sanitize"`
// Secrets is the list of all secret dependencies (vault)
Secrets *PrefixConfigs `mapstructure:"secret"`
Services *ServiceConfigs `mapstructure:"service"`
// Syslog is the configuration for syslog.
Syslog *config.SyslogConfig `mapstructure:"syslog"`
// Upcase converts environment variables to uppercase
Upcase *bool `mapstructure:"upcase"`
// Vault is the configuration for connecting to a vault server.
Vault *config.VaultConfig `mapstructure:"vault"`
// Wait is the quiescence timers.
Wait *config.WaitConfig `mapstructure:"wait"`
}
// Copy returns a deep copy of the current configuration. This is useful because
// the nested data structures may be shared.
func (c *Config) Copy() *Config {
var o Config
if c.Consul != nil {
o.Consul = c.Consul.Copy()
}
if c.Exec != nil {
o.Exec = c.Exec.Copy()
}
o.KillSignal = c.KillSignal
o.LogLevel = c.LogLevel
o.MaxStale = c.MaxStale
o.PidFile = c.PidFile
o.ReloadSignal = c.ReloadSignal
if c.Prefixes != nil {
o.Prefixes = c.Prefixes.Copy()
}
o.Services = c.Services
o.Pristine = c.Pristine
o.Sanitize = c.Sanitize
if c.Secrets != nil {
o.Secrets = c.Secrets.Copy()
}
if c.Syslog != nil {
o.Syslog = c.Syslog.Copy()
}
o.Upcase = c.Upcase
if c.Vault != nil {
o.Vault = c.Vault.Copy()
}
if c.Wait != nil {
o.Wait = c.Wait.Copy()
}
return &o
}
func (c *Config) Merge(o *Config) *Config {
if c == nil {
if o == nil {
return nil
}
return o.Copy()
}
if o == nil {
return c.Copy()
}
r := c.Copy()
if o.Consul != nil {
r.Consul = r.Consul.Merge(o.Consul)
}
if o.Exec != nil {
r.Exec = r.Exec.Merge(o.Exec)
}
if o.KillSignal != nil {
r.KillSignal = o.KillSignal
}
if o.LogLevel != nil {
r.LogLevel = o.LogLevel
}
if o.MaxStale != nil {
r.MaxStale = o.MaxStale
}
if o.PidFile != nil {
r.PidFile = o.PidFile
}
if o.ReloadSignal != nil {
r.ReloadSignal = o.ReloadSignal
}
if o.Prefixes != nil {
r.Prefixes = r.Prefixes.Merge(o.Prefixes)
}
if o.Services != nil {
r.Services = r.Services.Merge(o.Services)
}
if o.Pristine != nil {
r.Pristine = o.Pristine
}
if o.Sanitize != nil {
r.Sanitize = o.Sanitize
}
if o.Secrets != nil {
r.Secrets = r.Secrets.Merge(o.Secrets)
}
if o.Syslog != nil {
r.Syslog = r.Syslog.Merge(o.Syslog)
}
if o.Upcase != nil {
r.Upcase = o.Upcase
}
if o.Vault != nil {
r.Vault = r.Vault.Merge(o.Vault)
}
if o.Wait != nil {
r.Wait = r.Wait.Merge(o.Wait)
}
return r
}
// Parse parses the given string contents as a config
func Parse(s string) (*Config, error) {
logger := namedLogger("parse")
var shadow interface{}
if err := hcl.Decode(&shadow, s); err != nil {
return nil, errors.Wrap(err, "error decoding config")
}
// Convert to a map and flatten the keys we want to flatten
parsed, ok := shadow.(map[string]interface{})
if !ok {
return nil, errors.New("error converting config")
}
flattenKeys(parsed, []string{
"consul",
"consul.auth",
"consul.retry",
"consul.ssl",
"consul.transport",
"exec",
"exec.env",
"syslog",
"vault",
"vault.retry",
"vault.ssl",
"vault.transport",
"wait",
})
// Deprecations
// TODO remove in 0.8.0
flattenKeys(parsed, []string{
"auth",
"ssl",
})
if auth, ok := parsed["auth"]; ok {
logger.Warn("auth is now a child stanza inside consul instead of a " +
"top-level stanza. Update your configuration files and change " +
"auth {} to consul { auth { ... } } instead.")
consul, ok := parsed["consul"].(map[string]interface{})
if !ok {
consul = map[string]interface{}{}
}
consul["auth"] = auth
parsed["consul"] = consul
delete(parsed, "auth")
}
if _, ok := parsed["path"]; ok {
logger.Warn("path is no longer a key in the configuration. Please " +
"remove it and use the CLI option instead.")
delete(parsed, "path")
}
if splay, ok := parsed["splay"]; ok {
logger.Warn(fmt.Sprintf("splay is now a child stanza for exec instead "+
"of a top-level key. Update your configuration files and change "+
"splay = \"%s\" to exec { splay = \"%s\" } instead.", splay, splay))
exec, ok := parsed["exec"].(map[string]interface{})
if !ok {
exec = map[string]interface{}{}
}
exec["splay"] = splay
parsed["exec"] = exec
delete(parsed, "splay")
}
if retry, ok := parsed["retry"]; ok {
logger.Warn("retry is now a child stanza for both consul and vault " +
"instead of a top-level stanza. Update your configuration files " +
"and change retry {} to consul { retry { ... } } and " +
"vault { retry { ... } } instead.")
consul, ok := parsed["consul"].(map[string]interface{})
if !ok {
consul = map[string]interface{}{}
}
vault, ok := parsed["vault"].(map[string]interface{})
if !ok {
vault = map[string]interface{}{}
}
r := map[string]interface{}{
"backoff": retry,
"max_backoff": retry,
}
consul["retry"] = r
parsed["consul"] = consul
vault["retry"] = r
parsed["vault"] = vault
delete(parsed, "retry")
}
if ssl, ok := parsed["ssl"]; ok {
logger.Warn("ssl is now a child stanza for both consul and vault " +
"instead of a top-level stanza. Update your configuration files " +
"and change ssl {} to consul { ssl { ... } } and " +
"vault { ssl { ... } } instead.")
consul, ok := parsed["consul"].(map[string]interface{})
if !ok {
consul = map[string]interface{}{}
}
vault, ok := parsed["vault"].(map[string]interface{})
if !ok {
vault = map[string]interface{}{}
}
consul["ssl"] = ssl
parsed["consul"] = consul
vault["ssl"] = ssl
parsed["vault"] = vault
delete(parsed, "ssl")
}
if timeout, ok := parsed["timeout"]; ok {
logger.Warn(fmt.Sprintf("timeout is now a child stanza for exec instead"+
"of a top-level key. Update your configuration files and change "+
"timeout = \"%s\" to exec { kill_timeout = \"%s\" } instead.",
timeout, timeout))
exec, ok := parsed["exec"].(map[string]interface{})
if !ok {
exec = map[string]interface{}{}
}
exec["kill_timeout"] = timeout
parsed["exec"] = exec
delete(parsed, "timeout")
}
if token, ok := parsed["token"]; ok {
logger.Warn("token is now a child stanza inside consul instead of a " +
"top-level key. Update your configuration files and change " +
"token = \"...\" to consul { token = \"...\" } instead.")
consul, ok := parsed["consul"].(map[string]interface{})
if !ok {
consul = map[string]interface{}{}
}
consul["token"] = token
parsed["consul"] = consul
delete(parsed, "token")
}
// Create a new, empty config
var c Config
// Use mapstructure to populate the basic config fields
var md mapstructure.Metadata
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(
config.ConsulStringToStructFunc(),
config.StringToFileModeFunc(),
signals.StringToSignalFunc(),
config.StringToWaitDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
mapstructure.StringToTimeDurationHookFunc(),
),
ErrorUnused: true,
Metadata: &md,
Result: &c,
})
if err != nil {
logger.Debug(fmt.Sprintf("%#v", parsed))
return nil, errors.Wrap(err, "mapstructure decoder creation failed")
}
if err := decoder.Decode(parsed); err != nil {
logger.Debug(fmt.Sprintf("%#v", parsed))
return nil, errors.Wrap(err, "mapstructure decode failed")
}
return &c, nil
}
// Must returns a config object that must compile. If there are any errors, this
// function will panic. This is most useful in testing or constants.
func Must(s string) *Config {
c, err := Parse(s)
if err != nil {
namedLogger("parse").Error(err.Error())
}
return c
}
// TestConfig returuns a default, finalized config, with the provided
// configuration taking precedence.
func TestConfig(c *Config) *Config {
d := DefaultConfig().Merge(c)
d.Finalize()
return d
}
// FromFile reads the configuration file at the given path and returns a new
// Config struct with the data populated.
func FromFile(path string) (*Config, error) {
c, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, "from file: "+path)
}
config, err := Parse(string(c))
if err != nil {
return nil, errors.Wrap(err, "from file: "+path)
}
return config, nil
}
// FromPath iterates and merges all configuration files in a given
// directory, returning the resulting config.
func FromPath(path string) (*Config, error) {
// Ensure the given filepath exists
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, errors.Wrap(err, "missing file/folder: "+path)
}
// Check if a file was given or a path to a directory
stat, err := os.Stat(path)
if err != nil {
return nil, errors.Wrap(err, "failed stating file: "+path)
}
// Recursively parse directories, single load files
if stat.Mode().IsDir() {
// Ensure the given filepath has at least one config file
_, err := ioutil.ReadDir(path)
if err != nil {
return nil, errors.Wrap(err, "failed listing dir: "+path)
}
// Create a blank config to merge off of
var c *Config
// Potential bug: Walk does not follow symlinks!
err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
// If WalkFunc had an error, just return it
if err != nil {
return err
}
// Do nothing for directories
if info.IsDir() {
return nil
}
// Parse and merge the config
newConfig, err := FromFile(path)
if err != nil {
return err
}
c = c.Merge(newConfig)
return nil
})
if err != nil {
return nil, errors.Wrap(err, "walk error")
}
return c, nil
} else if stat.Mode().IsRegular() {
return FromFile(path)
}
return nil, fmt.Errorf("unknown filetype: %q", stat.Mode().String())
}
// GoString defines the printable version of this struct.
func (c *Config) GoString() string {
if c == nil {
return "(*Config)(nil)"
}
return fmt.Sprintf("&Config{"+
"Consul:%s, "+
"Exec:%s, "+
"KillSignal:%s, "+
"LogLevel:%s, "+
"MaxStale:%s, "+
"PidFile:%s, "+
"Prefixes:%s, "+
"Pristine:%s, "+
"ReloadSignal:%s, "+
"Sanitize:%s, "+
"Secrets:%s, "+
"Services:%s, "+
"Syslog:%s, "+
"Upcase:%s, "+
"Vault:%s, "+
"Wait:%s"+
"}",
c.Consul.GoString(),
c.Exec.GoString(),
config.SignalGoString(c.KillSignal),
config.StringGoString(c.LogLevel),
config.TimeDurationGoString(c.MaxStale),
config.StringGoString(c.PidFile),
c.Prefixes.GoString(),
config.BoolGoString(c.Pristine),
config.SignalGoString(c.ReloadSignal),
config.BoolGoString(c.Sanitize),
c.Secrets.GoString(),
c.Services.GoString(),
c.Syslog.GoString(),
config.BoolGoString(c.Upcase),
c.Vault.GoString(),
c.Wait.GoString(),
)
}
// DefaultConfig returns the default configuration struct. Certain environment
// variables may be set which control the values for the default configuration.
func DefaultConfig() *Config {
return &Config{
Consul: config.DefaultConsulConfig(),
Exec: config.DefaultExecConfig(),
Prefixes: DefaultPrefixConfigs(),
Secrets: DefaultPrefixConfigs(),
Services: DefaultServiceConfigs(),
Syslog: config.DefaultSyslogConfig(),
Vault: config.DefaultVaultConfig(),
Wait: config.DefaultWaitConfig(),
}
}
// Finalize ensures all configuration options have the default values, so it
// is safe to dereference the pointers later down the line. It also
// intelligently tries to activate stanzas that should be "enabled" because
// data was given, but the user did not explicitly add "Enabled: true" to the
// configuration.
func (c *Config) Finalize() {
if c.Consul == nil {
c.Consul = config.DefaultConsulConfig()
}
c.Consul.Finalize()
if c.Exec == nil {
c.Exec = config.DefaultExecConfig()
}
c.Exec.Finalize()
if c.KillSignal == nil {
c.KillSignal = config.Signal(DefaultKillSignal)
}
if c.LogLevel == nil {
c.LogLevel = stringFromEnv([]string{
"CT_LOG",
"ENVCONSUL",
}, DefaultLogLevel)
}
if c.MaxStale == nil {
c.MaxStale = config.TimeDuration(DefaultMaxStale)
}
if c.Prefixes == nil {
c.Prefixes = DefaultPrefixConfigs()
}
c.Prefixes.Finalize()
if c.PidFile == nil {
c.PidFile = config.String("")
}
if c.Pristine == nil {
c.Pristine = config.Bool(false)
}
if c.ReloadSignal == nil {
c.ReloadSignal = config.Signal(DefaultReloadSignal)
}
if c.Sanitize == nil {
c.Sanitize = config.Bool(false)
}
if c.Secrets == nil {
c.Secrets = DefaultPrefixConfigs()
}
c.Secrets.Finalize()
if c.Services == nil {
c.Services = DefaultServiceConfigs()
}
c.Services.Finalize()
if c.Syslog == nil {
c.Syslog = config.DefaultSyslogConfig()
}
c.Syslog.Finalize()
if c.Upcase == nil {
c.Upcase = config.Bool(false)
}
if c.Vault == nil {
c.Vault = config.DefaultVaultConfig()
}
c.Vault.Finalize()
if c.Wait == nil {
c.Wait = config.DefaultWaitConfig()
}
c.Wait.Finalize()
}
func stringFromEnv(list []string, def string) *string {
for _, s := range list {
if v := os.Getenv(s); v != "" {
return config.String(strings.TrimSpace(v))
}
}
return config.String(def)
}
func stringFromFile(list []string, def string) *string {
for _, s := range list {
c, err := ioutil.ReadFile(s)
if err == nil {
return config.String(strings.TrimSpace(string(c)))
}
}
return config.String(def)
}
func antiboolFromEnv(list []string, def bool) *bool {
for _, s := range list {
if v := os.Getenv(s); v != "" {
b, err := strconv.ParseBool(v)
if err == nil {
return config.Bool(!b)
}
}
}
return config.Bool(def)
}
func boolFromEnv(list []string, def bool) *bool {
for _, s := range list {
if v := os.Getenv(s); v != "" {
b, err := strconv.ParseBool(v)
if err == nil {
return config.Bool(b)
}
}
}
return config.Bool(def)
}
// flattenKeys is a function that takes a map[string]interface{} and recursively
// flattens any keys that are a []map[string]interface{} where the key is in the
// given list of keys.
func flattenKeys(m map[string]interface{}, keys []string) {
keyMap := make(map[string]struct{})
for _, key := range keys {
keyMap[key] = struct{}{}
}
var flatten func(map[string]interface{}, string)
flatten = func(m map[string]interface{}, parent string) {
for k, v := range m {
// Calculate the map key, since it could include a parent.
mapKey := k
if parent != "" {
mapKey = parent + "." + k
}
if _, ok := keyMap[mapKey]; !ok {
continue
}
switch typed := v.(type) {
case []map[string]interface{}:
if len(typed) > 0 {
last := typed[len(typed)-1]
flatten(last, mapKey)
m[k] = last
} else {
m[k] = nil
}
case map[string]interface{}:
flatten(typed, mapKey)
m[k] = typed
default:
m[k] = v
}
}
}
flatten(m, "")
}