traefik/pkg/server/server.go

353 lines
11 KiB
Go
Raw Normal View History

package server
import (
2016-08-16 15:26:10 +00:00
"context"
"encoding/json"
"net/http"
"os"
"os/signal"
"sync"
"time"
2019-09-06 13:08:04 +00:00
"github.com/containous/traefik/v2/pkg/api"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/config/dynamic"
"github.com/containous/traefik/v2/pkg/config/runtime"
"github.com/containous/traefik/v2/pkg/config/static"
"github.com/containous/traefik/v2/pkg/log"
"github.com/containous/traefik/v2/pkg/metrics"
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
"github.com/containous/traefik/v2/pkg/middlewares/requestdecorator"
"github.com/containous/traefik/v2/pkg/provider"
"github.com/containous/traefik/v2/pkg/safe"
"github.com/containous/traefik/v2/pkg/tls"
"github.com/containous/traefik/v2/pkg/tracing"
"github.com/containous/traefik/v2/pkg/tracing/jaeger"
"github.com/containous/traefik/v2/pkg/types"
)
// Server is the reverse-proxy/load-balancer engine
type Server struct {
entryPointsTCP TCPEntryPoints
configurationChan chan dynamic.Message
configurationValidatedChan chan dynamic.Message
2018-11-14 09:18:03 +00:00
signals chan os.Signal
stopChan chan bool
currentConfigurations safe.Safe
providerConfigUpdateMap map[string]chan dynamic.Message
2018-11-14 09:18:03 +00:00
accessLoggerMiddleware *accesslog.Handler
tracer *tracing.Tracing
routinesPool *safe.Pool
defaultRoundTripper http.RoundTripper
metricsRegistry metrics.Registry
provider provider.Provider
configurationListeners []func(dynamic.Configuration)
2018-11-14 09:18:03 +00:00
requestDecorator *requestdecorator.RequestDecorator
providersThrottleDuration time.Duration
tlsManager *tls.Manager
2019-09-06 13:08:04 +00:00
api func(configuration *runtime.Configuration) http.Handler
restHandler http.Handler
2018-11-14 09:18:03 +00:00
}
// RouteAppenderFactory the route appender factory interface
type RouteAppenderFactory interface {
2019-09-06 13:08:04 +00:00
NewAppender(ctx context.Context, runtimeConfiguration *runtime.Configuration) types.RouteAppender
}
2019-06-27 22:16:04 +00:00
func setupTracing(conf *static.Tracing) tracing.Backend {
var backend tracing.Backend
if conf.Jaeger != nil {
backend = conf.Jaeger
}
if conf.Zipkin != nil {
if backend != nil {
log.WithoutContext().Error("Multiple tracing backend are not supported: cannot create Zipkin backend.")
} else {
backend = conf.Zipkin
}
}
2019-09-02 10:18:04 +00:00
if conf.Datadog != nil {
2019-06-27 22:16:04 +00:00
if backend != nil {
2019-09-02 10:18:04 +00:00
log.WithoutContext().Error("Multiple tracing backend are not supported: cannot create Datadog backend.")
2019-06-27 22:16:04 +00:00
} else {
2019-09-02 10:18:04 +00:00
backend = conf.Datadog
2019-06-27 22:16:04 +00:00
}
}
if conf.Instana != nil {
if backend != nil {
log.WithoutContext().Error("Multiple tracing backend are not supported: cannot create Instana backend.")
} else {
backend = conf.Instana
}
2018-11-14 09:18:03 +00:00
}
2019-06-27 22:16:04 +00:00
if conf.Haystack != nil {
if backend != nil {
log.WithoutContext().Error("Multiple tracing backend are not supported: cannot create Haystack backend.")
} else {
backend = conf.Haystack
}
}
if backend == nil {
log.WithoutContext().Debug("Could not initialize tracing, use Jaeger by default")
2019-10-28 11:26:05 +00:00
bcd := &jaeger.Config{}
bcd.SetDefaults()
backend = bcd
2019-06-27 22:16:04 +00:00
}
return backend
2018-11-14 09:18:03 +00:00
}
// NewServer returns an initialized Server.
func NewServer(staticConfiguration static.Configuration, provider provider.Provider, entryPoints TCPEntryPoints, tlsManager *tls.Manager) *Server {
2018-06-11 09:36:03 +00:00
server := &Server{}
2019-09-06 13:08:04 +00:00
if staticConfiguration.API != nil {
server.api = api.NewBuilder(staticConfiguration)
}
if staticConfiguration.Providers != nil && staticConfiguration.Providers.Rest != nil {
server.restHandler = staticConfiguration.Providers.Rest.Handler()
}
server.provider = provider
server.entryPointsTCP = entryPoints
server.configurationChan = make(chan dynamic.Message, 100)
server.configurationValidatedChan = make(chan dynamic.Message, 100)
server.signals = make(chan os.Signal, 1)
server.stopChan = make(chan bool, 1)
server.configureSignals()
currentConfigurations := make(dynamic.Configurations)
server.currentConfigurations.Set(currentConfigurations)
server.providerConfigUpdateMap = make(map[string]chan dynamic.Message)
server.tlsManager = tlsManager
2018-11-14 09:18:03 +00:00
if staticConfiguration.Providers != nil {
server.providersThrottleDuration = time.Duration(staticConfiguration.Providers.ProvidersThrottleDuration)
}
transport, err := createHTTPTransport(staticConfiguration.ServersTransport)
2018-11-14 09:18:03 +00:00
if err != nil {
log.WithoutContext().Errorf("Could not configure HTTP Transport, fallbacking on default transport: %v", err)
2018-11-14 09:18:03 +00:00
server.defaultRoundTripper = http.DefaultTransport
} else {
server.defaultRoundTripper = transport
}
2018-06-11 09:36:03 +00:00
server.routinesPool = safe.NewPool(context.Background())
2018-06-11 09:36:03 +00:00
if staticConfiguration.Tracing != nil {
2019-06-27 22:16:04 +00:00
tracingBackend := setupTracing(staticConfiguration.Tracing)
if tracingBackend != nil {
server.tracer, err = tracing.NewTracing(staticConfiguration.Tracing.ServiceName, staticConfiguration.Tracing.SpanNameLimit, tracingBackend)
if err != nil {
log.WithoutContext().Warnf("Unable to create tracer: %v", err)
}
2018-11-14 09:18:03 +00:00
}
2018-06-11 09:36:03 +00:00
}
server.requestDecorator = requestdecorator.New(staticConfiguration.HostResolver)
server.metricsRegistry = registerMetricClients(staticConfiguration.Metrics)
if staticConfiguration.AccessLog != nil {
2017-05-25 11:25:53 +00:00
var err error
server.accessLoggerMiddleware, err = accesslog.NewHandler(staticConfiguration.AccessLog)
2017-05-25 11:25:53 +00:00
if err != nil {
2018-11-14 09:18:03 +00:00
log.WithoutContext().Warnf("Unable to create access logger : %v", err)
2017-05-25 11:25:53 +00:00
}
2017-05-22 19:39:29 +00:00
}
return server
}
// Start starts the server and Stop/Close it when context is Done
func (s *Server) Start(ctx context.Context) {
go func() {
defer s.Close()
<-ctx.Done()
logger := log.FromContext(ctx)
logger.Info("I have to go...")
logger.Info("Stopping server gracefully")
s.Stop()
}()
s.startTCPServers()
2017-11-24 18:18:03 +00:00
s.routinesPool.Go(func(stop chan bool) {
s.listenProviders(stop)
})
2017-11-24 18:18:03 +00:00
s.routinesPool.Go(func(stop chan bool) {
s.listenConfigurations(stop)
})
s.startProvider()
2018-09-06 12:24:03 +00:00
s.routinesPool.Go(func(stop chan bool) {
s.listenSignals(stop)
})
}
// Wait blocks until server is shutted down.
2017-11-24 18:18:03 +00:00
func (s *Server) Wait() {
<-s.stopChan
}
// Stop stops the server
2017-11-24 18:18:03 +00:00
func (s *Server) Stop() {
2018-11-14 09:18:03 +00:00
defer log.WithoutContext().Info("Server stopped")
var wg sync.WaitGroup
for epn, ep := range s.entryPointsTCP {
wg.Add(1)
go func(entryPointName string, entryPoint *TCPEntryPoint) {
ctx := log.With(context.Background(), log.Str(log.EntryPointName, entryPointName))
defer wg.Done()
2018-11-14 09:18:03 +00:00
entryPoint.Shutdown(ctx)
2018-11-14 09:18:03 +00:00
log.FromContext(ctx).Debugf("Entry point %s closed", entryPointName)
}(epn, ep)
}
wg.Wait()
2017-11-24 18:18:03 +00:00
s.stopChan <- true
}
// Close destroys the server
2017-11-24 18:18:03 +00:00
func (s *Server) Close() {
2018-03-14 12:14:03 +00:00
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
go func(ctx context.Context) {
<-ctx.Done()
if ctx.Err() == context.Canceled {
return
} else if ctx.Err() == context.DeadlineExceeded {
2018-03-14 12:14:03 +00:00
panic("Timeout while stopping traefik, killing instance ✝")
}
}(ctx)
2018-11-14 09:18:03 +00:00
stopMetricsClients()
2017-11-24 18:18:03 +00:00
s.routinesPool.Cleanup()
close(s.configurationChan)
close(s.configurationValidatedChan)
signal.Stop(s.signals)
close(s.signals)
close(s.stopChan)
2018-11-14 09:18:03 +00:00
2017-11-24 18:18:03 +00:00
if s.accessLoggerMiddleware != nil {
if err := s.accessLoggerMiddleware.Close(); err != nil {
2018-11-14 09:18:03 +00:00
log.WithoutContext().Errorf("Could not close the access log file: %s", err)
2017-05-22 19:39:29 +00:00
}
}
2018-11-14 09:18:03 +00:00
if s.tracer != nil {
s.tracer.Close()
}
cancel()
}
func (s *Server) startTCPServers() {
// Use an empty configuration in order to initialize the default handlers with internal routes
routers := s.loadConfigurationTCP(dynamic.Configurations{})
for entryPointName, router := range routers {
s.entryPointsTCP[entryPointName].switchRouter(router)
}
2017-01-12 13:34:54 +00:00
for entryPointName, serverEntryPoint := range s.entryPointsTCP {
ctx := log.With(context.Background(), log.Str(log.EntryPointName, entryPointName))
go serverEntryPoint.startTCP(ctx)
}
}
2017-11-24 18:18:03 +00:00
func (s *Server) listenProviders(stop chan bool) {
for {
select {
case <-stop:
return
2017-11-24 18:18:03 +00:00
case configMsg, ok := <-s.configurationChan:
if !ok {
return
}
if configMsg.Configuration != nil {
s.preLoadConfiguration(configMsg)
} else {
2019-09-13 17:28:04 +00:00
log.WithoutContext().WithField(log.ProviderName, configMsg.ProviderName).
Debug("Received nil configuration from provider, skipping.")
}
}
}
}
2018-03-05 19:54:04 +00:00
// AddListener adds a new listener function used when new configuration is provided
func (s *Server) AddListener(listener func(dynamic.Configuration)) {
2018-03-05 19:54:04 +00:00
if s.configurationListeners == nil {
s.configurationListeners = make([]func(dynamic.Configuration), 0)
2018-03-05 19:54:04 +00:00
}
s.configurationListeners = append(s.configurationListeners, listener)
}
func (s *Server) startProvider() {
2019-09-13 17:28:04 +00:00
logger := log.WithoutContext()
jsonConf, err := json.Marshal(s.provider)
if err != nil {
2019-09-13 17:28:04 +00:00
logger.Debugf("Unable to marshal provider configuration %T: %v", s.provider, err)
}
2018-11-14 09:18:03 +00:00
2019-09-13 17:28:04 +00:00
logger.Infof("Starting provider %T %s", s.provider, jsonConf)
currentProvider := s.provider
2018-11-14 09:18:03 +00:00
safe.Go(func() {
err := currentProvider.Provide(s.configurationChan, s.routinesPool)
if err != nil {
2019-09-13 17:28:04 +00:00
logger.Errorf("Error starting provider %T: %s", s.provider, err)
}
})
}
func registerMetricClients(metricsConfig *types.Metrics) metrics.Registry {
if metricsConfig == nil {
return metrics.NewVoidRegistry()
}
2018-01-31 18:10:04 +00:00
var registries []metrics.Registry
2018-11-14 09:18:03 +00:00
if metricsConfig.Prometheus != nil {
2018-11-14 09:18:03 +00:00
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "prometheus"))
prometheusRegister := metrics.RegisterPrometheus(ctx, metricsConfig.Prometheus)
2018-08-06 12:58:03 +00:00
if prometheusRegister != nil {
registries = append(registries, prometheusRegister)
2018-11-14 09:18:03 +00:00
log.FromContext(ctx).Debug("Configured Prometheus metrics")
2018-08-06 12:58:03 +00:00
}
}
2018-11-14 09:18:03 +00:00
2019-09-02 10:18:04 +00:00
if metricsConfig.Datadog != nil {
2018-11-14 09:18:03 +00:00
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "datadog"))
2019-09-02 10:18:04 +00:00
registries = append(registries, metrics.RegisterDatadog(ctx, metricsConfig.Datadog))
log.FromContext(ctx).Debugf("Configured Datadog metrics: pushing to %s once every %s",
metricsConfig.Datadog.Address, metricsConfig.Datadog.PushInterval)
}
2018-11-14 09:18:03 +00:00
if metricsConfig.StatsD != nil {
2018-11-14 09:18:03 +00:00
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "statsd"))
registries = append(registries, metrics.RegisterStatsd(ctx, metricsConfig.StatsD))
log.FromContext(ctx).Debugf("Configured StatsD metrics: pushing to %s once every %s",
metricsConfig.StatsD.Address, metricsConfig.StatsD.PushInterval)
2017-04-18 06:22:06 +00:00
}
2018-11-14 09:18:03 +00:00
if metricsConfig.InfluxDB != nil {
2018-11-14 09:18:03 +00:00
ctx := log.With(context.Background(), log.Str(log.MetricsProviderName, "influxdb"))
registries = append(registries, metrics.RegisterInfluxDB(ctx, metricsConfig.InfluxDB))
log.FromContext(ctx).Debugf("Configured InfluxDB metrics: pushing to %s once every %s",
metricsConfig.InfluxDB.Address, metricsConfig.InfluxDB.PushInterval)
}
2017-04-18 06:22:06 +00:00
return metrics.NewMultiRegistry(registries)
}
func stopMetricsClients() {
metrics.StopDatadog()
metrics.StopStatsd()
metrics.StopInfluxDB()
}