traefik/pkg/middlewares/circuitbreaker/circuit_breaker.go

61 lines
1.8 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package circuitbreaker
import (
"context"
"net/http"
2019-08-03 01:58:23 +00:00
"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/tracing"
2018-11-14 09:18:03 +00:00
"github.com/opentracing/opentracing-go/ext"
"github.com/vulcand/oxy/cbreaker"
)
const (
typeName = "CircuitBreaker"
)
type circuitBreaker struct {
circuitBreaker *cbreaker.CircuitBreaker
name string
}
// New creates a new circuit breaker middleware.
func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.CircuitBreaker, name string) (http.Handler, error) {
2018-11-14 09:18:03 +00:00
expression := confCircuitBreaker.Expression
2019-09-13 17:28:04 +00:00
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
2018-11-14 09:18:03 +00:00
logger.Debug("Creating middleware")
logger.Debug("Setting up with expression: %s", expression)
oxyCircuitBreaker, err := cbreaker.New(next, expression, createCircuitBreakerOptions(expression))
if err != nil {
return nil, err
}
return &circuitBreaker{
circuitBreaker: oxyCircuitBreaker,
name: name,
}, nil
}
2020-05-11 10:06:07 +00:00
// NewCircuitBreakerOptions returns a new CircuitBreakerOption.
2018-11-14 09:18:03 +00:00
func createCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption {
return cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
tracing.SetErrorWithEvent(req, "blocked by circuit-breaker (%q)", expression)
rw.WriteHeader(http.StatusServiceUnavailable)
if _, err := rw.Write([]byte(http.StatusText(http.StatusServiceUnavailable))); err != nil {
log.FromContext(req.Context()).Error(err)
}
}))
}
func (c *circuitBreaker) GetTracingInformation() (string, ext.SpanKindEnum) {
return c.name, tracing.SpanKindNoneEnum
}
func (c *circuitBreaker) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
c.circuitBreaker.ServeHTTP(rw, req)
}