2019-11-14 15:40:05 +00:00
package middleware
import (
"context"
"github.com/containous/alice"
2022-11-21 17:36:05 +00:00
"github.com/rs/zerolog/log"
2023-02-03 14:24:05 +00:00
"github.com/traefik/traefik/v3/pkg/metrics"
"github.com/traefik/traefik/v3/pkg/middlewares/accesslog"
"github.com/traefik/traefik/v3/pkg/middlewares/capture"
2024-01-08 08:10:06 +00:00
metricsMiddle "github.com/traefik/traefik/v3/pkg/middlewares/metrics"
tracingMiddle "github.com/traefik/traefik/v3/pkg/middlewares/tracing"
"go.opentelemetry.io/otel/trace"
2019-11-14 15:40:05 +00:00
)
// ChainBuilder Creates a middleware chain by entry point. It is used for middlewares that are created almost systematically and that need to be created before all others.
type ChainBuilder struct {
metricsRegistry metrics . Registry
accessLoggerMiddleware * accesslog . Handler
2024-01-08 08:10:06 +00:00
tracer trace . Tracer
2019-11-14 15:40:05 +00:00
}
// NewChainBuilder Creates a new ChainBuilder.
2024-01-08 08:10:06 +00:00
func NewChainBuilder ( metricsRegistry metrics . Registry , accessLoggerMiddleware * accesslog . Handler , tracer trace . Tracer ) * ChainBuilder {
2019-11-14 15:40:05 +00:00
return & ChainBuilder {
metricsRegistry : metricsRegistry ,
accessLoggerMiddleware : accessLoggerMiddleware ,
2022-09-12 15:10:09 +00:00
tracer : tracer ,
2019-11-14 15:40:05 +00:00
}
}
// Build a middleware chain by entry point.
func ( c * ChainBuilder ) Build ( ctx context . Context , entryPointName string ) alice . Chain {
chain := alice . New ( )
2022-10-27 14:08:06 +00:00
if c . accessLoggerMiddleware != nil || c . metricsRegistry != nil && ( c . metricsRegistry . IsEpEnabled ( ) || c . metricsRegistry . IsRouterEnabled ( ) || c . metricsRegistry . IsSvcEnabled ( ) ) {
chain = chain . Append ( capture . Wrap )
2022-09-12 15:10:09 +00:00
}
2019-11-14 15:40:05 +00:00
if c . accessLoggerMiddleware != nil {
chain = chain . Append ( accesslog . WrapHandler ( c . accessLoggerMiddleware ) )
}
if c . tracer != nil {
2024-01-08 08:10:06 +00:00
chain = chain . Append ( tracingMiddle . WrapEntryPointHandler ( ctx , c . tracer , entryPointName ) )
2019-11-14 15:40:05 +00:00
}
if c . metricsRegistry != nil && c . metricsRegistry . IsEpEnabled ( ) {
2024-01-08 08:10:06 +00:00
metricsHandler := metricsMiddle . WrapEntryPointHandler ( ctx , c . metricsRegistry , entryPointName )
chain = chain . Append ( tracingMiddle . WrapMiddleware ( ctx , metricsHandler ) )
2019-11-14 15:40:05 +00:00
}
2022-02-14 16:18:08 +00:00
return chain
2019-11-14 15:40:05 +00:00
}
// Close accessLogger and tracer.
func ( c * ChainBuilder ) Close ( ) {
if c . accessLoggerMiddleware != nil {
if err := c . accessLoggerMiddleware . Close ( ) ; err != nil {
2022-11-21 17:36:05 +00:00
log . Error ( ) . Err ( err ) . Msg ( "Could not close the access log file" )
2019-11-14 15:40:05 +00:00
}
}
}