traefik/pkg/middlewares/customerrors/custom_errors.go

249 lines
7.1 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
package customerrors
2018-04-11 11:54:03 +00:00
import (
"bufio"
"bytes"
2018-11-14 09:18:03 +00:00
"context"
2018-04-23 09:28:04 +00:00
"fmt"
2018-04-11 11:54:03 +00:00
"net"
"net/http"
2018-04-23 09:28:04 +00:00
"net/url"
2018-04-11 11:54:03 +00:00
"strconv"
"strings"
2018-11-14 09:18:03 +00:00
"github.com/containous/traefik/old/types"
2019-03-15 08:42:03 +00:00
"github.com/containous/traefik/pkg/config"
"github.com/containous/traefik/pkg/middlewares"
"github.com/containous/traefik/pkg/tracing"
2018-11-14 09:18:03 +00:00
"github.com/opentracing/opentracing-go/ext"
"github.com/sirupsen/logrus"
2018-04-11 11:54:03 +00:00
"github.com/vulcand/oxy/utils"
)
// Compile time validation that the response recorder implements http interfaces correctly.
var _ middlewares.Stateful = &responseRecorderWithCloseNotify{}
2018-11-14 09:18:03 +00:00
const (
typeName = "customError"
backendURL = "http://0.0.0.0"
)
type serviceBuilder interface {
BuildHTTP(ctx context.Context, serviceName string, responseModifier func(*http.Response) error) (http.Handler, error)
2018-11-14 09:18:03 +00:00
}
// customErrors is a middleware that provides the custom error pages..
type customErrors struct {
name string
next http.Handler
2018-04-11 11:54:03 +00:00
backendHandler http.Handler
httpCodeRanges types.HTTPCodeRanges
backendQuery string
}
2018-11-14 09:18:03 +00:00
// New creates a new custom error pages middleware.
func New(ctx context.Context, next http.Handler, config config.ErrorPage, serviceBuilder serviceBuilder, name string) (http.Handler, error) {
middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")
httpCodeRanges, err := types.NewHTTPCodeRanges(config.Status)
if err != nil {
return nil, err
2018-04-11 11:54:03 +00:00
}
backend, err := serviceBuilder.BuildHTTP(ctx, config.Service, nil)
2018-04-11 11:54:03 +00:00
if err != nil {
return nil, err
}
2018-11-14 09:18:03 +00:00
return &customErrors{
name: name,
next: next,
backendHandler: backend,
2018-04-11 11:54:03 +00:00
httpCodeRanges: httpCodeRanges,
2018-11-14 09:18:03 +00:00
backendQuery: config.Query,
2018-04-11 11:54:03 +00:00
}, nil
}
2018-11-14 09:18:03 +00:00
func (c *customErrors) GetTracingInformation() (string, ext.SpanKindEnum) {
return c.name, tracing.SpanKindNoneEnum
2018-04-11 11:54:03 +00:00
}
2018-11-14 09:18:03 +00:00
func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := middlewares.GetLogger(req.Context(), c.name, typeName)
if c.backendHandler == nil {
logger.Error("Error pages: no backend handler.")
tracing.SetErrorWithEvent(req, "Error pages: no backend handler.")
c.next.ServeHTTP(rw, req)
2018-04-11 11:54:03 +00:00
return
}
2018-11-14 09:18:03 +00:00
recorder := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName))
c.next.ServeHTTP(recorder, req)
2018-04-11 11:54:03 +00:00
// check the recorder code against the configured http status code ranges
2018-11-14 09:18:03 +00:00
for _, block := range c.httpCodeRanges {
2018-04-11 11:54:03 +00:00
if recorder.GetCode() >= block[0] && recorder.GetCode() <= block[1] {
2018-11-14 09:18:03 +00:00
logger.Errorf("Caught HTTP Status Code %d, returning error page", recorder.GetCode())
2018-04-11 11:54:03 +00:00
var query string
2018-11-14 09:18:03 +00:00
if len(c.backendQuery) > 0 {
query = "/" + strings.TrimPrefix(c.backendQuery, "/")
2018-04-11 11:54:03 +00:00
query = strings.Replace(query, "{status}", strconv.Itoa(recorder.GetCode()), -1)
}
2018-11-14 09:18:03 +00:00
pageReq, err := newRequest(backendURL + query)
2018-04-23 09:28:04 +00:00
if err != nil {
2018-11-14 09:18:03 +00:00
logger.Error(err)
rw.WriteHeader(recorder.GetCode())
_, err = fmt.Fprint(rw, http.StatusText(recorder.GetCode()))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
2018-04-23 09:28:04 +00:00
return
2018-04-11 11:54:03 +00:00
}
2018-04-23 09:28:04 +00:00
2018-11-14 09:18:03 +00:00
recorderErrorPage := newResponseRecorder(rw, middlewares.GetLogger(context.Background(), "test", typeName))
2018-04-23 09:28:04 +00:00
utils.CopyHeaders(pageReq.Header, req.Header)
2018-05-18 14:38:03 +00:00
2018-11-14 09:18:03 +00:00
c.backendHandler.ServeHTTP(recorderErrorPage, pageReq.WithContext(req.Context()))
2018-05-18 14:38:03 +00:00
2018-11-14 09:18:03 +00:00
utils.CopyHeaders(rw.Header(), recorderErrorPage.Header())
rw.WriteHeader(recorder.GetCode())
2018-08-06 18:00:03 +00:00
2018-11-14 09:18:03 +00:00
if _, err = rw.Write(recorderErrorPage.GetBody().Bytes()); err != nil {
logger.Error(err)
2018-08-06 18:00:03 +00:00
}
2018-04-11 11:54:03 +00:00
return
}
}
// did not catch a configured status code so proceed with the request
2018-11-14 09:18:03 +00:00
utils.CopyHeaders(rw.Header(), recorder.Header())
rw.WriteHeader(recorder.GetCode())
_, err := rw.Write(recorder.GetBody().Bytes())
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
}
2018-04-11 11:54:03 +00:00
}
2018-04-23 09:28:04 +00:00
func newRequest(baseURL string) (*http.Request, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("error pages: error when parse URL: %v", err)
}
2018-11-14 09:18:03 +00:00
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
2018-04-23 09:28:04 +00:00
if err != nil {
return nil, fmt.Errorf("error pages: error when create query: %v", err)
}
req.RequestURI = u.RequestURI()
return req, nil
}
2018-04-11 11:54:03 +00:00
type responseRecorder interface {
http.ResponseWriter
http.Flusher
GetCode() int
GetBody() *bytes.Buffer
IsStreamingResponseStarted() bool
}
// newResponseRecorder returns an initialized responseRecorder.
2018-11-14 09:18:03 +00:00
func newResponseRecorder(rw http.ResponseWriter, logger logrus.FieldLogger) responseRecorder {
2018-04-11 11:54:03 +00:00
recorder := &responseRecorderWithoutCloseNotify{
HeaderMap: make(http.Header),
Body: new(bytes.Buffer),
Code: http.StatusOK,
responseWriter: rw,
2018-11-14 09:18:03 +00:00
logger: logger,
2018-04-11 11:54:03 +00:00
}
if _, ok := rw.(http.CloseNotifier); ok {
return &responseRecorderWithCloseNotify{recorder}
}
return recorder
}
// responseRecorderWithoutCloseNotify is an implementation of http.ResponseWriter that
// records its mutations for later inspection.
type responseRecorderWithoutCloseNotify struct {
Code int // the HTTP response code from WriteHeader
HeaderMap http.Header // the HTTP response headers
Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
responseWriter http.ResponseWriter
err error
streamingResponseStarted bool
2018-11-14 09:18:03 +00:00
logger logrus.FieldLogger
2018-04-11 11:54:03 +00:00
}
type responseRecorderWithCloseNotify struct {
*responseRecorderWithoutCloseNotify
}
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone away.
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithCloseNotify) CloseNotify() <-chan bool {
return r.responseWriter.(http.CloseNotifier).CloseNotify()
2018-04-11 11:54:03 +00:00
}
// Header returns the response headers.
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) Header() http.Header {
if r.HeaderMap == nil {
r.HeaderMap = make(http.Header)
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
return r.HeaderMap
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) GetCode() int {
return r.Code
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) GetBody() *bytes.Buffer {
return r.Body
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) IsStreamingResponseStarted() bool {
return r.streamingResponseStarted
2018-04-11 11:54:03 +00:00
}
// Write always succeeds and writes to rw.Body, if not nil.
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) Write(buf []byte) (int, error) {
if r.err != nil {
return 0, r.err
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
return r.Body.Write(buf)
2018-04-11 11:54:03 +00:00
}
// WriteHeader sets rw.Code.
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) WriteHeader(code int) {
r.Code = code
2018-04-11 11:54:03 +00:00
}
// Hijack hijacks the connection
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.responseWriter.(http.Hijacker).Hijack()
2018-04-11 11:54:03 +00:00
}
// Flush sends any buffered data to the client.
2018-05-28 13:00:04 +00:00
func (r *responseRecorderWithoutCloseNotify) Flush() {
if !r.streamingResponseStarted {
utils.CopyHeaders(r.responseWriter.Header(), r.Header())
r.responseWriter.WriteHeader(r.Code)
r.streamingResponseStarted = true
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
_, err := r.responseWriter.Write(r.Body.Bytes())
2018-04-11 11:54:03 +00:00
if err != nil {
2018-11-14 09:18:03 +00:00
r.logger.Errorf("Error writing response in responseRecorder: %v", err)
2018-05-28 13:00:04 +00:00
r.err = err
2018-04-11 11:54:03 +00:00
}
2018-05-28 13:00:04 +00:00
r.Body.Reset()
2018-04-11 11:54:03 +00:00
2018-05-28 13:00:04 +00:00
if flusher, ok := r.responseWriter.(http.Flusher); ok {
2018-04-11 11:54:03 +00:00
flusher.Flush()
}
}