traefik/pkg/provider/file/file.go

631 lines
19 KiB
Go
Raw Permalink Normal View History

package file
import (
2019-03-27 14:02:06 +00:00
"bytes"
2018-11-14 09:18:03 +00:00
"context"
2019-04-01 13:30:07 +00:00
"errors"
"fmt"
"os"
"os/signal"
2024-02-09 10:08:05 +00:00
"path"
"path/filepath"
2015-09-07 15:39:22 +00:00
"strings"
"syscall"
"text/template"
2021-01-20 14:10:04 +00:00
"github.com/Masterminds/sprig/v3"
"github.com/fsnotify/fsnotify"
2022-11-21 17:36:05 +00:00
"github.com/rs/zerolog/log"
"github.com/traefik/paerser/file"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/config/dynamic"
"github.com/traefik/traefik/v3/pkg/logs"
"github.com/traefik/traefik/v3/pkg/provider"
"github.com/traefik/traefik/v3/pkg/safe"
"github.com/traefik/traefik/v3/pkg/tls"
"github.com/traefik/traefik/v3/pkg/types"
)
2018-11-14 09:18:03 +00:00
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 .yml or .toml files in a directory." json:"directory,omitempty" toml:"directory,omitempty" yaml:"directory,omitempty" export:"true"`
2019-07-01 09:30:05 +00:00
Watch bool `description:"Watch provider." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"`
2019-09-26 07:24:04 +00:00
Filename string `description:"Load dynamic configuration from a file." json:"filename,omitempty" toml:"filename,omitempty" yaml:"filename,omitempty" export:"true"`
2019-07-01 09:30:05 +00:00
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 = ""
}
2020-05-11 10:06:07 +00:00
// Init the provider.
func (p *Provider) Init() error {
2019-03-27 14:02:06 +00:00
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 {
logger := log.With().Str(logs.ProviderName, providerName).Logger()
if p.Watch {
2024-02-09 10:08:05 +00:00
var watchItems []string
2019-02-05 16:10:03 +00:00
switch {
case len(p.Directory) > 0:
2024-02-09 10:08:05 +00:00
watchItems = append(watchItems, p.Directory)
fileList, err := os.ReadDir(p.Directory)
if err != nil {
return fmt.Errorf("unable to read directory %s: %w", p.Directory, err)
}
for _, entry := range fileList {
if entry.IsDir() {
// ignore sub-dir
continue
}
watchItems = append(watchItems, path.Join(p.Directory, entry.Name()))
}
2019-02-05 16:10:03 +00:00
case len(p.Filename) > 0:
2024-02-09 10:08:05 +00:00
watchItems = append(watchItems, filepath.Dir(p.Filename), p.Filename)
2019-02-05 16:10:03 +00:00
default:
return errors.New("error using file configuration provider, neither filename nor directory is defined")
}
2024-02-13 08:46:53 +00:00
if err := p.addWatcher(pool, watchItems, configurationChan, p.applyConfiguration); err != nil {
return err
}
}
pool.GoCtx(func(ctx context.Context) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGHUP)
for {
select {
case <-ctx.Done():
return
// signals only receives SIGHUP events.
case <-signals:
if err := p.applyConfiguration(configurationChan); err != nil {
logger.Error().Err(err).Msg("Error while building configuration")
}
}
}
})
2023-01-02 13:55:45 +00:00
if err := p.applyConfiguration(configurationChan); err != nil {
if p.Watch {
logger.Err(err).Msg("Error while building configuration (for the first time)")
return nil
}
return err
}
return nil
}
2024-02-13 08:46:53 +00:00
func (p *Provider) addWatcher(pool *safe.Pool, items []string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message) error) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
2020-05-11 10:06:07 +00:00
return fmt.Errorf("error creating file watcher: %w", err)
}
2024-02-09 10:08:05 +00:00
for _, item := range items {
2024-02-13 08:46:53 +00:00
log.Debug().Msgf("add watcher on: %s", item)
2024-02-09 10:08:05 +00:00
err = watcher.Add(item)
if err != nil {
return fmt.Errorf("error adding file watcher: %w", err)
}
}
// Process events
pool.GoCtx(func(ctx context.Context) {
logger := log.With().Str(logs.ProviderName, providerName).Logger()
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 {
err := callback(configurationChan)
if err != nil {
logger.Error().Err(err).Msg("Error occurred during watcher callback")
}
}
} else {
err := callback(configurationChan)
if err != nil {
logger.Error().Err(err).Msg("Error occurred during watcher callback")
}
}
case err := <-watcher.Errors:
logger.Error().Err(err).Msg("Watcher event error")
}
2015-10-03 14:50:53 +00:00
}
})
return nil
}
// applyConfiguration builds the configuration and sends it to the given configurationChan.
func (p *Provider) applyConfiguration(configurationChan chan<- dynamic.Message) error {
configuration, err := p.buildConfiguration()
if err != nil {
return err
2017-11-21 09:24:03 +00:00
}
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().Str(logs.ProviderName, providerName).Logger().WithContext(context.Background())
2018-11-14 09:18:03 +00:00
if len(p.Directory) > 0 {
return p.loadFileConfigFromDirectory(ctx, p.Directory, nil)
2017-11-21 09:24:03 +00:00
}
if len(p.Filename) > 0 {
return p.loadFileConfig(ctx, p.Filename, true)
2017-11-21 09:24:03 +00:00
}
return nil, errors.New("error using file configuration provider, neither filename nor directory is defined")
2017-11-21 09:24:03 +00:00
}
func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration *dynamic.Configuration) {
configurationChan <- dynamic.Message{
ProviderName: "file",
Configuration: configuration,
}
}
2019-09-13 17:28:04 +00:00
func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) {
var err error
var configuration *dynamic.Configuration
if parseTemplate {
2019-09-13 17:28:04 +00:00
configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false)
} else {
configuration, err = p.DecodeConfiguration(filename)
}
if err != nil {
return nil, err
}
2018-11-14 09:18:03 +00:00
if configuration.TLS != nil {
2019-09-13 17:28:04 +00:00
configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS)
// TLS Options
if configuration.TLS.Options != nil {
for name, options := range configuration.TLS.Options {
var caCerts []types.FileOrContent
for _, caFile := range options.ClientAuth.CAFiles {
content, err := caFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
caCerts = append(caCerts, types.FileOrContent(content))
}
options.ClientAuth.CAFiles = caCerts
configuration.TLS.Options[name] = options
}
}
// TLS stores
if len(configuration.TLS.Stores) > 0 {
for name, store := range configuration.TLS.Stores {
if store.DefaultCertificate == nil {
continue
}
content, err := store.DefaultCertificate.CertFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
store.DefaultCertificate.CertFile = types.FileOrContent(content)
content, err = store.DefaultCertificate.KeyFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
store.DefaultCertificate.KeyFile = types.FileOrContent(content)
configuration.TLS.Stores[name] = store
}
}
}
// HTTP ServersTransport
if configuration.HTTP != nil && len(configuration.HTTP.ServersTransports) > 0 {
for name, st := range configuration.HTTP.ServersTransports {
var certificates []tls.Certificate
for _, cert := range st.Certificates {
content, err := cert.CertFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.CertFile = types.FileOrContent(content)
content, err = cert.KeyFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.KeyFile = types.FileOrContent(content)
certificates = append(certificates, cert)
}
configuration.HTTP.ServersTransports[name].Certificates = certificates
var rootCAs []types.FileOrContent
for _, rootCA := range st.RootCAs {
content, err := rootCA.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
rootCAs = append(rootCAs, types.FileOrContent(content))
}
st.RootCAs = rootCAs
}
}
// TCP ServersTransport
if configuration.TCP != nil && len(configuration.TCP.ServersTransports) > 0 {
for name, st := range configuration.TCP.ServersTransports {
var certificates []tls.Certificate
if st.TLS == nil {
continue
}
for _, cert := range st.TLS.Certificates {
content, err := cert.CertFile.Read()
if err != nil {
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.CertFile = types.FileOrContent(content)
content, err = cert.KeyFile.Read()
if err != nil {
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.KeyFile = types.FileOrContent(content)
certificates = append(certificates, cert)
}
configuration.TCP.ServersTransports[name].TLS.Certificates = certificates
var rootCAs []types.FileOrContent
for _, rootCA := range st.TLS.RootCAs {
content, err := rootCA.Read()
if err != nil {
log.Ctx(ctx).Error().Err(err).Send()
continue
}
rootCAs = append(rootCAs, types.FileOrContent(content))
}
st.TLS.RootCAs = rootCAs
}
}
return configuration, nil
}
2019-09-13 17:28:04 +00:00
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 {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.Certificate.CertFile = types.FileOrContent(string(content))
content, err = cert.Certificate.KeyFile.Read()
if err != nil {
2022-11-21 17:36:05 +00:00
log.Ctx(ctx).Error().Err(err).Send()
continue
}
cert.Certificate.KeyFile = types.FileOrContent(string(content))
certs = append(certs, cert)
}
return certs
}
func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) {
2021-03-04 19:08:03 +00:00
fileList, err := os.ReadDir(directory)
if err != nil {
2020-05-11 10:06:07 +00:00
return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err)
}
if configuration == nil {
configuration = &dynamic.Configuration{
HTTP: &dynamic.HTTPConfiguration{
2020-09-11 13:40:03 +00:00
Routers: make(map[string]*dynamic.Router),
Middlewares: make(map[string]*dynamic.Middleware),
Services: make(map[string]*dynamic.Service),
ServersTransports: make(map[string]*dynamic.ServersTransport),
},
TCP: &dynamic.TCPConfiguration{
Routers: make(map[string]*dynamic.TCPRouter),
Services: make(map[string]*dynamic.TCPService),
Middlewares: make(map[string]*dynamic.TCPMiddleware),
ServersTransports: make(map[string]*dynamic.TCPServersTransport),
},
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 {
2022-11-21 17:36:05 +00:00
logger := log.Ctx(ctx).With().Str("filename", item.Name()).Logger()
if item.IsDir() {
2022-11-21 17:36:05 +00:00
configuration, err = p.loadFileConfigFromDirectory(logger.WithContext(ctx), filepath.Join(directory, item.Name()), configuration)
if err != nil {
2020-05-11 10:06:07 +00:00
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
2022-11-21 17:36:05 +00:00
c, err = p.loadFileConfig(logger.WithContext(ctx), filepath.Join(directory, item.Name()), true)
if err != nil {
2020-05-11 10:06:07 +00:00
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 {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.RouterName, name).Msg("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 {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.MiddlewareName, name).Msg("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 {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.ServiceName, name).Msg("HTTP service already configured, skipping")
} else {
configuration.HTTP.Services[name] = conf
}
}
2020-09-11 13:40:03 +00:00
for name, conf := range c.HTTP.ServersTransports {
if _, exists := configuration.HTTP.ServersTransports[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.ServersTransportName, name).Msg("HTTP servers transport already configured, skipping")
2020-09-11 13:40:03 +00:00
} else {
configuration.HTTP.ServersTransports[name] = conf
}
}
for name, conf := range c.TCP.Routers {
if _, exists := configuration.TCP.Routers[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.RouterName, name).Msg("TCP router already configured, skipping")
} else {
configuration.TCP.Routers[name] = conf
2018-11-14 09:18:03 +00:00
}
}
2021-06-11 13:30:05 +00:00
for name, conf := range c.TCP.Middlewares {
if _, exists := configuration.TCP.Middlewares[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.MiddlewareName, name).Msg("TCP middleware already configured, skipping")
2021-06-11 13:30:05 +00:00
} else {
configuration.TCP.Middlewares[name] = conf
}
}
for name, conf := range c.TCP.Services {
if _, exists := configuration.TCP.Services[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.ServiceName, name).Msg("TCP service already configured, skipping")
2018-11-14 09:18:03 +00:00
} else {
configuration.TCP.Services[name] = conf
}
}
for name, conf := range c.TCP.ServersTransports {
if _, exists := configuration.TCP.ServersTransports[name]; exists {
logger.Warn().Str(logs.ServersTransportName, name).Msg("TCP servers transport already configured, skipping")
} else {
configuration.TCP.ServersTransports[name] = conf
}
}
for name, conf := range c.UDP.Routers {
if _, exists := configuration.UDP.Routers[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.RouterName, name).Msg("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 {
2022-11-21 17:36:05 +00:00
logger.Warn().Str(logs.ServiceName, name).Msg("UDP service already configured, skipping")
} else {
configuration.UDP.Services[name] = conf
}
}
for _, conf := range c.TLS.Certificates {
if _, exists := configTLSMaps[conf]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Msgf("TLS configuration %v already configured, skipping", conf)
} else {
configTLSMaps[conf] = struct{}{}
}
}
2019-07-18 14:26:05 +00:00
for name, conf := range c.TLS.Options {
if _, exists := configuration.TLS.Options[name]; exists {
2022-11-21 17:36:05 +00:00
logger.Warn().Msgf("TLS options %v already configured, skipping", name)
2019-07-18 14:26:05 +00:00
} 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 {
2022-11-21 17:36:05 +00:00
logger.Warn().Msgf("TLS store %v already configured, skipping", name)
2019-07-18 14:26:05 +00:00
} else {
if configuration.TLS.Stores == nil {
configuration.TLS.Stores = map[string]tls.Store{}
}
configuration.TLS.Stores[name] = conf
}
}
}
2018-11-14 09:18:03 +00:00
2019-07-18 14:26:05 +00:00
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
}
2019-03-27 14:02:06 +00:00
// CreateConfiguration creates a provider configuration from content using templating.
2019-09-13 17:28:04 +00:00
func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) {
tmplContent, err := readFile(filename)
if err != nil {
2020-05-11 10:06:07 +00:00
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
2020-07-07 12:42:03 +00:00
defaultFuncMap := sprig.TxtFuncMap()
2019-03-27 14:02:06 +00:00
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)
2019-03-27 14:02:06 +00:00
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, templateObjects)
if err != nil {
return nil, err
}
2020-07-07 12:42:03 +00:00
renderedTemplate := buffer.String()
2019-03-27 14:02:06 +00:00
if p.DebugLogGeneratedTemplate {
2022-11-21 17:36:05 +00:00
logger := log.Ctx(ctx)
logger.Debug().Msgf("Template content: %s", tmplContent)
logger.Debug().Msgf("Rendering results: %s", renderedTemplate)
2019-03-27 14:02:06 +00:00
}
return p.decodeConfiguration(filename, renderedTemplate)
2019-03-27 14:02:06 +00:00
}
// DecodeConfiguration Decodes a *types.Configuration from a content.
func (p *Provider) DecodeConfiguration(filename string) (*dynamic.Configuration, error) {
content, err := readFile(filename)
if err != nil {
2020-05-11 10:06:07 +00:00
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
return p.decodeConfiguration(filename, content)
}
2020-07-07 12:42:03 +00:00
func (p *Provider) decodeConfiguration(filePath, content string) (*dynamic.Configuration, error) {
configuration := &dynamic.Configuration{
HTTP: &dynamic.HTTPConfiguration{
2020-09-11 13:40:03 +00:00
Routers: make(map[string]*dynamic.Router),
Middlewares: make(map[string]*dynamic.Middleware),
Services: make(map[string]*dynamic.Service),
ServersTransports: make(map[string]*dynamic.ServersTransport),
2019-03-27 14:02:06 +00:00
},
TCP: &dynamic.TCPConfiguration{
Routers: make(map[string]*dynamic.TCPRouter),
Services: make(map[string]*dynamic.TCPService),
Middlewares: make(map[string]*dynamic.TCPMiddleware),
ServersTransports: make(map[string]*dynamic.TCPServersTransport),
2019-03-27 14:02:06 +00:00
},
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),
},
2019-03-27 14:02:06 +00:00
}
err := file.DecodeContent(content, strings.ToLower(filepath.Ext(filePath)), configuration)
if err != nil {
return nil, err
2019-03-27 14:02:06 +00:00
}
2019-03-27 14:02:06 +00:00
return configuration, nil
}
func readFile(filename string) (string, error) {
if len(filename) > 0 {
2021-03-04 19:08:03 +00:00
buf, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return string(buf), nil
}
return "", fmt.Errorf("invalid filename: %s", filename)
}