forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
82 lines (74 loc) · 1.94 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
package provider
import (
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"github.com/containous/traefik/safe"
"github.com/containous/traefik/types"
"gopkg.in/fsnotify.v1"
)
// File holds configurations of the File provider.
type File struct {
BaseProvider `mapstructure:",squash"`
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *File) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error("Error creating file watcher", err)
return err
}
file, err := os.Open(provider.Filename)
if err != nil {
log.Error("Error opening file", err)
return err
}
defer file.Close()
if provider.Watch {
// Process events
pool.Go(func(stop chan bool) {
defer watcher.Close()
for {
select {
case <-stop:
return
case event := <-watcher.Events:
if strings.Contains(event.Name, file.Name()) {
log.Debug("File event:", event)
configuration := provider.loadFileConfig(file.Name())
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
}
}
case error := <-watcher.Errors:
log.Error("Watcher event error", error)
}
}
})
err = watcher.Add(filepath.Dir(file.Name()))
if err != nil {
log.Error("Error adding file watcher", err)
return err
}
}
configuration := provider.loadFileConfig(file.Name())
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
return nil
}
func (provider *File) loadFileConfig(filename string) *types.Configuration {
configuration := new(types.Configuration)
if _, err := toml.DecodeFile(filename, configuration); err != nil {
log.Error("Error reading file:", err)
return nil
}
return configuration
}