fix: logger and context.
This commit is contained in:
parent
b4c7b90c9e
commit
8e18d37b3d
52 changed files with 231 additions and 183 deletions
|
@ -46,7 +46,7 @@ func (s *AccessLogSuite) SetUpSuite(c *check.C) {
|
||||||
|
|
||||||
func (s *AccessLogSuite) TearDownTest(c *check.C) {
|
func (s *AccessLogSuite) TearDownTest(c *check.C) {
|
||||||
displayTraefikLogFile(c, traefikTestLogFile)
|
displayTraefikLogFile(c, traefikTestLogFile)
|
||||||
os.Remove(traefikTestAccessLogFile)
|
_ = os.Remove(traefikTestAccessLogFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *AccessLogSuite) TestAccessLog(c *check.C) {
|
func (s *AccessLogSuite) TestAccessLog(c *check.C) {
|
||||||
|
@ -59,7 +59,7 @@ func (s *AccessLogSuite) TestAccessLog(c *check.C) {
|
||||||
defer func() {
|
defer func() {
|
||||||
traefikLog, err := ioutil.ReadFile(traefikTestLogFile)
|
traefikLog, err := ioutil.ReadFile(traefikTestLogFile)
|
||||||
c.Assert(err, checker.IsNil)
|
c.Assert(err, checker.IsNil)
|
||||||
log.Info(string(traefikLog))
|
log.WithoutContext().Info(string(traefikLog))
|
||||||
}()
|
}()
|
||||||
|
|
||||||
err := cmd.Start()
|
err := cmd.Start()
|
||||||
|
@ -233,7 +233,7 @@ func digestParts(resp *http.Response) map[string]string {
|
||||||
func getMD5(data string) string {
|
func getMD5(data string) string {
|
||||||
digest := md5.New()
|
digest := md5.New()
|
||||||
if _, err := digest.Write([]byte(data)); err != nil {
|
if _, err := digest.Write([]byte(data)); err != nil {
|
||||||
log.Error(err)
|
log.WithoutContext().Error(err)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%x", digest.Sum(nil))
|
return fmt.Sprintf("%x", digest.Sum(nil))
|
||||||
}
|
}
|
||||||
|
@ -241,7 +241,7 @@ func getMD5(data string) string {
|
||||||
func getCnonce() string {
|
func getCnonce() string {
|
||||||
b := make([]byte, 8)
|
b := make([]byte, 8)
|
||||||
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
if _, err := io.ReadFull(rand.Reader, b); err != nil {
|
||||||
log.Error(err)
|
log.WithoutContext().Error(err)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("%x", b)[:16]
|
return fmt.Sprintf("%x", b)[:16]
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,6 +15,8 @@ type handler struct{}
|
||||||
// Simplified version of the Challenge Test Server from Boulder
|
// Simplified version of the Challenge Test Server from Boulder
|
||||||
// https://github.com/letsencrypt/boulder/blob/a6597b9f120207eff192c3e4107a7e49972a0250/test/challtestsrv/dnsone.go#L40
|
// https://github.com/letsencrypt/boulder/blob/a6597b9f120207eff192c3e4107a7e49972a0250/test/challtestsrv/dnsone.go#L40
|
||||||
func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||||
|
logger := log.WithoutContext()
|
||||||
|
|
||||||
m := new(dns.Msg)
|
m := new(dns.Msg)
|
||||||
m.SetReply(r)
|
m.SetReply(r)
|
||||||
m.Compress = false
|
m.Compress = false
|
||||||
|
@ -23,8 +25,9 @@ func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||||
if fakeDNS == "" {
|
if fakeDNS == "" {
|
||||||
fakeDNS = "127.0.0.1"
|
fakeDNS = "127.0.0.1"
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, q := range r.Question {
|
for _, q := range r.Question {
|
||||||
log.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype])
|
logger.Infof("Query -- [%s] %s", q.Name, dns.TypeToString[q.Qtype])
|
||||||
|
|
||||||
switch q.Qtype {
|
switch q.Qtype {
|
||||||
case dns.TypeA:
|
case dns.TypeA:
|
||||||
|
@ -94,7 +97,7 @@ func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
|
||||||
m.Ns = append(m.Ns, auth)
|
m.Ns = append(m.Ns, auth)
|
||||||
|
|
||||||
if err := w.WriteMsg(m); err != nil {
|
if err := w.WriteMsg(m); err != nil {
|
||||||
log.Fatalf("Failed to write message %v", err)
|
logger.Fatalf("Failed to write message %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -106,9 +109,9 @@ func startFakeDNSServer() *dns.Server {
|
||||||
}
|
}
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Infof("Start a fake DNS server.")
|
log.WithoutContext().Infof("Start a fake DNS server.")
|
||||||
if err := srv.ListenAndServe(); err != nil {
|
if err := srv.ListenAndServe(); err != nil {
|
||||||
log.Fatalf("Failed to set udp listener %v", err)
|
log.WithoutContext().Fatalf("Failed to set udp listener %v", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
|
|
@ -50,7 +50,7 @@ func (s *myserver) StreamExample(in *helloworld.StreamExampleRequest, server hel
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := server.Send(&helloworld.StreamExampleReply{Data: string(data)}); err != nil {
|
if err := server.Send(&helloworld.StreamExampleReply{Data: string(data)}); err != nil {
|
||||||
log.Error(err)
|
log.WithoutContext().Error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
<-s.stopStreamExample
|
<-s.stopStreamExample
|
||||||
|
|
|
@ -28,7 +28,7 @@ var showLog = flag.Bool("tlog", false, "always show Traefik logs")
|
||||||
|
|
||||||
func Test(t *testing.T) {
|
func Test(t *testing.T) {
|
||||||
if !*integration {
|
if !*integration {
|
||||||
log.Info("Integration tests disabled.")
|
log.WithoutContext().Info("Integration tests disabled.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -91,7 +91,7 @@ func (s *BaseSuite) createComposeProject(c *check.C, name string) {
|
||||||
ip, _, err := net.ParseCIDR(addr.String())
|
ip, _, err := net.ParseCIDR(addr.String())
|
||||||
c.Assert(err, checker.IsNil)
|
c.Assert(err, checker.IsNil)
|
||||||
if !ip.IsLoopback() && ip.To4() != nil {
|
if !ip.IsLoopback() && ip.To4() != nil {
|
||||||
os.Setenv("DOCKER_HOST_IP", ip.String())
|
_ = os.Setenv("DOCKER_HOST_IP", ip.String())
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -35,7 +35,7 @@ func Collect(staticConfiguration *static.Configuration) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig)
|
log.WithoutContext().Infof("Anonymous stats sent to %s: %s", collectorURL, anonConfig)
|
||||||
|
|
||||||
hashConf, err := hashstructure.Hash(staticConfiguration, nil)
|
hashConf, err := hashstructure.Hash(staticConfiguration, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -238,13 +238,15 @@ func getSafeACMECAServer(caServerSrc string) string {
|
||||||
|
|
||||||
if strings.HasPrefix(caServerSrc, "https://acme-v01.api.letsencrypt.org") {
|
if strings.HasPrefix(caServerSrc, "https://acme-v01.api.letsencrypt.org") {
|
||||||
caServer := strings.Replace(caServerSrc, "v01", "v02", 1)
|
caServer := strings.Replace(caServerSrc, "v01", "v02", 1)
|
||||||
log.Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer)
|
log.WithoutContext().
|
||||||
|
Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer)
|
||||||
return caServer
|
return caServer
|
||||||
}
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(caServerSrc, "https://acme-staging.api.letsencrypt.org") {
|
if strings.HasPrefix(caServerSrc, "https://acme-staging.api.letsencrypt.org") {
|
||||||
caServer := strings.Replace(caServerSrc, "https://acme-staging.api.letsencrypt.org", "https://acme-staging-v02.api.letsencrypt.org", 1)
|
caServer := strings.Replace(caServerSrc, "https://acme-staging.api.letsencrypt.org", "https://acme-staging-v02.api.letsencrypt.org", 1)
|
||||||
log.Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer)
|
log.WithoutContext().
|
||||||
|
Warnf("The CA server %[1]q refers to a v01 endpoint of the ACME API, please change to %[2]q. Fallback to %[2]q.", caServerSrc, caServer)
|
||||||
return caServer
|
return caServer
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -122,37 +122,41 @@ func (hc *HealthCheck) SetBackendsConfiguration(parentCtx context.Context, backe
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) execute(ctx context.Context, backend *BackendConfig) {
|
func (hc *HealthCheck) execute(ctx context.Context, backend *BackendConfig) {
|
||||||
log.Debugf("Initial health check for backend: %q", backend.name)
|
logger := log.FromContext(ctx)
|
||||||
hc.checkBackend(backend)
|
logger.Debugf("Initial health check for backend: %q", backend.name)
|
||||||
|
|
||||||
|
hc.checkBackend(ctx, backend)
|
||||||
ticker := time.NewTicker(backend.Interval)
|
ticker := time.NewTicker(backend.Interval)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.Debugf("Stopping current health check goroutines of backend: %s", backend.name)
|
logger.Debugf("Stopping current health check goroutines of backend: %s", backend.name)
|
||||||
return
|
return
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
log.Debugf("Refreshing health check for backend: %s", backend.name)
|
logger.Debugf("Refreshing health check for backend: %s", backend.name)
|
||||||
hc.checkBackend(backend)
|
hc.checkBackend(ctx, backend)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (hc *HealthCheck) checkBackend(backend *BackendConfig) {
|
func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig) {
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
|
|
||||||
enabledURLs := backend.LB.Servers()
|
enabledURLs := backend.LB.Servers()
|
||||||
var newDisabledURLs []backendURL
|
var newDisabledURLs []backendURL
|
||||||
// FIXME re enable metrics
|
// FIXME re enable metrics
|
||||||
for _, disableURL := range backend.disabledURLs {
|
for _, disableURL := range backend.disabledURLs {
|
||||||
// FIXME serverUpMetricValue := float64(0)
|
// FIXME serverUpMetricValue := float64(0)
|
||||||
if err := checkHealth(disableURL.url, backend); err == nil {
|
if err := checkHealth(disableURL.url, backend); err == nil {
|
||||||
log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d",
|
logger.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d",
|
||||||
backend.name, disableURL.url.String(), disableURL.weight)
|
backend.name, disableURL.url.String(), disableURL.weight)
|
||||||
if err = backend.LB.UpsertServer(disableURL.url, roundrobin.Weight(disableURL.weight)); err != nil {
|
if err = backend.LB.UpsertServer(disableURL.url, roundrobin.Weight(disableURL.weight)); err != nil {
|
||||||
log.Error(err)
|
logger.Error(err)
|
||||||
}
|
}
|
||||||
// FIXME serverUpMetricValue = 1
|
// FIXME serverUpMetricValue = 1
|
||||||
} else {
|
} else {
|
||||||
log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.url.String(), err)
|
logger.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.url.String(), err)
|
||||||
newDisabledURLs = append(newDisabledURLs, disableURL)
|
newDisabledURLs = append(newDisabledURLs, disableURL)
|
||||||
}
|
}
|
||||||
// FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()}
|
// FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()}
|
||||||
|
@ -173,9 +177,9 @@ func (hc *HealthCheck) checkBackend(backend *BackendConfig) {
|
||||||
weight = 1
|
weight = 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Weight: %d Reason: %s", backend.name, enableURL.String(), weight, err)
|
logger.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Weight: %d Reason: %s", backend.name, enableURL.String(), weight, err)
|
||||||
if err := backend.LB.RemoveServer(enableURL); err != nil {
|
if err := backend.LB.RemoveServer(enableURL); err != nil {
|
||||||
log.Error(err)
|
logger.Error(err)
|
||||||
}
|
}
|
||||||
backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight})
|
backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight})
|
||||||
// FIXME serverUpMetricValue = 0
|
// FIXME serverUpMetricValue = 0
|
||||||
|
@ -244,10 +248,10 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewLBStatusUpdater returns a new LbStatusUpdater
|
// NewLBStatusUpdater returns a new LbStatusUpdater
|
||||||
func NewLBStatusUpdater(bh BalancerHandler, svinfo *runtime.ServiceInfo) *LbStatusUpdater {
|
func NewLBStatusUpdater(bh BalancerHandler, info *runtime.ServiceInfo) *LbStatusUpdater {
|
||||||
return &LbStatusUpdater{
|
return &LbStatusUpdater{
|
||||||
BalancerHandler: bh,
|
BalancerHandler: bh,
|
||||||
serviceInfo: svinfo,
|
serviceInfo: info,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -62,12 +62,6 @@ func Panic(args ...interface{}) {
|
||||||
mainLogger.Panic(args...)
|
mainLogger.Panic(args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Panicf logs a message at level Panic on the standard logger.
|
|
||||||
// Deprecated
|
|
||||||
func Panicf(format string, args ...interface{}) {
|
|
||||||
mainLogger.Panicf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fatal logs a message at level Fatal on the standard logger.
|
// Fatal logs a message at level Fatal on the standard logger.
|
||||||
// Deprecated
|
// Deprecated
|
||||||
func Fatal(args ...interface{}) {
|
func Fatal(args ...interface{}) {
|
||||||
|
|
|
@ -12,4 +12,5 @@ const (
|
||||||
MetricsProviderName = "metricsProviderName"
|
MetricsProviderName = "metricsProviderName"
|
||||||
TracingProviderName = "tracingProviderName"
|
TracingProviderName = "tracingProviderName"
|
||||||
ServerName = "serverName"
|
ServerName = "serverName"
|
||||||
|
TLSStoreName = "tlsStoreName"
|
||||||
)
|
)
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -24,7 +25,7 @@ type addPrefix struct {
|
||||||
|
|
||||||
// New creates a new handler.
|
// New creates a new handler.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.AddPrefix, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
var result *addPrefix
|
var result *addPrefix
|
||||||
|
|
||||||
if len(config.Prefix) > 0 {
|
if len(config.Prefix) > 0 {
|
||||||
|
@ -45,7 +46,7 @@ func (ap *addPrefix) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ap *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (ap *addPrefix) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), ap.name, typeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), ap.name, typeName))
|
||||||
|
|
||||||
oldURLPath := req.URL.Path
|
oldURLPath := req.URL.Path
|
||||||
req.URL.Path = ap.prefix + req.URL.Path
|
req.URL.Path = ap.prefix + req.URL.Path
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
|
|
||||||
goauth "github.com/abbot/go-http-auth"
|
goauth "github.com/abbot/go-http-auth"
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
|
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
|
@ -30,7 +31,7 @@ type basicAuth struct {
|
||||||
|
|
||||||
// NewBasic creates a basicAuth middleware.
|
// NewBasic creates a basicAuth middleware.
|
||||||
func NewBasic(ctx context.Context, next http.Handler, authConfig dynamic.BasicAuth, name string) (http.Handler, error) {
|
func NewBasic(ctx context.Context, next http.Handler, authConfig dynamic.BasicAuth, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, basicTypeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, basicTypeName)).Debug("Creating middleware")
|
||||||
users, err := getUsers(authConfig.UsersFile, authConfig.Users, basicUserParser)
|
users, err := getUsers(authConfig.UsersFile, authConfig.Users, basicUserParser)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -58,7 +59,7 @@ func (b *basicAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (b *basicAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), b.name, basicTypeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), b.name, basicTypeName))
|
||||||
|
|
||||||
if username := b.auth.CheckAuth(req); username == "" {
|
if username := b.auth.CheckAuth(req); username == "" {
|
||||||
logger.Debug("Authentication failed")
|
logger.Debug("Authentication failed")
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
|
|
||||||
goauth "github.com/abbot/go-http-auth"
|
goauth "github.com/abbot/go-http-auth"
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
|
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
|
@ -30,7 +31,7 @@ type digestAuth struct {
|
||||||
|
|
||||||
// NewDigest creates a digest auth middleware.
|
// NewDigest creates a digest auth middleware.
|
||||||
func NewDigest(ctx context.Context, next http.Handler, authConfig dynamic.DigestAuth, name string) (http.Handler, error) {
|
func NewDigest(ctx context.Context, next http.Handler, authConfig dynamic.DigestAuth, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, digestTypeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, digestTypeName)).Debug("Creating middleware")
|
||||||
users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser)
|
users, err := getUsers(authConfig.UsersFile, authConfig.Users, digestUserParser)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
@ -58,7 +59,7 @@ func (d *digestAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (d *digestAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), d.name, digestTypeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), d.name, digestTypeName))
|
||||||
|
|
||||||
if username, _ := d.auth.CheckAuth(req); username == "" {
|
if username, _ := d.auth.CheckAuth(req); username == "" {
|
||||||
logger.Debug("Digest authentication failed")
|
logger.Debug("Digest authentication failed")
|
||||||
|
|
|
@ -10,6 +10,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -34,7 +35,7 @@ type forwardAuth struct {
|
||||||
|
|
||||||
// NewForward creates a forward auth middleware.
|
// NewForward creates a forward auth middleware.
|
||||||
func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAuth, name string) (http.Handler, error) {
|
func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAuth, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, forwardedTypeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, forwardedTypeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
fa := &forwardAuth{
|
fa := &forwardAuth{
|
||||||
address: config.Address,
|
address: config.Address,
|
||||||
|
@ -61,7 +62,7 @@ func (fa *forwardAuth) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), fa.name, forwardedTypeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), fa.name, forwardedTypeName))
|
||||||
|
|
||||||
// Ensure our request client does not follow redirects
|
// Ensure our request client does not follow redirects
|
||||||
httpClient := http.Client{
|
httpClient := http.Client{
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -22,7 +23,7 @@ type buffer struct {
|
||||||
|
|
||||||
// New creates a buffering middleware.
|
// New creates a buffering middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.Buffering, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.Buffering, name string) (http.Handler, error) {
|
||||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
logger.Debugf("Setting up buffering: request limits: %d (mem), %d (max), response limits: %d (mem), %d (max) with retry: '%s'",
|
logger.Debugf("Setting up buffering: request limits: %d (mem), %d (max), response limits: %d (mem), %d (max) with retry: '%s'",
|
||||||
config.MemRequestBodyBytes, config.MaxRequestBodyBytes, config.MemResponseBodyBytes, config.MaxResponseBodyBytes, config.RetryExpression)
|
config.MemRequestBodyBytes, config.MaxRequestBodyBytes, config.MemResponseBodyBytes, config.MaxResponseBodyBytes, config.RetryExpression)
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
|
|
||||||
"github.com/containous/alice"
|
"github.com/containous/alice"
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -19,7 +20,7 @@ type chainBuilder interface {
|
||||||
|
|
||||||
// New creates a chain middleware
|
// New creates a chain middleware
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
middlewareChain := builder.BuildChain(ctx, config.Middlewares)
|
middlewareChain := builder.BuildChain(ctx, config.Middlewares)
|
||||||
return middlewareChain.Then(next)
|
return middlewareChain.Then(next)
|
||||||
|
|
|
@ -25,7 +25,7 @@ type circuitBreaker struct {
|
||||||
func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) {
|
||||||
expression := confCircuitBreaker.Expression
|
expression := confCircuitBreaker.Expression
|
||||||
|
|
||||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
logger.Debug("Setting up with expression: %s", expression)
|
logger.Debug("Setting up with expression: %s", expression)
|
||||||
|
|
||||||
|
@ -56,6 +56,5 @@ func (c *circuitBreaker) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *circuitBreaker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (c *circuitBreaker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
middlewares.GetLogger(req.Context(), c.name, typeName).Debug("Entering middleware")
|
|
||||||
c.circuitBreaker.ServeHTTP(rw, req)
|
c.circuitBreaker.ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,10 +7,10 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/NYTimes/gziphandler"
|
"github.com/NYTimes/gziphandler"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -25,7 +25,7 @@ type compress struct {
|
||||||
|
|
||||||
// New creates a new compress middleware.
|
// New creates a new compress middleware.
|
||||||
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &compress{
|
return &compress{
|
||||||
next: next,
|
next: next,
|
||||||
|
@ -38,7 +38,8 @@ func (c *compress) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
if strings.HasPrefix(contentType, "application/grpc") {
|
if strings.HasPrefix(contentType, "application/grpc") {
|
||||||
c.next.ServeHTTP(rw, req)
|
c.next.ServeHTTP(rw, req)
|
||||||
} else {
|
} else {
|
||||||
gzipHandler(c.next, middlewares.GetLogger(req.Context(), c.name, typeName)).ServeHTTP(rw, req)
|
ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName)
|
||||||
|
gzipHandler(ctx, c.next).ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -46,12 +47,12 @@ func (c *compress) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
return c.name, tracing.SpanKindNoneEnum
|
return c.name, tracing.SpanKindNoneEnum
|
||||||
}
|
}
|
||||||
|
|
||||||
func gzipHandler(h http.Handler, logger logrus.FieldLogger) http.Handler {
|
func gzipHandler(ctx context.Context, h http.Handler) http.Handler {
|
||||||
wrapper, err := gziphandler.GzipHandlerWithOpts(
|
wrapper, err := gziphandler.GzipHandlerWithOpts(
|
||||||
gziphandler.CompressionLevel(gzip.DefaultCompression),
|
gziphandler.CompressionLevel(gzip.DefaultCompression),
|
||||||
gziphandler.MinSize(gziphandler.DefaultMinSize))
|
gziphandler.MinSize(gziphandler.DefaultMinSize))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error(err)
|
log.FromContext(ctx).Error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return wrapper(h)
|
return wrapper(h)
|
||||||
|
|
|
@ -12,6 +12,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/containous/traefik/v2/pkg/types"
|
"github.com/containous/traefik/v2/pkg/types"
|
||||||
|
@ -43,7 +44,7 @@ type customErrors struct {
|
||||||
|
|
||||||
// New creates a new custom error pages middleware.
|
// New creates a new custom error pages middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.ErrorPage, serviceBuilder serviceBuilder, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.ErrorPage, serviceBuilder serviceBuilder, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status)
|
httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -69,7 +70,8 @@ func (c *customErrors) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
|
ctx := middlewares.GetLoggerCtx(req.Context(), c.name, typeName)
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
|
|
||||||
if c.backendHandler == nil {
|
if c.backendHandler == nil {
|
||||||
logger.Error("Error pages: no backend handler.")
|
logger.Error("Error pages: no backend handler.")
|
||||||
|
@ -78,7 +80,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
recorder := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName))
|
recorder := newResponseRecorder(ctx, rw)
|
||||||
c.next.ServeHTTP(recorder, req)
|
c.next.ServeHTTP(recorder, req)
|
||||||
|
|
||||||
// check the recorder code against the configured http status code ranges
|
// check the recorder code against the configured http status code ranges
|
||||||
|
@ -103,7 +105,7 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
recorderErrorPage := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName))
|
recorderErrorPage := newResponseRecorder(ctx, rw)
|
||||||
utils.CopyHeaders(pageReq.Header, req.Header)
|
utils.CopyHeaders(pageReq.Header, req.Header)
|
||||||
|
|
||||||
c.backendHandler.ServeHTTP(recorderErrorPage, pageReq.WithContext(req.Context()))
|
c.backendHandler.ServeHTTP(recorderErrorPage, pageReq.WithContext(req.Context()))
|
||||||
|
@ -151,13 +153,13 @@ type responseRecorder interface {
|
||||||
}
|
}
|
||||||
|
|
||||||
// newResponseRecorder returns an initialized responseRecorder.
|
// newResponseRecorder returns an initialized responseRecorder.
|
||||||
func newResponseRecorder(rw http.ResponseWriter, logger logrus.FieldLogger) responseRecorder {
|
func newResponseRecorder(ctx context.Context, rw http.ResponseWriter) responseRecorder {
|
||||||
recorder := &responseRecorderWithoutCloseNotify{
|
recorder := &responseRecorderWithoutCloseNotify{
|
||||||
HeaderMap: make(http.Header),
|
HeaderMap: make(http.Header),
|
||||||
Body: new(bytes.Buffer),
|
Body: new(bytes.Buffer),
|
||||||
Code: http.StatusOK,
|
Code: http.StatusOK,
|
||||||
responseWriter: rw,
|
responseWriter: rw,
|
||||||
logger: logger,
|
logger: log.FromContext(ctx),
|
||||||
}
|
}
|
||||||
if _, ok := rw.(http.CloseNotifier); ok {
|
if _, ok := rw.(http.CloseNotifier); ok {
|
||||||
return &responseRecorderWithCloseNotify{recorder}
|
return &responseRecorderWithCloseNotify{recorder}
|
||||||
|
|
|
@ -8,7 +8,6 @@ import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
|
||||||
"github.com/containous/traefik/v2/pkg/testhelpers"
|
"github.com/containous/traefik/v2/pkg/testhelpers"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
@ -151,7 +150,7 @@ func TestNewResponseRecorder(t *testing.T) {
|
||||||
t.Run(test.desc, func(t *testing.T) {
|
t.Run(test.desc, func(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
rec := newResponseRecorder(test.rw, middlewares.GetLogger(context.Background(), "test", typeName))
|
rec := newResponseRecorder(context.Background(), test.rw)
|
||||||
assert.IsType(t, rec, test.expected)
|
assert.IsType(t, rec, test.expected)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -27,8 +28,9 @@ type headers struct {
|
||||||
// New creates a Headers middleware.
|
// New creates a Headers middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.Headers, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.Headers, name string) (http.Handler, error) {
|
||||||
// HeaderMiddleware -> SecureMiddleWare -> next
|
// HeaderMiddleware -> SecureMiddleWare -> next
|
||||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
|
|
||||||
hasSecureHeaders := config.HasSecureHeadersDefined()
|
hasSecureHeaders := config.HasSecureHeadersDefined()
|
||||||
hasCustomHeaders := config.HasCustomHeadersDefined()
|
hasCustomHeaders := config.HasCustomHeadersDefined()
|
||||||
hasCorsHeaders := config.HasCorsHeadersDefined()
|
hasCorsHeaders := config.HasCorsHeadersDefined()
|
||||||
|
|
|
@ -8,10 +8,10 @@ import (
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
"github.com/containous/traefik/v2/pkg/ip"
|
"github.com/containous/traefik/v2/pkg/ip"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -28,7 +28,7 @@ type ipWhiteLister struct {
|
||||||
|
|
||||||
// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist
|
// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) {
|
||||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
|
|
||||||
if len(config.SourceRange) == 0 {
|
if len(config.SourceRange) == 0 {
|
||||||
|
@ -46,6 +46,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, nam
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Debugf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange)
|
logger.Debugf("Setting up IPWhiteLister with sourceRange: %s", config.SourceRange)
|
||||||
|
|
||||||
return &ipWhiteLister{
|
return &ipWhiteLister{
|
||||||
strategy: strategy,
|
strategy: strategy,
|
||||||
whiteLister: checker,
|
whiteLister: checker,
|
||||||
|
@ -59,14 +60,15 @@ func (wl *ipWhiteLister) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), wl.name, typeName)
|
ctx := middlewares.GetLoggerCtx(req.Context(), wl.name, typeName)
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
|
|
||||||
err := wl.whiteLister.IsAuthorized(wl.strategy.GetIP(req))
|
err := wl.whiteLister.IsAuthorized(wl.strategy.GetIP(req))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logMessage := fmt.Sprintf("rejecting request %+v: %v", req, err)
|
logMessage := fmt.Sprintf("rejecting request %+v: %v", req, err)
|
||||||
logger.Debug(logMessage)
|
logger.Debug(logMessage)
|
||||||
tracing.SetErrorWithEvent(req, logMessage)
|
tracing.SetErrorWithEvent(req, logMessage)
|
||||||
reject(logger, rw)
|
reject(ctx, rw)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
logger.Debugf("Accept %s: %+v", wl.strategy.GetIP(req), req)
|
logger.Debugf("Accept %s: %+v", wl.strategy.GetIP(req), req)
|
||||||
|
@ -74,12 +76,12 @@ func (wl *ipWhiteLister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
wl.next.ServeHTTP(rw, req)
|
wl.next.ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func reject(logger logrus.FieldLogger, rw http.ResponseWriter) {
|
func reject(ctx context.Context, rw http.ResponseWriter) {
|
||||||
statusCode := http.StatusForbidden
|
statusCode := http.StatusForbidden
|
||||||
|
|
||||||
rw.WriteHeader(statusCode)
|
rw.WriteHeader(statusCode)
|
||||||
_, err := rw.Write([]byte(http.StatusText(statusCode)))
|
_, err := rw.Write([]byte(http.StatusText(statusCode)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error(err)
|
log.FromContext(ctx).Error(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -39,7 +39,7 @@ type metricsMiddleware struct {
|
||||||
|
|
||||||
// NewEntryPointMiddleware creates a new metrics middleware for an Entrypoint.
|
// NewEntryPointMiddleware creates a new metrics middleware for an Entrypoint.
|
||||||
func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, entryPointName string) http.Handler {
|
func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, entryPointName string) http.Handler {
|
||||||
middlewares.GetLogger(ctx, nameEntrypoint, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, nameEntrypoint, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &metricsMiddleware{
|
return &metricsMiddleware{
|
||||||
next: next,
|
next: next,
|
||||||
|
@ -52,7 +52,7 @@ func NewEntryPointMiddleware(ctx context.Context, next http.Handler, registry me
|
||||||
|
|
||||||
// NewServiceMiddleware creates a new metrics middleware for a Service.
|
// NewServiceMiddleware creates a new metrics middleware for a Service.
|
||||||
func NewServiceMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, serviceName string) http.Handler {
|
func NewServiceMiddleware(ctx context.Context, next http.Handler, registry metrics.Registry, serviceName string) http.Handler {
|
||||||
middlewares.GetLogger(ctx, nameService, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, nameService, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &metricsMiddleware{
|
return &metricsMiddleware{
|
||||||
next: next,
|
next: next,
|
||||||
|
|
|
@ -4,10 +4,9 @@ import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/log"
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetLogger creates a logger configured with the middleware fields.
|
// GetLoggerCtx creates a logger context with the middleware fields.
|
||||||
func GetLogger(ctx context.Context, middleware string, middlewareType string) logrus.FieldLogger {
|
func GetLoggerCtx(ctx context.Context, middleware string, middlewareType string) context.Context {
|
||||||
return log.FromContext(ctx).WithField(log.MiddlewareName, middleware).WithField(log.MiddlewareType, middlewareType)
|
return log.With(ctx, log.Str(log.MiddlewareName, middleware), log.Str(log.MiddlewareType, middlewareType))
|
||||||
}
|
}
|
||||||
|
|
|
@ -16,7 +16,6 @@ import (
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -66,7 +65,7 @@ type passTLSClientCert struct {
|
||||||
|
|
||||||
// New constructs a new PassTLSClientCert instance from supplied frontend header struct.
|
// New constructs a new PassTLSClientCert instance from supplied frontend header struct.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.PassTLSClientCert, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.PassTLSClientCert, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &passTLSClientCert{
|
return &passTLSClientCert{
|
||||||
next: next,
|
next: next,
|
||||||
|
@ -104,11 +103,13 @@ func (p *passTLSClientCert) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
logger := middlewares.GetLogger(req.Context(), p.name, typeName)
|
ctx := middlewares.GetLoggerCtx(req.Context(), p.name, typeName)
|
||||||
p.modifyRequestHeaders(logger, req)
|
|
||||||
|
p.modifyRequestHeaders(ctx, req)
|
||||||
p.next.ServeHTTP(rw, req)
|
p.next.ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name) string {
|
|
||||||
|
func getDNInfo(ctx context.Context, prefix string, options *DistinguishedNameOptions, cs *pkix.Name) string {
|
||||||
if options == nil {
|
if options == nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
@ -124,27 +125,27 @@ func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.CountryName {
|
if options.CountryName {
|
||||||
writeParts(content, cs.Country, "C")
|
writeParts(ctx, content, cs.Country, "C")
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.StateOrProvinceName {
|
if options.StateOrProvinceName {
|
||||||
writeParts(content, cs.Province, "ST")
|
writeParts(ctx, content, cs.Province, "ST")
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.LocalityName {
|
if options.LocalityName {
|
||||||
writeParts(content, cs.Locality, "L")
|
writeParts(ctx, content, cs.Locality, "L")
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.OrganizationName {
|
if options.OrganizationName {
|
||||||
writeParts(content, cs.Organization, "O")
|
writeParts(ctx, content, cs.Organization, "O")
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.SerialNumber {
|
if options.SerialNumber {
|
||||||
writePart(content, cs.SerialNumber, "SN")
|
writePart(ctx, content, cs.SerialNumber, "SN")
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.CommonName {
|
if options.CommonName {
|
||||||
writePart(content, cs.CommonName, "CN")
|
writePart(ctx, content, cs.CommonName, "CN")
|
||||||
}
|
}
|
||||||
|
|
||||||
if content.Len() > 0 {
|
if content.Len() > 0 {
|
||||||
|
@ -154,24 +155,24 @@ func getDNInfo(prefix string, options *DistinguishedNameOptions, cs *pkix.Name)
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeParts(content io.StringWriter, entries []string, prefix string) {
|
func writeParts(ctx context.Context, content io.StringWriter, entries []string, prefix string) {
|
||||||
for _, entry := range entries {
|
for _, entry := range entries {
|
||||||
writePart(content, entry, prefix)
|
writePart(ctx, content, entry, prefix)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func writePart(content io.StringWriter, entry string, prefix string) {
|
func writePart(ctx context.Context, content io.StringWriter, entry string, prefix string) {
|
||||||
if len(entry) > 0 {
|
if len(entry) > 0 {
|
||||||
_, err := content.WriteString(fmt.Sprintf("%s=%s,", prefix, entry))
|
_, err := content.WriteString(fmt.Sprintf("%s=%s,", prefix, entry))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.FromContext(ctx).Error(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// getXForwardedTLSClientCertInfo Build a string with the wanted client certificates information
|
// getXForwardedTLSClientCertInfo Build a string with the wanted client certificates information
|
||||||
// like Subject="C=%s,ST=%s,L=%s,O=%s,CN=%s",NB=%d,NA=%d,SAN=%s;
|
// like Subject="C=%s,ST=%s,L=%s,O=%s,CN=%s",NB=%d,NA=%d,SAN=%s;
|
||||||
func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certificate) string {
|
func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(ctx context.Context, certs []*x509.Certificate) string {
|
||||||
var headerValues []string
|
var headerValues []string
|
||||||
|
|
||||||
for _, peerCert := range certs {
|
for _, peerCert := range certs {
|
||||||
|
@ -181,12 +182,12 @@ func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certifi
|
||||||
var na string
|
var na string
|
||||||
|
|
||||||
if p.info != nil {
|
if p.info != nil {
|
||||||
subject := getDNInfo("Subject", p.info.subject, &peerCert.Subject)
|
subject := getDNInfo(ctx, "Subject", p.info.subject, &peerCert.Subject)
|
||||||
if len(subject) > 0 {
|
if len(subject) > 0 {
|
||||||
values = append(values, subject)
|
values = append(values, subject)
|
||||||
}
|
}
|
||||||
|
|
||||||
issuer := getDNInfo("Issuer", p.info.issuer, &peerCert.Issuer)
|
issuer := getDNInfo(ctx, "Issuer", p.info.issuer, &peerCert.Issuer)
|
||||||
if len(issuer) > 0 {
|
if len(issuer) > 0 {
|
||||||
values = append(values, issuer)
|
values = append(values, issuer)
|
||||||
}
|
}
|
||||||
|
@ -217,10 +218,12 @@ func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(certs []*x509.Certifi
|
||||||
}
|
}
|
||||||
|
|
||||||
// modifyRequestHeaders set the wanted headers with the certificates information.
|
// modifyRequestHeaders set the wanted headers with the certificates information.
|
||||||
func (p *passTLSClientCert) modifyRequestHeaders(logger logrus.FieldLogger, r *http.Request) {
|
func (p *passTLSClientCert) modifyRequestHeaders(ctx context.Context, r *http.Request) {
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
|
|
||||||
if p.pem {
|
if p.pem {
|
||||||
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
|
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
|
||||||
r.Header.Set(xForwardedTLSClientCert, getXForwardedTLSClientCert(logger, r.TLS.PeerCertificates))
|
r.Header.Set(xForwardedTLSClientCert, getXForwardedTLSClientCert(ctx, r.TLS.PeerCertificates))
|
||||||
} else {
|
} else {
|
||||||
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
||||||
}
|
}
|
||||||
|
@ -228,7 +231,7 @@ func (p *passTLSClientCert) modifyRequestHeaders(logger logrus.FieldLogger, r *h
|
||||||
|
|
||||||
if p.info != nil {
|
if p.info != nil {
|
||||||
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
|
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
|
||||||
headerContent := p.getXForwardedTLSClientCertInfo(r.TLS.PeerCertificates)
|
headerContent := p.getXForwardedTLSClientCertInfo(ctx, r.TLS.PeerCertificates)
|
||||||
r.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
|
r.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
|
||||||
} else {
|
} else {
|
||||||
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
|
||||||
|
@ -248,22 +251,22 @@ func sanitize(cert []byte) string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// extractCertificate extract the certificate from the request.
|
// extractCertificate extract the certificate from the request.
|
||||||
func extractCertificate(logger logrus.FieldLogger, cert *x509.Certificate) string {
|
func extractCertificate(ctx context.Context, cert *x509.Certificate) string {
|
||||||
b := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
|
b := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
|
||||||
certPEM := pem.EncodeToMemory(&b)
|
certPEM := pem.EncodeToMemory(&b)
|
||||||
if certPEM == nil {
|
if certPEM == nil {
|
||||||
logger.Error("Cannot extract the certificate content")
|
log.FromContext(ctx).Error("Cannot extract the certificate content")
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return sanitize(certPEM)
|
return sanitize(certPEM)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getXForwardedTLSClientCert Build a string with the client certificates.
|
// getXForwardedTLSClientCert Build a string with the client certificates.
|
||||||
func getXForwardedTLSClientCert(logger logrus.FieldLogger, certs []*x509.Certificate) string {
|
func getXForwardedTLSClientCert(ctx context.Context, certs []*x509.Certificate) string {
|
||||||
var headerValues []string
|
var headerValues []string
|
||||||
|
|
||||||
for _, peerCert := range certs {
|
for _, peerCert := range certs {
|
||||||
headerValues = append(headerValues, extractCertificate(logger, peerCert))
|
headerValues = append(headerValues, extractCertificate(ctx, peerCert))
|
||||||
}
|
}
|
||||||
|
|
||||||
return strings.Join(headerValues, ",")
|
return strings.Join(headerValues, ",")
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -20,7 +21,7 @@ type pipelining struct {
|
||||||
|
|
||||||
// New returns a new pipelining instance
|
// New returns a new pipelining instance
|
||||||
func New(ctx context.Context, next http.Handler, name string) http.Handler {
|
func New(ctx context.Context, next http.Handler, name string) http.Handler {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &pipelining{
|
return &pipelining{
|
||||||
next: next,
|
next: next,
|
||||||
|
|
|
@ -90,7 +90,8 @@ func (rl *rateLimiter) GetTracingInformation() (string, ext.SpanKindEnum) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
logger := middlewares.GetLogger(r.Context(), rl.name, typeName)
|
ctx := middlewares.GetLoggerCtx(r.Context(), rl.name, typeName)
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
|
|
||||||
source, amount, err := rl.sourceMatcher.Extract(r)
|
source, amount, err := rl.sourceMatcher.Extract(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -127,7 +128,7 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
delay := res.Delay()
|
delay := res.Delay()
|
||||||
if delay > rl.maxDelay {
|
if delay > rl.maxDelay {
|
||||||
res.Cancel()
|
res.Cancel()
|
||||||
rl.serveDelayError(w, r, delay)
|
rl.serveDelayError(ctx, w, r, delay)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -135,12 +136,12 @@ func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
rl.next.ServeHTTP(w, r)
|
rl.next.ServeHTTP(w, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (rl *rateLimiter) serveDelayError(w http.ResponseWriter, r *http.Request, delay time.Duration) {
|
func (rl *rateLimiter) serveDelayError(ctx context.Context, w http.ResponseWriter, r *http.Request, delay time.Duration) {
|
||||||
w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
|
w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds()))
|
||||||
w.Header().Set("X-Retry-In", delay.String())
|
w.Header().Set("X-Retry-In", delay.String())
|
||||||
w.WriteHeader(http.StatusTooManyRequests)
|
w.WriteHeader(http.StatusTooManyRequests)
|
||||||
|
|
||||||
if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil {
|
if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil {
|
||||||
middlewares.GetLogger(r.Context(), rl.name, typeName).Errorf("could not serve 429: %v", err)
|
log.FromContext(ctx).Errorf("could not serve 429: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -4,8 +4,8 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/sirupsen/logrus"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -19,7 +19,7 @@ type recovery struct {
|
||||||
|
|
||||||
// New creates recovery middleware.
|
// New creates recovery middleware.
|
||||||
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &recovery{
|
return &recovery{
|
||||||
next: next,
|
next: next,
|
||||||
|
@ -28,13 +28,13 @@ func New(ctx context.Context, next http.Handler, name string) (http.Handler, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
defer recoverFunc(middlewares.GetLogger(req.Context(), re.name, typeName), rw)
|
defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw)
|
||||||
re.next.ServeHTTP(rw, req)
|
re.next.ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
|
|
||||||
func recoverFunc(logger logrus.FieldLogger, rw http.ResponseWriter) {
|
func recoverFunc(ctx context.Context, rw http.ResponseWriter) {
|
||||||
if err := recover(); err != nil {
|
if err := recover(); err != nil {
|
||||||
logger.Errorf("Recovered from panic in http handler: %+v", err)
|
log.FromContext(ctx).Errorf("Recovered from panic in http handler: %+v", err)
|
||||||
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,7 +2,6 @@ package redirect
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
@ -25,7 +24,7 @@ type redirect struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a Redirect middleware.
|
// New creates a Redirect middleware.
|
||||||
func newRedirect(_ context.Context, next http.Handler, regex string, replacement string, permanent bool, name string) (http.Handler, error) {
|
func newRedirect(next http.Handler, regex string, replacement string, permanent bool, name string) (http.Handler, error) {
|
||||||
re, err := regexp.Compile(regex)
|
re, err := regexp.Compile(regex)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -14,9 +15,9 @@ const (
|
||||||
|
|
||||||
// NewRedirectRegex creates a redirect middleware.
|
// NewRedirectRegex creates a redirect middleware.
|
||||||
func NewRedirectRegex(ctx context.Context, next http.Handler, conf dynamic.RedirectRegex, name string) (http.Handler, error) {
|
func NewRedirectRegex(ctx context.Context, next http.Handler, conf dynamic.RedirectRegex, name string) (http.Handler, error) {
|
||||||
logger := middlewares.GetLogger(ctx, name, typeRegexName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeRegexName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
logger.Debugf("Setting up redirection from %s to %s", conf.Regex, conf.Replacement)
|
logger.Debugf("Setting up redirection from %s to %s", conf.Regex, conf.Replacement)
|
||||||
|
|
||||||
return newRedirect(ctx, next, conf.Regex, conf.Replacement, conf.Permanent, name)
|
return newRedirect(next, conf.Regex, conf.Replacement, conf.Permanent, name)
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -16,7 +17,7 @@ const (
|
||||||
|
|
||||||
// NewRedirectScheme creates a new RedirectScheme middleware.
|
// NewRedirectScheme creates a new RedirectScheme middleware.
|
||||||
func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.RedirectScheme, name string) (http.Handler, error) {
|
func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.RedirectScheme, name string) (http.Handler, error) {
|
||||||
logger := middlewares.GetLogger(ctx, name, typeSchemeName)
|
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeSchemeName))
|
||||||
logger.Debug("Creating middleware")
|
logger.Debug("Creating middleware")
|
||||||
logger.Debugf("Setting up redirection to %s %s", conf.Scheme, conf.Port)
|
logger.Debugf("Setting up redirection to %s %s", conf.Scheme, conf.Port)
|
||||||
|
|
||||||
|
@ -29,5 +30,5 @@ func NewRedirectScheme(ctx context.Context, next http.Handler, conf dynamic.Redi
|
||||||
port = ":" + conf.Port
|
port = ":" + conf.Port
|
||||||
}
|
}
|
||||||
|
|
||||||
return newRedirect(ctx, next, schemeRedirectRegex, conf.Scheme+"://${2}"+port+"${4}", conf.Permanent, name)
|
return newRedirect(next, schemeRedirectRegex, conf.Scheme+"://${2}"+port+"${4}", conf.Permanent, name)
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -25,7 +26,7 @@ type replacePath struct {
|
||||||
|
|
||||||
// New creates a new replace path middleware.
|
// New creates a new replace path middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePath, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &replacePath{
|
return &replacePath{
|
||||||
next: next,
|
next: next,
|
||||||
|
@ -42,5 +43,6 @@ func (r *replacePath) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
req.Header.Add(ReplacedPathHeader, req.URL.Path)
|
req.Header.Add(ReplacedPathHeader, req.URL.Path)
|
||||||
req.URL.Path = r.path
|
req.URL.Path = r.path
|
||||||
req.RequestURI = req.URL.RequestURI()
|
req.RequestURI = req.URL.RequestURI()
|
||||||
|
|
||||||
r.next.ServeHTTP(rw, req)
|
r.next.ServeHTTP(rw, req)
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,6 +8,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares/replacepath"
|
"github.com/containous/traefik/v2/pkg/middlewares/replacepath"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
|
@ -28,7 +29,7 @@ type replacePathRegex struct {
|
||||||
|
|
||||||
// New creates a new replace path regex middleware.
|
// New creates a new replace path regex middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
|
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
@ -10,6 +10,7 @@ import (
|
||||||
"net/http/httptrace"
|
"net/http/httptrace"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -43,8 +44,7 @@ type retry struct {
|
||||||
|
|
||||||
// New returns a new retry middleware.
|
// New returns a new retry middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.Retry, listener Listener, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.Retry, listener Listener, name string) (http.Handler, error) {
|
||||||
logger := middlewares.GetLogger(ctx, name, typeName)
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
logger.Debug("Creating middleware")
|
|
||||||
|
|
||||||
if config.Attempts <= 0 {
|
if config.Attempts <= 0 {
|
||||||
return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts)
|
return nil, fmt.Errorf("incorrect (or empty) value for attempt (%d)", config.Attempts)
|
||||||
|
@ -94,8 +94,10 @@ func (r *retry) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
attempts++
|
attempts++
|
||||||
logger := middlewares.GetLogger(req.Context(), r.name, typeName)
|
|
||||||
logger.Debugf("New attempt %d for request: %v", attempts, req.URL)
|
log.FromContext(middlewares.GetLoggerCtx(req.Context(), r.name, typeName)).
|
||||||
|
Debugf("New attempt %d for request: %v", attempts, req.URL)
|
||||||
|
|
||||||
r.listener.Retried(req, attempts)
|
r.listener.Retried(req, attempts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,6 +6,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -26,7 +27,7 @@ type stripPrefix struct {
|
||||||
|
|
||||||
// New creates a new strip prefix middleware.
|
// New creates a new strip prefix middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefix, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefix, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
return &stripPrefix{
|
return &stripPrefix{
|
||||||
prefixes: config.Prefixes,
|
prefixes: config.Prefixes,
|
||||||
next: next,
|
next: next,
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares/stripprefix"
|
"github.com/containous/traefik/v2/pkg/middlewares/stripprefix"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
|
@ -26,7 +27,7 @@ type stripPrefixRegex struct {
|
||||||
|
|
||||||
// New builds a new StripPrefixRegex middleware.
|
// New builds a new StripPrefixRegex middleware.
|
||||||
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, name string) (http.Handler, error) {
|
func New(ctx context.Context, next http.Handler, config dynamic.StripPrefixRegex, name string) (http.Handler, error) {
|
||||||
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
stripPrefix := stripPrefixRegex{
|
stripPrefix := stripPrefixRegex{
|
||||||
next: next,
|
next: next,
|
||||||
|
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/containous/alice"
|
"github.com/containous/alice"
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go"
|
"github.com/opentracing/opentracing-go"
|
||||||
|
@ -17,7 +18,7 @@ const (
|
||||||
|
|
||||||
// NewEntryPoint creates a new middleware that the incoming request.
|
// NewEntryPoint creates a new middleware that the incoming request.
|
||||||
func NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler {
|
func NewEntryPoint(ctx context.Context, t *tracing.Tracing, entryPointName string, next http.Handler) http.Handler {
|
||||||
middlewares.GetLogger(ctx, "tracing", entryPointTypeName).Debug("Creating middleware")
|
log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", entryPointTypeName)).Debug("Creating middleware")
|
||||||
|
|
||||||
return &entryPointMiddleware{
|
return &entryPointMiddleware{
|
||||||
entryPoint: entryPointName,
|
entryPoint: entryPointName,
|
||||||
|
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/containous/traefik/v2/pkg/log"
|
||||||
"github.com/containous/traefik/v2/pkg/middlewares"
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
||||||
"github.com/containous/traefik/v2/pkg/tracing"
|
"github.com/containous/traefik/v2/pkg/tracing"
|
||||||
"github.com/opentracing/opentracing-go/ext"
|
"github.com/opentracing/opentracing-go/ext"
|
||||||
|
@ -21,7 +22,7 @@ type forwarderMiddleware struct {
|
||||||
|
|
||||||
// NewForwarder creates a new forwarder middleware that traces the outgoing request.
|
// NewForwarder creates a new forwarder middleware that traces the outgoing request.
|
||||||
func NewForwarder(ctx context.Context, router, service string, next http.Handler) http.Handler {
|
func NewForwarder(ctx context.Context, router, service string, next http.Handler) http.Handler {
|
||||||
middlewares.GetLogger(ctx, "tracing", forwarderTypeName).
|
log.FromContext(middlewares.GetLoggerCtx(ctx, "tracing", forwarderTypeName)).
|
||||||
Debugf("Added outgoing tracing middleware %s", service)
|
Debugf("Added outgoing tracing middleware %s", service)
|
||||||
|
|
||||||
return &forwarderMiddleware{
|
return &forwarderMiddleware{
|
||||||
|
|
|
@ -350,17 +350,19 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
||||||
if route.TLS == nil || route.TLS.CertResolver != p.ResolverName {
|
if route.TLS == nil || route.TLS.CertResolver != p.ResolverName {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
ctxRouter := log.With(ctx, log.Str(log.RouterName, routerName), log.Str(log.Rule, route.Rule))
|
ctxRouter := log.With(ctx, log.Str(log.RouterName, routerName), log.Str(log.Rule, route.Rule))
|
||||||
|
logger := log.FromContext(ctxRouter)
|
||||||
|
|
||||||
tlsStore := "default"
|
tlsStore := "default"
|
||||||
if len(route.TLS.Domains) > 0 {
|
if len(route.TLS.Domains) > 0 {
|
||||||
for _, domain := range route.TLS.Domains {
|
for _, domain := range route.TLS.Domains {
|
||||||
if domain.Main != dns01.UnFqdn(domain.Main) {
|
if domain.Main != dns01.UnFqdn(domain.Main) {
|
||||||
log.Warnf("FQDN detected, please remove the trailing dot: %s", domain.Main)
|
logger.Warnf("FQDN detected, please remove the trailing dot: %s", domain.Main)
|
||||||
}
|
}
|
||||||
for _, san := range domain.SANs {
|
for _, san := range domain.SANs {
|
||||||
if san != dns01.UnFqdn(san) {
|
if san != dns01.UnFqdn(san) {
|
||||||
log.Warnf("FQDN detected, please remove the trailing dot: %s", san)
|
logger.Warnf("FQDN detected, please remove the trailing dot: %s", san)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -378,7 +380,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
|
||||||
} else {
|
} else {
|
||||||
domains, err := rules.ParseHostSNI(route.Rule)
|
domains, err := rules.ParseHostSNI(route.Rule)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.FromContext(ctxRouter).Errorf("Error parsing domains in provider ACME: %v", err)
|
logger.Errorf("Error parsing domains in provider ACME: %v", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
p.resolveDomains(ctxRouter, domains, tlsStore)
|
p.resolveDomains(ctxRouter, domains, tlsStore)
|
||||||
|
|
|
@ -85,8 +85,9 @@ func (p *Provider) buildTCPServiceConfiguration(ctx context.Context, container d
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, service := range configuration.Services {
|
for name, service := range configuration.Services {
|
||||||
err := p.addServerTCP(ctx, container, service.LoadBalancer)
|
ctxSvc := log.With(ctx, log.Str(log.ServiceName, name))
|
||||||
|
err := p.addServerTCP(ctxSvc, container, service.LoadBalancer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -107,8 +108,9 @@ func (p *Provider) buildServiceConfiguration(ctx context.Context, container dock
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, service := range configuration.Services {
|
for name, service := range configuration.Services {
|
||||||
err := p.addServer(ctx, container, service.LoadBalancer)
|
ctxSvc := log.With(ctx, log.Str(log.ServiceName, name))
|
||||||
|
err := p.addServer(ctxSvc, container, service.LoadBalancer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
|
@ -85,7 +85,7 @@ func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(p.Filename) > 0 {
|
if len(p.Filename) > 0 {
|
||||||
return p.loadFileConfig(p.Filename, true)
|
return p.loadFileConfig(ctx, p.Filename, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, errors.New("error using file configuration provider, neither filename or directory defined")
|
return nil, errors.New("error using file configuration provider, neither filename or directory defined")
|
||||||
|
@ -156,11 +156,11 @@ func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Provider) loadFileConfig(filename string, parseTemplate bool) (*dynamic.Configuration, error) {
|
func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) {
|
||||||
var err error
|
var err error
|
||||||
var configuration *dynamic.Configuration
|
var configuration *dynamic.Configuration
|
||||||
if parseTemplate {
|
if parseTemplate {
|
||||||
configuration, err = p.CreateConfiguration(filename, template.FuncMap{}, false)
|
configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false)
|
||||||
} else {
|
} else {
|
||||||
configuration, err = p.DecodeConfiguration(filename)
|
configuration, err = p.DecodeConfiguration(filename)
|
||||||
}
|
}
|
||||||
|
@ -169,25 +169,25 @@ func (p *Provider) loadFileConfig(filename string, parseTemplate bool) (*dynamic
|
||||||
}
|
}
|
||||||
|
|
||||||
if configuration.TLS != nil {
|
if configuration.TLS != nil {
|
||||||
configuration.TLS.Certificates = flattenCertificates(configuration.TLS)
|
configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS)
|
||||||
}
|
}
|
||||||
|
|
||||||
return configuration, nil
|
return configuration, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func flattenCertificates(tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores {
|
func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores {
|
||||||
var certs []*tls.CertAndStores
|
var certs []*tls.CertAndStores
|
||||||
for _, cert := range tlsConfig.Certificates {
|
for _, cert := range tlsConfig.Certificates {
|
||||||
content, err := cert.Certificate.CertFile.Read()
|
content, err := cert.Certificate.CertFile.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.FromContext(ctx).Error(err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
cert.Certificate.CertFile = tls.FileOrContent(string(content))
|
cert.Certificate.CertFile = tls.FileOrContent(string(content))
|
||||||
|
|
||||||
content, err = cert.Certificate.KeyFile.Read()
|
content, err = cert.Certificate.KeyFile.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
log.FromContext(ctx).Error(err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
cert.Certificate.KeyFile = tls.FileOrContent(string(content))
|
cert.Certificate.KeyFile = tls.FileOrContent(string(content))
|
||||||
|
@ -243,7 +243,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st
|
||||||
}
|
}
|
||||||
|
|
||||||
var c *dynamic.Configuration
|
var c *dynamic.Configuration
|
||||||
c, err = p.loadFileConfig(filepath.Join(directory, item.Name()), true)
|
c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return configuration, err
|
return configuration, err
|
||||||
}
|
}
|
||||||
|
@ -331,7 +331,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateConfiguration creates a provider configuration from content using templating.
|
// CreateConfiguration creates a provider configuration from content using templating.
|
||||||
func (p *Provider) CreateConfiguration(filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) {
|
func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) {
|
||||||
tmplContent, err := readFile(filename)
|
tmplContent, err := readFile(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error reading configuration file: %s - %s", filename, err)
|
return nil, fmt.Errorf("error reading configuration file: %s - %s", filename, err)
|
||||||
|
@ -359,7 +359,7 @@ func (p *Provider) CreateConfiguration(filename string, funcMap template.FuncMap
|
||||||
|
|
||||||
var renderedTemplate = buffer.String()
|
var renderedTemplate = buffer.String()
|
||||||
if p.DebugLogGeneratedTemplate {
|
if p.DebugLogGeneratedTemplate {
|
||||||
logger := log.WithoutContext().WithField(log.ProviderName, providerName)
|
logger := log.FromContext(ctx)
|
||||||
logger.Debugf("Template content: %s", tmplContent)
|
logger.Debugf("Template content: %s", tmplContent)
|
||||||
logger.Debugf("Rendering results: %s", renderedTemplate)
|
logger.Debugf("Rendering results: %s", renderedTemplate)
|
||||||
}
|
}
|
||||||
|
|
|
@ -46,7 +46,7 @@ func TestTLSContent(t *testing.T) {
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
provider := &Provider{}
|
provider := &Provider{}
|
||||||
configuration, err := provider.loadFileConfig(fileConfig.Name(), true)
|
configuration, err := provider.loadFileConfig(context.Background(), fileConfig.Name(), true)
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
require.Equal(t, "CONTENT", configuration.TLS.Certificates[0].Certificate.CertFile.String())
|
require.Equal(t, "CONTENT", configuration.TLS.Certificates[0].Certificate.CertFile.String())
|
||||||
|
|
|
@ -155,8 +155,9 @@ func GoWithRecover(goroutine func(), customRecover func(err interface{})) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultRecoverGoroutine(err interface{}) {
|
func defaultRecoverGoroutine(err interface{}) {
|
||||||
log.Errorf("Error in Go routine: %s", err)
|
logger := log.WithoutContext()
|
||||||
log.Errorf("Stack: %s", debug.Stack())
|
logger.Errorf("Error in Go routine: %s", err)
|
||||||
|
logger.Errorf("Stack: %s", debug.Stack())
|
||||||
}
|
}
|
||||||
|
|
||||||
// OperationWithRecover wrap a backoff operation in a Recover
|
// OperationWithRecover wrap a backoff operation in a Recover
|
||||||
|
|
|
@ -27,7 +27,7 @@ func GenerateName(backendName string) string {
|
||||||
_, err := hash.Write(data)
|
_, err := hash.Write(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Impossible case
|
// Impossible case
|
||||||
log.Errorf("Fail to create cookie name: %v", err)
|
log.WithoutContext().Errorf("Fail to create cookie name: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength]
|
return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength]
|
||||||
|
|
|
@ -203,6 +203,7 @@ func TestRuntimeConfiguration(t *testing.T) {
|
||||||
serviceManager := tcp.NewManager(conf)
|
serviceManager := tcp.NewManager(conf)
|
||||||
tlsManager := tls.NewManager()
|
tlsManager := tls.NewManager()
|
||||||
tlsManager.UpdateConfigs(
|
tlsManager.UpdateConfigs(
|
||||||
|
context.Background(),
|
||||||
map[string]tls.Store{},
|
map[string]tls.Store{},
|
||||||
map[string]tls.Options{
|
map[string]tls.Options{
|
||||||
"default": {
|
"default": {
|
||||||
|
|
|
@ -270,7 +270,8 @@ func (s *Server) listenProviders(stop chan bool) {
|
||||||
if configMsg.Configuration != nil {
|
if configMsg.Configuration != nil {
|
||||||
s.preLoadConfiguration(configMsg)
|
s.preLoadConfiguration(configMsg)
|
||||||
} else {
|
} else {
|
||||||
log.Debugf("Received nil configuration from provider %q, skipping.", configMsg.ProviderName)
|
log.WithoutContext().WithField(log.ProviderName, configMsg.ProviderName).
|
||||||
|
Debug("Received nil configuration from provider, skipping.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -285,18 +286,20 @@ func (s *Server) AddListener(listener func(dynamic.Configuration)) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Server) startProvider() {
|
func (s *Server) startProvider() {
|
||||||
|
logger := log.WithoutContext()
|
||||||
|
|
||||||
jsonConf, err := json.Marshal(s.provider)
|
jsonConf, err := json.Marshal(s.provider)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.WithoutContext().Debugf("Unable to marshal provider configuration %T: %v", s.provider, err)
|
logger.Debugf("Unable to marshal provider configuration %T: %v", s.provider, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.WithoutContext().Infof("Starting provider %T %s", s.provider, jsonConf)
|
logger.Infof("Starting provider %T %s", s.provider, jsonConf)
|
||||||
currentProvider := s.provider
|
currentProvider := s.provider
|
||||||
|
|
||||||
safe.Go(func() {
|
safe.Go(func() {
|
||||||
err := currentProvider.Provide(s.configurationChan, s.routinesPool)
|
err := currentProvider.Provide(s.configurationChan, s.routinesPool)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.WithoutContext().Errorf("Error starting provider %T: %s", s.provider, err)
|
logger.Errorf("Error starting provider %T: %s", s.provider, err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -63,7 +63,7 @@ func (s *Server) loadConfiguration(configMsg dynamic.Message) {
|
||||||
// loadConfigurationTCP returns a new gorilla.mux Route from the specified global configuration and the dynamic
|
// loadConfigurationTCP returns a new gorilla.mux Route from the specified global configuration and the dynamic
|
||||||
// provider configurations.
|
// provider configurations.
|
||||||
func (s *Server) loadConfigurationTCP(configurations dynamic.Configurations) map[string]*tcpCore.Router {
|
func (s *Server) loadConfigurationTCP(configurations dynamic.Configurations) map[string]*tcpCore.Router {
|
||||||
ctx := context.TODO()
|
ctx := context.Background()
|
||||||
|
|
||||||
var entryPoints []string
|
var entryPoints []string
|
||||||
for entryPointName := range s.entryPointsTCP {
|
for entryPointName := range s.entryPointsTCP {
|
||||||
|
@ -72,7 +72,7 @@ func (s *Server) loadConfigurationTCP(configurations dynamic.Configurations) map
|
||||||
|
|
||||||
conf := mergeConfiguration(configurations)
|
conf := mergeConfiguration(configurations)
|
||||||
|
|
||||||
s.tlsManager.UpdateConfigs(conf.TLS.Stores, conf.TLS.Options, conf.TLS.Certificates)
|
s.tlsManager.UpdateConfigs(ctx, conf.TLS.Stores, conf.TLS.Options, conf.TLS.Certificates)
|
||||||
|
|
||||||
rtConf := runtime.NewConfig(conf)
|
rtConf := runtime.NewConfig(conf)
|
||||||
handlersNonTLS, handlersTLS := s.createHTTPHandlers(ctx, rtConf, entryPoints)
|
handlersNonTLS, handlersTLS := s.createHTTPHandlers(ctx, rtConf, entryPoints)
|
||||||
|
|
|
@ -72,14 +72,14 @@ func NewTCPEntryPoint(ctx context.Context, configuration *static.EntryPoint) (*T
|
||||||
|
|
||||||
router := &tcp.Router{}
|
router := &tcp.Router{}
|
||||||
|
|
||||||
httpServer, err := createHTTPServer(listener, configuration, true)
|
httpServer, err := createHTTPServer(ctx, listener, configuration, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error preparing httpServer: %v", err)
|
return nil, fmt.Errorf("error preparing httpServer: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
router.HTTPForwarder(httpServer.Forwarder)
|
router.HTTPForwarder(httpServer.Forwarder)
|
||||||
|
|
||||||
httpsServer, err := createHTTPServer(listener, configuration, false)
|
httpsServer, err := createHTTPServer(ctx, listener, configuration, false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error preparing httpsServer: %v", err)
|
return nil, fmt.Errorf("error preparing httpsServer: %v", err)
|
||||||
}
|
}
|
||||||
|
@ -128,13 +128,13 @@ func writeCloser(conn net.Conn) (tcp.WriteCloser, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *TCPEntryPoint) startTCP(ctx context.Context) {
|
func (e *TCPEntryPoint) startTCP(ctx context.Context) {
|
||||||
|
logger := log.FromContext(ctx)
|
||||||
log.FromContext(ctx).Debugf("Start TCP Server")
|
logger.Debugf("Start TCP Server")
|
||||||
|
|
||||||
for {
|
for {
|
||||||
conn, err := e.listener.Accept()
|
conn, err := e.listener.Accept()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error(err)
|
logger.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -372,7 +372,7 @@ type httpServer struct {
|
||||||
Switcher *middlewares.HTTPHandlerSwitcher
|
Switcher *middlewares.HTTPHandlerSwitcher
|
||||||
}
|
}
|
||||||
|
|
||||||
func createHTTPServer(ln net.Listener, configuration *static.EntryPoint, withH2c bool) (*httpServer, error) {
|
func createHTTPServer(ctx context.Context, ln net.Listener, configuration *static.EntryPoint, withH2c bool) (*httpServer, error) {
|
||||||
httpSwitcher := middlewares.NewHandlerSwitcher(buildDefaultHTTPRouter())
|
httpSwitcher := middlewares.NewHandlerSwitcher(buildDefaultHTTPRouter())
|
||||||
|
|
||||||
var handler http.Handler
|
var handler http.Handler
|
||||||
|
@ -398,7 +398,7 @@ func createHTTPServer(ln net.Listener, configuration *static.EntryPoint, withH2c
|
||||||
go func() {
|
go func() {
|
||||||
err := serverHTTP.Serve(listener)
|
err := serverHTTP.Serve(listener)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("Error while starting server: %v", err)
|
log.FromContext(ctx).Errorf("Error while starting server: %v", err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
return &httpServer{
|
return &httpServer{
|
||||||
|
|
|
@ -232,7 +232,7 @@ func (m *Manager) LaunchHealthCheck() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// FIXME metrics and context
|
// FIXME metrics and context
|
||||||
healthcheck.GetHealthCheck().SetBackendsConfiguration(context.TODO(), backendConfigs)
|
healthcheck.GetHealthCheck().SetBackendsConfiguration(context.Background(), backendConfigs)
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler, backend string, hc *dynamic.HealthCheck) *healthcheck.Options {
|
func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler, backend string, hc *dynamic.HealthCheck) *healthcheck.Options {
|
||||||
|
|
|
@ -39,7 +39,7 @@ func (r *RRLoadBalancer) next() Handler {
|
||||||
|
|
||||||
if r.current >= len(r.servers) {
|
if r.current >= len(r.servers) {
|
||||||
r.current = 0
|
r.current = 0
|
||||||
log.Debugf("Load balancer: going back to the first available server")
|
log.WithoutContext().Debugf("Load balancer: going back to the first available server")
|
||||||
}
|
}
|
||||||
|
|
||||||
handler := r.servers[r.current]
|
handler := r.servers[r.current]
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package tls
|
package tls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"errors"
|
"errors"
|
||||||
|
@ -30,7 +31,7 @@ func NewManager() *Manager {
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateConfigs updates the TLS* configuration options
|
// UpdateConfigs updates the TLS* configuration options
|
||||||
func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Options, certs []*CertAndStores) {
|
func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, configs map[string]Options, certs []*CertAndStores) {
|
||||||
m.lock.Lock()
|
m.lock.Lock()
|
||||||
defer m.lock.Unlock()
|
defer m.lock.Unlock()
|
||||||
|
|
||||||
|
@ -40,9 +41,10 @@ func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Opti
|
||||||
|
|
||||||
m.stores = make(map[string]*CertificateStore)
|
m.stores = make(map[string]*CertificateStore)
|
||||||
for storeName, storeConfig := range m.storesConfig {
|
for storeName, storeConfig := range m.storesConfig {
|
||||||
store, err := buildCertificateStore(storeConfig)
|
ctxStore := log.With(ctx, log.Str(log.TLSStoreName, storeName))
|
||||||
|
store, err := buildCertificateStore(ctxStore, storeConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("Error while creating certificate store %s: %v", storeName, err)
|
log.FromContext(ctxStore).Errorf("Error while creating certificate store: %v", err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
m.stores[storeName] = store
|
m.stores[storeName] = store
|
||||||
|
@ -52,14 +54,15 @@ func (m *Manager) UpdateConfigs(stores map[string]Store, configs map[string]Opti
|
||||||
for _, conf := range certs {
|
for _, conf := range certs {
|
||||||
if len(conf.Stores) == 0 {
|
if len(conf.Stores) == 0 {
|
||||||
if log.GetLevel() >= logrus.DebugLevel {
|
if log.GetLevel() >= logrus.DebugLevel {
|
||||||
log.Debugf("No store is defined to add the certificate %s, it will be added to the default store.",
|
log.FromContext(ctx).Debugf("No store is defined to add the certificate %s, it will be added to the default store.",
|
||||||
conf.Certificate.GetTruncatedCertificateName())
|
conf.Certificate.GetTruncatedCertificateName())
|
||||||
}
|
}
|
||||||
conf.Stores = []string{"default"}
|
conf.Stores = []string{"default"}
|
||||||
}
|
}
|
||||||
for _, store := range conf.Stores {
|
for _, store := range conf.Stores {
|
||||||
|
ctxStore := log.With(ctx, log.Str(log.TLSStoreName, store))
|
||||||
if err := conf.Certificate.AppendCertificate(storesCertificates, store); err != nil {
|
if err := conf.Certificate.AppendCertificate(storesCertificates, store); err != nil {
|
||||||
log.Errorf("Unable to append certificate %s to store %s: %v", conf.Certificate.GetTruncatedCertificateName(), store, err)
|
log.FromContext(ctxStore).Errorf("Unable to append certificate %s to store: %v", conf.Certificate.GetTruncatedCertificateName(), err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -125,7 +128,7 @@ func (m *Manager) Get(storeName string, configName string) (*tls.Config, error)
|
||||||
func (m *Manager) getStore(storeName string) *CertificateStore {
|
func (m *Manager) getStore(storeName string) *CertificateStore {
|
||||||
_, ok := m.stores[storeName]
|
_, ok := m.stores[storeName]
|
||||||
if !ok {
|
if !ok {
|
||||||
m.stores[storeName], _ = buildCertificateStore(Store{})
|
m.stores[storeName], _ = buildCertificateStore(context.Background(), Store{})
|
||||||
}
|
}
|
||||||
return m.stores[storeName]
|
return m.stores[storeName]
|
||||||
}
|
}
|
||||||
|
@ -138,7 +141,7 @@ func (m *Manager) GetStore(storeName string) *CertificateStore {
|
||||||
return m.getStore(storeName)
|
return m.getStore(storeName)
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildCertificateStore(tlsStore Store) (*CertificateStore, error) {
|
func buildCertificateStore(ctx context.Context, tlsStore Store) (*CertificateStore, error) {
|
||||||
certificateStore := NewCertificateStore()
|
certificateStore := NewCertificateStore()
|
||||||
certificateStore.DynamicCerts.Set(make(map[string]*tls.Certificate))
|
certificateStore.DynamicCerts.Set(make(map[string]*tls.Certificate))
|
||||||
|
|
||||||
|
@ -149,7 +152,7 @@ func buildCertificateStore(tlsStore Store) (*CertificateStore, error) {
|
||||||
}
|
}
|
||||||
certificateStore.DefaultCertificate = cert
|
certificateStore.DefaultCertificate = cert
|
||||||
} else {
|
} else {
|
||||||
log.Debug("No default certificate, generating one")
|
log.FromContext(ctx).Debug("No default certificate, generating one")
|
||||||
cert, err := generate.DefaultCertificate()
|
cert, err := generate.DefaultCertificate()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return certificateStore, err
|
return certificateStore, err
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package tls
|
package tls
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"encoding/pem"
|
"encoding/pem"
|
||||||
|
@ -57,7 +58,7 @@ func TestTLSInStore(t *testing.T) {
|
||||||
}}
|
}}
|
||||||
|
|
||||||
tlsManager := NewManager()
|
tlsManager := NewManager()
|
||||||
tlsManager.UpdateConfigs(nil, nil, dynamicConfigs)
|
tlsManager.UpdateConfigs(context.Background(), nil, nil, dynamicConfigs)
|
||||||
|
|
||||||
certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*tls.Certificate)
|
certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*tls.Certificate)
|
||||||
if len(certs) == 0 {
|
if len(certs) == 0 {
|
||||||
|
@ -74,7 +75,8 @@ func TestTLSInvalidStore(t *testing.T) {
|
||||||
}}
|
}}
|
||||||
|
|
||||||
tlsManager := NewManager()
|
tlsManager := NewManager()
|
||||||
tlsManager.UpdateConfigs(map[string]Store{
|
tlsManager.UpdateConfigs(context.Background(),
|
||||||
|
map[string]Store{
|
||||||
"default": {
|
"default": {
|
||||||
DefaultCertificate: &Certificate{
|
DefaultCertificate: &Certificate{
|
||||||
CertFile: "/wrong",
|
CertFile: "/wrong",
|
||||||
|
@ -131,7 +133,7 @@ func TestManager_Get(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsManager := NewManager()
|
tlsManager := NewManager()
|
||||||
tlsManager.UpdateConfigs(nil, tlsConfigs, dynamicConfigs)
|
tlsManager.UpdateConfigs(context.Background(), nil, tlsConfigs, dynamicConfigs)
|
||||||
|
|
||||||
for _, test := range testCases {
|
for _, test := range testCases {
|
||||||
test := test
|
test := test
|
||||||
|
@ -270,7 +272,7 @@ func TestClientAuth(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
tlsManager := NewManager()
|
tlsManager := NewManager()
|
||||||
tlsManager.UpdateConfigs(nil, tlsConfigs, nil)
|
tlsManager.UpdateConfigs(context.Background(), nil, tlsConfigs, nil)
|
||||||
|
|
||||||
for _, test := range testCases {
|
for _, test := range testCases {
|
||||||
test := test
|
test := test
|
||||||
|
|
|
@ -43,7 +43,7 @@ func (v Handler) Append(router *mux.Router) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := templatesRenderer.JSON(response, http.StatusOK, v); err != nil {
|
if err := templatesRenderer.JSON(response, http.StatusOK, v); err != nil {
|
||||||
log.Error(err)
|
log.WithoutContext().Error(err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -53,34 +53,39 @@ func CheckNewVersion() {
|
||||||
if Version == "dev" {
|
if Version == "dev" {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger := log.WithoutContext()
|
||||||
|
|
||||||
client := github.NewClient(nil)
|
client := github.NewClient(nil)
|
||||||
|
|
||||||
updateURL, err := url.Parse("https://update.traefik.io/")
|
updateURL, err := url.Parse("https://update.traefik.io/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("Error checking new version: %s", err)
|
logger.Warnf("Error checking new version: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
client.BaseURL = updateURL
|
client.BaseURL = updateURL
|
||||||
|
|
||||||
releases, resp, err := client.Repositories.ListReleases(context.Background(), "containous", "traefik", nil)
|
releases, resp, err := client.Repositories.ListReleases(context.Background(), "containous", "traefik", nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("Error checking new version: %s", err)
|
logger.Warnf("Error checking new version: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
log.Warnf("Error checking new version: status=%s", resp.Status)
|
logger.Warnf("Error checking new version: status=%s", resp.Status)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
currentVersion, err := goversion.NewVersion(Version)
|
currentVersion, err := goversion.NewVersion(Version)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("Error checking new version: %s", err)
|
logger.Warnf("Error checking new version: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, release := range releases {
|
for _, release := range releases {
|
||||||
releaseVersion, err := goversion.NewVersion(*release.TagName)
|
releaseVersion, err := goversion.NewVersion(*release.TagName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Warnf("Error checking new version: %s", err)
|
logger.Warnf("Error checking new version: %s", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -89,7 +94,7 @@ func CheckNewVersion() {
|
||||||
}
|
}
|
||||||
|
|
||||||
if releaseVersion.GreaterThan(currentVersion) {
|
if releaseVersion.GreaterThan(currentVersion) {
|
||||||
log.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String())
|
logger.Warnf("A new release has been found: %s. Please consider updating.", releaseVersion.String())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue