1
0
mirror of https://github.com/containous/traefik.git synced 2024-12-25 23:21:40 +03:00
traefik/provider/kv.go

119 lines
2.8 KiB
Go
Raw Normal View History

// Package provider holds the different provider implementation.
package provider
import (
"strings"
"text/template"
"time"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
"github.com/emilevauge/traefik/types"
)
// Kv holds common configurations of key-value providers.
type Kv struct {
2016-01-14 00:46:44 +03:00
BaseProvider `mapstructure:",squash"`
Endpoint string
Prefix string
storeType store.Backend
kvclient store.Store
}
func (provider *Kv) provide(configurationChan chan<- types.ConfigMessage) error {
kv, err := libkv.NewStore(
2016-01-14 00:46:44 +03:00
provider.storeType,
[]string{provider.Endpoint},
&store.Config{
ConnectionTimeout: 30 * time.Second,
2015-10-23 19:59:08 +03:00
Bucket: "traefik",
},
)
if err != nil {
return err
}
if _, err := kv.List(""); err != nil {
return err
}
provider.kvclient = kv
if provider.Watch {
stopCh := make(chan struct{})
chanKeys, err := kv.WatchTree(provider.Prefix, stopCh)
if err != nil {
return err
}
go func() {
for {
<-chanKeys
configuration := provider.loadConfig()
if configuration != nil {
configurationChan <- types.ConfigMessage{
2016-01-14 00:46:44 +03:00
ProviderName: string(provider.storeType),
Configuration: configuration,
}
}
defer close(stopCh)
}
}()
}
configuration := provider.loadConfig()
configurationChan <- types.ConfigMessage{
2016-01-14 00:46:44 +03:00
ProviderName: string(provider.storeType),
Configuration: configuration,
}
return nil
}
func (provider *Kv) loadConfig() *types.Configuration {
templateObjects := struct {
Prefix string
}{
provider.Prefix,
}
var KvFuncMap = template.FuncMap{
"List": provider.list,
"Get": provider.get,
"Last": provider.last,
}
configuration, err := provider.getConfiguration("templates/kv.tmpl", KvFuncMap, templateObjects)
if err != nil {
log.Error(err)
}
return configuration
}
func (provider *Kv) list(keys ...string) []string {
joinedKeys := strings.Join(keys, "")
keysPairs, err := provider.kvclient.List(joinedKeys)
if err != nil {
log.Error("Error getting keys: ", joinedKeys, err)
return nil
}
directoryKeys := make(map[string]string)
for _, key := range keysPairs {
directory := strings.Split(strings.TrimPrefix(key.Key, strings.TrimPrefix(joinedKeys, "/")), "/")[0]
directoryKeys[directory] = joinedKeys + directory
}
return fun.Values(directoryKeys).([]string)
}
func (provider *Kv) get(keys ...string) string {
joinedKeys := strings.Join(keys, "")
keyPair, err := provider.kvclient.Get(joinedKeys)
if err != nil {
log.Error("Error getting key: ", joinedKeys, err)
return ""
} else if keyPair == nil {
return ""
}
return string(keyPair.Value)
}
func (provider *Kv) last(key string) string {
splittedKey := strings.Split(key, "/")
return splittedKey[len(splittedKey)-1]
}