traefik/provider/file.go

85 lines
2 KiB
Go
Raw Normal View History

package provider
import (
2015-09-07 17:39:22 +02:00
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
"github.com/containous/traefik/log"
"github.com/containous/traefik/safe"
"github.com/containous/traefik/types"
"gopkg.in/fsnotify.v1"
)
var _ Provider = (*File)(nil)
// File holds configurations of the File provider.
type File struct {
2016-06-24 09:58:42 +02:00
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, constraints types.Constraints) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
2015-09-11 16:37:13 +02:00
log.Error("Error creating file watcher", err)
return err
}
2015-09-07 17:39:22 +02:00
file, err := os.Open(provider.Filename)
if err != nil {
2015-09-11 16:37:13 +02:00
log.Error("Error opening file", err)
return err
}
2015-09-07 17:39:22 +02:00
defer file.Close()
2015-10-03 16:50:53 +02:00
if provider.Watch {
// Process events
pool.Go(func(stop chan bool) {
2015-10-03 16:50:53 +02:00
defer watcher.Close()
for {
select {
case <-stop:
return
2015-10-03 16:50:53 +02:00
case event := <-watcher.Events:
if strings.Contains(event.Name, file.Name()) {
log.Debug("File event:", event)
configuration := provider.loadFileConfig(file.Name())
2015-10-03 16:50:53 +02:00
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
2015-10-03 16:50:53 +02:00
}
2015-09-07 23:25:07 +02:00
}
2015-10-03 16:50:53 +02:00
case error := <-watcher.Errors:
log.Error("Watcher event error", error)
2015-09-07 17:39:22 +02:00
}
}
})
2015-09-07 18:10:33 +02:00
err = watcher.Add(filepath.Dir(file.Name()))
2015-10-03 16:50:53 +02:00
if err != nil {
log.Error("Error adding file watcher", err)
return err
}
2015-09-07 17:39:22 +02:00
}
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)
2015-09-08 00:15:14 +02:00
if _, err := toml.DecodeFile(filename, configuration); err != nil {
2015-09-11 16:37:13 +02:00
log.Error("Error reading file:", err)
return nil
}
2015-09-08 00:15:14 +02:00
return configuration
2015-09-12 15:10:03 +02:00
}