forked from hashicorp/consul-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
589 lines (504 loc) · 15.2 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
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/hashicorp/consul-template/watch"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/hcl"
"github.com/mitchellh/mapstructure"
)
// The pattern to split the config template syntax on
var configTemplateRe = regexp.MustCompile("([a-zA-Z]:)?([^:]+)")
// Config is used to configure Consul Template
type Config struct {
// Path is the path to this configuration file on disk. This value is not
// read from disk by rather dynamically populated by the code so the Config
// has a reference to the path to the file on disk that created it.
Path string `json:"path" mapstructure:"-"`
// Consul is the location of the Consul instance to query (may be an IP
// address or FQDN) with port.
Consul string `json:"consul" mapstructure:"consul"`
// Token is the Consul API token.
Token string `json:"-" mapstructure:"token"`
// Auth is the HTTP basic authentication for communicating with Consul.
Auth *AuthConfig `json:"auth" mapstructure:"auth"`
// Vault is the configuration for connecting to a vault server.
Vault *VaultConfig `json:"vault" mapstructure:"vault"`
// SSL indicates we should use a secure connection while talking to
// Consul. This requires Consul to be configured to serve HTTPS.
SSL *SSLConfig `json:"ssl" mapstructure:"ssl"`
// Syslog is the configuration for syslog.
Syslog *SyslogConfig `json:"syslog" mapstructure:"syslog"`
// MaxStale is the maximum amount of time for staleness from Consul as given
// by LastContact. If supplied, Consul Template will query all servers instead
// of just the leader.
MaxStale time.Duration `json:"max_stale" mapstructure:"max_stale"`
// ConfigTemplates is a slice of the ConfigTemplate objects in the config.
ConfigTemplates []*ConfigTemplate `json:"templates" mapstructure:"template"`
// Retry is the duration of time to wait between Consul failures.
Retry time.Duration `json:"retry" mapstructure:"retry"`
// Wait is the quiescence timers.
Wait *watch.Wait `json:"wait" mapstructure:"wait"`
// PidFile is the path on disk where a PID file should be written containing
// this processes PID.
PidFile string `json:"pid_file" mapstructure:"pid_file"`
// LogLevel is the level with which to log for this config.
LogLevel string `json:"log_level" mapstructure:"log_level"`
// setKeys is the list of config keys that were set by the user.
setKeys map[string]struct{}
}
// Merge merges the values in config into this config object. Values in the
// config object overwrite the values in c.
func (c *Config) Merge(config *Config) {
if config.WasSet("path") {
c.Path = config.Path
}
if config.WasSet("consul") {
c.Consul = config.Consul
}
if config.WasSet("token") {
c.Token = config.Token
}
if config.WasSet("vault") {
if c.Vault == nil {
c.Vault = &VaultConfig{}
}
if config.WasSet("vault.address") {
c.Vault.Address = config.Vault.Address
}
if config.WasSet("vault.token") {
c.Vault.Token = config.Vault.Token
}
if config.WasSet("vault.renew") {
c.Vault.Renew = config.Vault.Renew
}
if config.WasSet("vault.ssl") {
if c.Vault.SSL == nil {
c.Vault.SSL = &SSLConfig{}
}
if config.WasSet("vault.ssl.verify") {
c.Vault.SSL.Verify = config.Vault.SSL.Verify
c.Vault.SSL.Enabled = true
}
if config.WasSet("vault.ssl.cert") {
c.Vault.SSL.Cert = config.Vault.SSL.Cert
c.Vault.SSL.Enabled = true
}
if config.WasSet("vault.ssl.ca_cert") {
c.Vault.SSL.CaCert = config.Vault.SSL.CaCert
c.Vault.SSL.Enabled = true
}
if config.WasSet("vault.ssl.enabled") {
c.Vault.SSL.Enabled = config.Vault.SSL.Enabled
}
}
}
if config.WasSet("auth") {
if c.Auth == nil {
c.Auth = &AuthConfig{}
}
if config.WasSet("auth.username") {
c.Auth.Username = config.Auth.Username
c.Auth.Enabled = true
}
if config.WasSet("auth.password") {
c.Auth.Password = config.Auth.Password
c.Auth.Enabled = true
}
if config.WasSet("auth.enabled") {
c.Auth.Enabled = config.Auth.Enabled
}
}
if config.WasSet("ssl") {
if c.SSL == nil {
c.SSL = &SSLConfig{}
}
if config.WasSet("ssl.verify") {
c.SSL.Verify = config.SSL.Verify
c.SSL.Enabled = true
}
if config.WasSet("ssl.cert") {
c.SSL.Cert = config.SSL.Cert
c.SSL.Enabled = true
}
if config.WasSet("ssl.ca_cert") {
c.SSL.CaCert = config.SSL.CaCert
c.SSL.Enabled = true
}
if config.WasSet("ssl.enabled") {
c.SSL.Enabled = config.SSL.Enabled
}
}
if config.WasSet("syslog") {
if c.Syslog == nil {
c.Syslog = &SyslogConfig{}
}
if config.WasSet("syslog.facility") {
c.Syslog.Facility = config.Syslog.Facility
c.Syslog.Enabled = true
}
if config.WasSet("syslog.enabled") {
c.Syslog.Enabled = config.Syslog.Enabled
}
}
if config.WasSet("max_stale") {
c.MaxStale = config.MaxStale
}
if len(config.ConfigTemplates) > 0 {
if c.ConfigTemplates == nil {
c.ConfigTemplates = make([]*ConfigTemplate, 0, 1)
}
for _, template := range config.ConfigTemplates {
c.ConfigTemplates = append(c.ConfigTemplates, &ConfigTemplate{
Source: template.Source,
Destination: template.Destination,
Command: template.Command,
})
}
}
if config.WasSet("retry") {
c.Retry = config.Retry
}
if config.WasSet("wait") {
c.Wait = &watch.Wait{
Min: config.Wait.Min,
Max: config.Wait.Max,
}
}
if config.WasSet("pid_file") {
c.PidFile = config.PidFile
}
if config.WasSet("log_level") {
c.LogLevel = config.LogLevel
}
if c.setKeys == nil {
c.setKeys = make(map[string]struct{})
}
for k, _ := range config.setKeys {
if _, ok := c.setKeys[k]; !ok {
c.setKeys[k] = struct{}{}
}
}
}
// WasSet determines if the given key was set in the config (as opposed to just
// having the default value).
func (c *Config) WasSet(key string) bool {
if _, ok := c.setKeys[key]; ok {
return true
}
return false
}
// set is a helper function for marking a key as set.
func (c *Config) set(key string) {
if _, ok := c.setKeys[key]; !ok {
c.setKeys[key] = struct{}{}
}
}
// ParseConfig reads the configuration file at the given path and returns a new
// Config struct with the data populated.
func ParseConfig(path string) (*Config, error) {
var errs *multierror.Error
// Read the contents of the file
contents, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("error reading config at %q: %s", path, err)
}
// Parse the file (could be HCL or JSON)
var shadow interface{}
if err := hcl.Decode(&shadow, string(contents)); err != nil {
return nil, fmt.Errorf("error decoding config at %q: %s", path, err)
}
// Convert to a map and flatten the keys we want to flatten
parsed, ok := shadow.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("error converting config at %q", path)
}
flattenKeys(parsed, []string{"auth", "ssl", "syslog", "vault"})
//
if raw, ok := parsed["max_stale"]; ok {
if typed, ok := raw.(string); !ok {
err = fmt.Errorf("error converting max_stale to string at %q", path)
errs = multierror.Append(errs, err)
delete(parsed, "max_stale")
} else {
if stale, err := time.ParseDuration(typed); err != nil {
err = fmt.Errorf("error parsing max_stale at %q: %s", path, err)
errs = multierror.Append(errs, err)
delete(parsed, "max_stale")
} else {
parsed["max_stale"] = stale
}
}
}
if raw, ok := parsed["retry"]; ok {
if typed, ok := raw.(string); !ok {
err = fmt.Errorf("error converting retry to string at %q", path)
errs = multierror.Append(errs, err)
delete(parsed, "retry")
} else {
if stale, err := time.ParseDuration(typed); err != nil {
err = fmt.Errorf("error parsing retry at %q: %s", path, err)
errs = multierror.Append(errs, err)
delete(parsed, "retry")
} else {
parsed["retry"] = stale
}
}
}
if raw, ok := parsed["wait"]; ok {
if typed, ok := raw.(string); !ok {
err = fmt.Errorf("error converting wait to string at %q", path)
errs = multierror.Append(errs, err)
delete(parsed, "wait")
} else {
if wait, err := watch.ParseWait(typed); err != nil {
err = fmt.Errorf("error parsing wait at %q: %s", path, err)
errs = multierror.Append(errs, err)
delete(parsed, "wait")
} else {
parsed["wait"] = map[string]time.Duration{
"min": wait.Min,
"max": wait.Max,
}
}
}
}
// Create a new, empty config
config := new(Config)
// Use mapstructure to populate the basic config fields
metadata := new(mapstructure.Metadata)
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
ErrorUnused: true,
Metadata: metadata,
Result: config,
})
if err != nil {
errs = multierror.Append(errs, err)
return nil, errs.ErrorOrNil()
}
if err := decoder.Decode(parsed); err != nil {
errs = multierror.Append(errs, err)
return nil, errs.ErrorOrNil()
}
// Store a reference to the path where this config was read from
config.Path = path
// Update the list of set keys
if config.setKeys == nil {
config.setKeys = make(map[string]struct{})
}
for _, key := range metadata.Keys {
if _, ok := config.setKeys[key]; !ok {
config.setKeys[key] = struct{}{}
}
}
config.setKeys["path"] = struct{}{}
d := DefaultConfig()
d.Merge(config)
config = d
return config, errs.ErrorOrNil()
}
// ConfigFromPath iterates and merges all configuration files in a given
// directory, returning the resulting config.
func ConfigFromPath(path string) (*Config, error) {
log.Printf("[DEBUG] (config) loading configs from %q", path)
// Ensure the given filepath exists
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, fmt.Errorf("config: missing file/folder: %s", path)
}
// Check if a file was given or a path to a directory
stat, err := os.Stat(path)
if err != nil {
return nil, fmt.Errorf("config: error stating file: %s", err)
}
// 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, fmt.Errorf("config: error listing directory: %s", err)
}
// Create a blank config to merge off of
config := DefaultConfig()
// 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
}
log.Printf("[DEBUG] (config) merging with %q", path)
// Parse and merge the config
newConfig, err := ParseConfig(path)
if err != nil {
return err
}
config.Merge(newConfig)
return nil
})
if err != nil {
return nil, fmt.Errorf("config: walk error: %s", err)
}
return config, nil
} else if stat.Mode().IsRegular() {
return ParseConfig(path)
}
return nil, fmt.Errorf("config: unknown filetype: %q", stat.Mode().String())
}
// DefaultConfig returns the default configuration struct.
func DefaultConfig() *Config {
logLevel := os.Getenv("CONSUL_TEMPLATE_LOG")
if logLevel == "" {
logLevel = "WARN"
}
config := &Config{
Vault: &VaultConfig{
Renew: true,
SSL: &SSLConfig{
Enabled: true,
Verify: true,
},
},
Auth: &AuthConfig{
Enabled: false,
},
SSL: &SSLConfig{
Enabled: false,
Verify: true,
},
Syslog: &SyslogConfig{
Enabled: false,
Facility: "LOCAL0",
},
ConfigTemplates: make([]*ConfigTemplate, 0),
Retry: 5 * time.Second,
Wait: &watch.Wait{},
LogLevel: logLevel,
setKeys: make(map[string]struct{}),
}
if v := os.Getenv("CONSUL_HTTP_ADDR"); v != "" {
config.Consul = v
}
if v := os.Getenv("CONSUL_TOKEN"); v != "" {
config.Token = v
}
if v := os.Getenv("VAULT_ADDR"); v != "" {
config.Vault.Address = v
}
if v := os.Getenv("VAULT_CAPATH"); v != "" {
config.Vault.SSL.Cert = v
}
if v := os.Getenv("VAULT_CACERT"); v != "" {
config.Vault.SSL.CaCert = v
}
if v := os.Getenv("VAULT_SKIP_VERIFY"); v != "" {
config.Vault.SSL.Verify = false
}
return config
}
// AuthConfig is the HTTP basic authentication data.
type AuthConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"`
Username string `json:"username" mapstructure:"username"`
Password string `json:"password" mapstructure:"password"`
}
// String is the string representation of this authentication. If authentication
// is not enabled, this returns the empty string. The username and password will
// be separated by a colon.
func (a *AuthConfig) String() string {
if !a.Enabled {
return ""
}
if a.Password != "" {
return fmt.Sprintf("%s:%s", a.Username, a.Password)
}
return a.Username
}
// SSLConfig is the configuration for SSL.
type SSLConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"`
Verify bool `json:"verify" mapstructure:"verify"`
Cert string `json:"cert,omitempty" mapstructure:"cert"`
CaCert string `json:"ca_cert,omitempty" mapstructure:"ca_cert"`
}
// SyslogConfig is the configuration for syslog.
type SyslogConfig struct {
Enabled bool `json:"enabled" mapstructure:"enabled"`
Facility string `json:"facility" mapstructure:"facility"`
}
// ConfigTemplate is the representation of an input template, output location,
// and optional command to execute when rendered
type ConfigTemplate struct {
Source string `json:"source" mapstructure:"source"`
Destination string `json:"destination" mapstructure:"destination"`
Command string `json:"command,omitempty" mapstructure:"command"`
}
// VaultConfig is the configuration for connecting to a vault server.
type VaultConfig struct {
Address string `json:"address,omitempty" mapstructure:"address"`
Token string `json:"-" mapstructure:"token"`
Renew bool `json:"renew" mapstructure:"renew"`
// SSL indicates we should use a secure connection while talking to Vault.
SSL *SSLConfig `json:"ssl" mapstructure:"ssl"`
}
// ParseConfigTemplate parses a string into a ConfigTemplate struct
func ParseConfigTemplate(s string) (*ConfigTemplate, error) {
if len(strings.TrimSpace(s)) < 1 {
return nil, errors.New("cannot specify empty template declaration")
}
var source, destination, command string
parts := configTemplateRe.FindAllString(s, -1)
switch len(parts) {
case 1:
source = parts[0]
case 2:
source, destination = parts[0], parts[1]
case 3:
source, destination, command = parts[0], parts[1], parts[2]
default:
return nil, errors.New("invalid template declaration format")
}
return &ConfigTemplate{source, destination, command}, nil
}
// 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{})
flatten = func(m map[string]interface{}) {
for k, v := range m {
if _, ok := keyMap[k]; !ok {
continue
}
switch typed := v.(type) {
case []map[string]interface{}:
if len(typed) > 0 {
last := typed[len(typed)-1]
flatten(last)
m[k] = last
} else {
m[k] = nil
}
case map[string]interface{}:
flatten(typed)
m[k] = typed
default:
m[k] = v
}
}
}
flatten(m)
}