forked from hashicorp/consul-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
306 lines (255 loc) · 7.69 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
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"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 `mapstructure:"-"`
// Consul is the location of the Consul instance to query (may be an IP
// address or FQDN) with port.
Consul string `mapstructure:"consul"`
// Token is the Consul API token.
Token string `mapstructure:"token"`
// Auth is the HTTP basic authentication for communicating with Consul.
Auth *Auth `mapstructure:"-"`
AuthRaw []*Auth `mapstructure:"auth"`
// SSL indicates we should use a secure connection while talking to
// Consul. This requires Consul to be configured to serve HTTPS.
//
// SSLNoVerify determines if we should skip certificate warnings
SSL *SSL `mapstructure:"-"`
SSLRaw []*SSL `mapstructure:"ssl"`
// Syslog is the configuration for syslog.
Syslog *Syslog `mapstructure:"-"`
SyslogRaw []*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 `mapstructure:"-"`
MaxStaleRaw string `mapstructure:"max_stale"`
// ConfigTemplates is a slice of the ConfigTemplate objects in the config.
ConfigTemplates []*ConfigTemplate `mapstructure:"template"`
// Retry is the duration of time to wait between Consul failures.
Retry time.Duration `mapstructure:"-"`
RetryRaw string `mapstructure:"retry" json:""`
// Wait is the quiescence timers.
Wait *watch.Wait `mapstructure:"-"`
WaitRaw string `mapstructure:"wait" json:""`
// LogLevel is the level with which to log for this config.
LogLevel string `mapstructure:"log_level"`
}
// 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.Consul != "" {
c.Consul = config.Consul
}
if config.Token != "" {
c.Token = config.Token
}
if config.Auth != nil {
c.Auth = &Auth{
Enabled: config.Auth.Enabled,
Username: config.Auth.Username,
Password: config.Auth.Password,
}
}
if config.SSL != nil {
c.SSL = &SSL{
Enabled: config.SSL.Enabled,
Verify: config.SSL.Verify,
}
}
if config.Syslog != nil {
c.Syslog = &Syslog{
Enabled: config.Syslog.Enabled,
Facility: config.Syslog.Facility,
}
}
if config.MaxStale != 0 {
c.MaxStale = config.MaxStale
c.MaxStaleRaw = config.MaxStaleRaw
}
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.Retry != 0 {
c.Retry = config.Retry
c.RetryRaw = config.RetryRaw
}
if config.Wait != nil {
c.Wait = &watch.Wait{
Min: config.Wait.Min,
Max: config.Wait.Max,
}
c.WaitRaw = config.WaitRaw
}
if config.LogLevel != "" {
c.LogLevel = config.LogLevel
}
}
// 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 {
errs = multierror.Append(errs, err)
return nil, errs.ErrorOrNil()
}
// Parse the file (could be HCL or JSON)
var parsed interface{}
if err := hcl.Decode(&parsed, string(contents)); err != nil {
errs = multierror.Append(errs, err)
return nil, errs.ErrorOrNil()
}
// Create a new, empty config
config := &Config{}
// Use mapstructure to populate the basic config fields
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
ErrorUnused: true,
Metadata: nil,
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
// Parse the MaxStale component
if raw := config.MaxStaleRaw; raw != "" {
stale, err := time.ParseDuration(raw)
if err == nil {
config.MaxStale = stale
} else {
errs = multierror.Append(errs, fmt.Errorf("max_stale invalid: %v", err))
}
}
// Extract the last Auth block
if len(config.AuthRaw) > 0 {
config.Auth = config.AuthRaw[len(config.AuthRaw)-1]
}
// Extract the last SSL block
if len(config.SSLRaw) > 0 {
config.SSL = config.SSLRaw[len(config.SSLRaw)-1]
}
// Extract the last Syslog block
if len(config.SyslogRaw) > 0 {
config.Syslog = config.SyslogRaw[len(config.SyslogRaw)-1]
}
// Parse the Retry component
if raw := config.RetryRaw; raw != "" {
retry, err := time.ParseDuration(raw)
if err == nil {
config.Retry = retry
} else {
errs = multierror.Append(errs, fmt.Errorf("retry invalid: %v", err))
}
}
// Parse the Wait component
if raw := config.WaitRaw; raw != "" {
wait, err := watch.ParseWait(raw)
if err == nil {
config.Wait = wait
} else {
errs = multierror.Append(errs, fmt.Errorf("wait invalid: %v", err))
}
}
return config, errs.ErrorOrNil()
}
// DefaultConfig returns the default configuration struct.
func DefaultConfig() *Config {
logLevel := os.Getenv("CONSUL_TEMPLATE_LOG")
if logLevel == "" {
logLevel = "WARN"
}
return &Config{
Auth: &Auth{
Enabled: false,
},
SSL: &SSL{
Enabled: false,
Verify: true,
},
Syslog: &Syslog{
Enabled: false,
Facility: "LOCAL0",
},
ConfigTemplates: []*ConfigTemplate{},
Retry: 5 * time.Second,
Wait: &watch.Wait{},
LogLevel: logLevel,
}
}
// Auth is the HTTP basic authentication data.
type Auth struct {
Enabled bool `mapstructure:"enabled"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
}
// SSL is the configuration for SSL.
type SSL struct {
Enabled bool `mapstructure:"enabled"`
Verify bool `mapstructure:"verify"`
}
// Syslog is the configuration for syslog.
type Syslog struct {
Enabled bool `mapstructure:"enabled"`
Facility string `mapstructure:"facility"`
}
// ConfigTemplate is the representation of an input template, output location,
// and optional command to execute when rendered
type ConfigTemplate struct {
Source string `mapstructure:"source"`
Destination string `mapstructure:"destination"`
Command string `mapstructure:"command"`
}
// 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
}