-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
file.go
450 lines (383 loc) · 13.3 KB
/
file.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
package file
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/BurntSushi/toml"
"github.com/Masterminds/sprig"
"github.com/containous/traefik/v2/pkg/config/dynamic"
"github.com/containous/traefik/v2/pkg/log"
"github.com/containous/traefik/v2/pkg/provider"
"github.com/containous/traefik/v2/pkg/safe"
"github.com/containous/traefik/v2/pkg/tls"
"gopkg.in/fsnotify.v1"
"gopkg.in/yaml.v2"
)
const providerName = "file"
var _ provider.Provider = (*Provider)(nil)
// Provider holds configurations of the provider.
type Provider struct {
Directory string `description:"Load dynamic configuration from one or more .toml or .yml files in a directory." json:"directory,omitempty" toml:"directory,omitempty" yaml:"directory,omitempty" export:"true"`
Watch bool `description:"Watch provider." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"`
Filename string `description:"Load dynamic configuration from a file." json:"filename,omitempty" toml:"filename,omitempty" yaml:"filename,omitempty" export:"true"`
DebugLogGeneratedTemplate bool `description:"Enable debug logging of generated configuration template." json:"debugLogGeneratedTemplate,omitempty" toml:"debugLogGeneratedTemplate,omitempty" yaml:"debugLogGeneratedTemplate,omitempty" export:"true"`
}
// SetDefaults sets the default values.
func (p *Provider) SetDefaults() {
p.Watch = true
p.Filename = ""
}
// Init the provider.
func (p *Provider) Init() error {
return nil
}
// Provide allows the file provider to provide configurations to traefik
// using the given configuration channel.
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
configuration, err := p.BuildConfiguration()
if err != nil {
return err
}
if p.Watch {
var watchItem string
switch {
case len(p.Directory) > 0:
watchItem = p.Directory
case len(p.Filename) > 0:
watchItem = filepath.Dir(p.Filename)
default:
return errors.New("error using file configuration provider, neither filename or directory defined")
}
if err := p.addWatcher(pool, watchItem, configurationChan, p.watcherCallback); err != nil {
return err
}
}
sendConfigToChannel(configurationChan, configuration)
return nil
}
// BuildConfiguration loads configuration either from file or a directory
// specified by 'Filename'/'Directory' and returns a 'Configuration' object.
func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) {
ctx := log.With(context.Background(), log.Str(log.ProviderName, providerName))
if len(p.Directory) > 0 {
return p.loadFileConfigFromDirectory(ctx, p.Directory, nil)
}
if len(p.Filename) > 0 {
return p.loadFileConfig(ctx, p.Filename, true)
}
return nil, errors.New("error using file configuration provider, neither filename or directory defined")
}
func (p *Provider) addWatcher(pool *safe.Pool, directory string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message, fsnotify.Event)) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("error creating file watcher: %w", err)
}
err = watcher.Add(directory)
if err != nil {
return fmt.Errorf("error adding file watcher: %w", err)
}
// Process events
pool.GoCtx(func(ctx context.Context) {
defer watcher.Close()
for {
select {
case <-ctx.Done():
return
case evt := <-watcher.Events:
if p.Directory == "" {
_, evtFileName := filepath.Split(evt.Name)
_, confFileName := filepath.Split(p.Filename)
if evtFileName == confFileName {
callback(configurationChan, evt)
}
} else {
callback(configurationChan, evt)
}
case err := <-watcher.Errors:
log.WithoutContext().WithField(log.ProviderName, providerName).Errorf("Watcher event error: %s", err)
}
}
})
return nil
}
func (p *Provider) watcherCallback(configurationChan chan<- dynamic.Message, event fsnotify.Event) {
watchItem := p.Filename
if len(p.Directory) > 0 {
watchItem = p.Directory
}
logger := log.WithoutContext().WithField(log.ProviderName, providerName)
if _, err := os.Stat(watchItem); err != nil {
logger.Errorf("Unable to watch %s : %v", watchItem, err)
return
}
configuration, err := p.BuildConfiguration()
if err != nil {
logger.Errorf("Error occurred during watcher callback: %s", err)
return
}
sendConfigToChannel(configurationChan, configuration)
}
func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration *dynamic.Configuration) {
configurationChan <- dynamic.Message{
ProviderName: "file",
Configuration: configuration,
}
}
func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) {
var err error
var configuration *dynamic.Configuration
if parseTemplate {
configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false)
} else {
configuration, err = p.DecodeConfiguration(filename)
}
if err != nil {
return nil, err
}
if configuration.TLS != nil {
configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS)
}
return configuration, nil
}
func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores {
var certs []*tls.CertAndStores
for _, cert := range tlsConfig.Certificates {
content, err := cert.Certificate.CertFile.Read()
if err != nil {
log.FromContext(ctx).Error(err)
continue
}
cert.Certificate.CertFile = tls.FileOrContent(string(content))
content, err = cert.Certificate.KeyFile.Read()
if err != nil {
log.FromContext(ctx).Error(err)
continue
}
cert.Certificate.KeyFile = tls.FileOrContent(string(content))
certs = append(certs, cert)
}
return certs
}
func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) {
fileList, err := ioutil.ReadDir(directory)
if err != nil {
return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err)
}
if configuration == nil {
configuration = &dynamic.Configuration{
HTTP: &dynamic.HTTPConfiguration{
Routers: make(map[string]*dynamic.Router),
Middlewares: make(map[string]*dynamic.Middleware),
Services: make(map[string]*dynamic.Service),
},
TCP: &dynamic.TCPConfiguration{
Routers: make(map[string]*dynamic.TCPRouter),
Services: make(map[string]*dynamic.TCPService),
},
TLS: &dynamic.TLSConfiguration{
Stores: make(map[string]tls.Store),
Options: make(map[string]tls.Options),
},
UDP: &dynamic.UDPConfiguration{
Routers: make(map[string]*dynamic.UDPRouter),
Services: make(map[string]*dynamic.UDPService),
},
}
}
configTLSMaps := make(map[*tls.CertAndStores]struct{})
for _, item := range fileList {
logger := log.FromContext(log.With(ctx, log.Str("filename", item.Name())))
if item.IsDir() {
configuration, err = p.loadFileConfigFromDirectory(ctx, filepath.Join(directory, item.Name()), configuration)
if err != nil {
return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %w", item, err)
}
continue
}
switch strings.ToLower(filepath.Ext(item.Name())) {
case ".toml", ".yaml", ".yml":
// noop
default:
continue
}
var c *dynamic.Configuration
c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true)
if err != nil {
return configuration, fmt.Errorf("%s: %w", filepath.Join(directory, item.Name()), err)
}
for name, conf := range c.HTTP.Routers {
if _, exists := configuration.HTTP.Routers[name]; exists {
logger.WithField(log.RouterName, name).Warn("HTTP router already configured, skipping")
} else {
configuration.HTTP.Routers[name] = conf
}
}
for name, conf := range c.HTTP.Middlewares {
if _, exists := configuration.HTTP.Middlewares[name]; exists {
logger.WithField(log.MiddlewareName, name).Warn("HTTP middleware already configured, skipping")
} else {
configuration.HTTP.Middlewares[name] = conf
}
}
for name, conf := range c.HTTP.Services {
if _, exists := configuration.HTTP.Services[name]; exists {
logger.WithField(log.ServiceName, name).Warn("HTTP service already configured, skipping")
} else {
configuration.HTTP.Services[name] = conf
}
}
for name, conf := range c.TCP.Routers {
if _, exists := configuration.TCP.Routers[name]; exists {
logger.WithField(log.RouterName, name).Warn("TCP router already configured, skipping")
} else {
configuration.TCP.Routers[name] = conf
}
}
for name, conf := range c.TCP.Services {
if _, exists := configuration.TCP.Services[name]; exists {
logger.WithField(log.ServiceName, name).Warn("TCP service already configured, skipping")
} else {
configuration.TCP.Services[name] = conf
}
}
for name, conf := range c.UDP.Routers {
if _, exists := configuration.UDP.Routers[name]; exists {
logger.WithField(log.RouterName, name).Warn("UDP router already configured, skipping")
} else {
configuration.UDP.Routers[name] = conf
}
}
for name, conf := range c.UDP.Services {
if _, exists := configuration.UDP.Services[name]; exists {
logger.WithField(log.ServiceName, name).Warn("UDP service already configured, skipping")
} else {
configuration.UDP.Services[name] = conf
}
}
for _, conf := range c.TLS.Certificates {
if _, exists := configTLSMaps[conf]; exists {
logger.Warnf("TLS configuration %v already configured, skipping", conf)
} else {
configTLSMaps[conf] = struct{}{}
}
}
for name, conf := range c.TLS.Options {
if _, exists := configuration.TLS.Options[name]; exists {
logger.Warnf("TLS options %v already configured, skipping", name)
} else {
if configuration.TLS.Options == nil {
configuration.TLS.Options = map[string]tls.Options{}
}
configuration.TLS.Options[name] = conf
}
}
for name, conf := range c.TLS.Stores {
if _, exists := configuration.TLS.Stores[name]; exists {
logger.Warnf("TLS store %v already configured, skipping", name)
} else {
if configuration.TLS.Stores == nil {
configuration.TLS.Stores = map[string]tls.Store{}
}
configuration.TLS.Stores[name] = conf
}
}
}
if len(configTLSMaps) > 0 && configuration.TLS == nil {
configuration.TLS = &dynamic.TLSConfiguration{}
}
for conf := range configTLSMaps {
configuration.TLS.Certificates = append(configuration.TLS.Certificates, conf)
}
return configuration, nil
}
// CreateConfiguration creates a provider configuration from content using templating.
func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) {
tmplContent, err := readFile(filename)
if err != nil {
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
defaultFuncMap := sprig.TxtFuncMap()
defaultFuncMap["normalize"] = provider.Normalize
defaultFuncMap["split"] = strings.Split
for funcID, funcElement := range funcMap {
defaultFuncMap[funcID] = funcElement
}
tmpl := template.New(p.Filename).Funcs(defaultFuncMap)
_, err = tmpl.Parse(tmplContent)
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, templateObjects)
if err != nil {
return nil, err
}
renderedTemplate := buffer.String()
if p.DebugLogGeneratedTemplate {
logger := log.FromContext(ctx)
logger.Debugf("Template content: %s", tmplContent)
logger.Debugf("Rendering results: %s", renderedTemplate)
}
return p.decodeConfiguration(filename, renderedTemplate)
}
// DecodeConfiguration Decodes a *types.Configuration from a content.
func (p *Provider) DecodeConfiguration(filename string) (*dynamic.Configuration, error) {
content, err := readFile(filename)
if err != nil {
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
return p.decodeConfiguration(filename, content)
}
func (p *Provider) decodeConfiguration(filePath, content string) (*dynamic.Configuration, error) {
configuration := &dynamic.Configuration{
HTTP: &dynamic.HTTPConfiguration{
Routers: make(map[string]*dynamic.Router),
Middlewares: make(map[string]*dynamic.Middleware),
Services: make(map[string]*dynamic.Service),
},
TCP: &dynamic.TCPConfiguration{
Routers: make(map[string]*dynamic.TCPRouter),
Services: make(map[string]*dynamic.TCPService),
},
TLS: &dynamic.TLSConfiguration{
Stores: make(map[string]tls.Store),
Options: make(map[string]tls.Options),
},
UDP: &dynamic.UDPConfiguration{
Routers: make(map[string]*dynamic.UDPRouter),
Services: make(map[string]*dynamic.UDPService),
},
}
switch strings.ToLower(filepath.Ext(filePath)) {
case ".toml":
_, err := toml.Decode(content, configuration)
if err != nil {
return nil, err
}
case ".yml", ".yaml":
var err error
err = yaml.Unmarshal([]byte(content), configuration)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported file extension: %s", filePath)
}
return configuration, nil
}
func readFile(filename string) (string, error) {
if len(filename) > 0 {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return "", err
}
return string(buf), nil
}
return "", fmt.Errorf("invalid filename: %s", filename)
}