2018-11-14 09:18:03 +00:00
|
|
|
package recovery
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"net/http"
|
2019-10-18 09:30:05 +00:00
|
|
|
"runtime"
|
2018-11-14 09:18:03 +00:00
|
|
|
|
2019-09-13 17:28:04 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/log"
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/containous/traefik/v2/pkg/middlewares"
|
2018-11-14 09:18:03 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
typeName = "Recovery"
|
|
|
|
)
|
|
|
|
|
|
|
|
type recovery struct {
|
|
|
|
next http.Handler
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates recovery middleware.
|
|
|
|
func New(ctx context.Context, next http.Handler, name string) (http.Handler, error) {
|
2019-09-13 17:28:04 +00:00
|
|
|
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
return &recovery{
|
|
|
|
next: next,
|
|
|
|
name: name,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (re *recovery) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
2019-10-18 09:30:05 +00:00
|
|
|
defer recoverFunc(middlewares.GetLoggerCtx(req.Context(), re.name, typeName), rw, req)
|
2018-11-14 09:18:03 +00:00
|
|
|
re.next.ServeHTTP(rw, req)
|
|
|
|
}
|
|
|
|
|
2019-10-18 09:30:05 +00:00
|
|
|
func recoverFunc(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
|
2018-11-14 09:18:03 +00:00
|
|
|
if err := recover(); err != nil {
|
2019-10-18 09:30:05 +00:00
|
|
|
if !shouldLogPanic(err) {
|
|
|
|
log.FromContext(ctx).Debugf("Request has been aborted [%s - %s]: %v", r.RemoteAddr, r.URL, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.FromContext(ctx).Errorf("Recovered from panic in HTTP handler [%s - %s]: %+v", r.RemoteAddr, r.URL, err)
|
|
|
|
|
|
|
|
const size = 64 << 10
|
|
|
|
buf := make([]byte, size)
|
|
|
|
buf = buf[:runtime.Stack(buf, false)]
|
|
|
|
log.FromContext(ctx).Errorf("Stack: %s", buf)
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
2019-10-18 09:30:05 +00:00
|
|
|
|
|
|
|
// https://github.com/golang/go/blob/a0d6420d8be2ae7164797051ec74fa2a2df466a1/src/net/http/server.go#L1761-L1775
|
|
|
|
// https://github.com/golang/go/blob/c33153f7b416c03983324b3e8f869ce1116d84bc/src/net/http/httputil/reverseproxy.go#L284
|
|
|
|
func shouldLogPanic(panicValue interface{}) bool {
|
|
|
|
return panicValue != nil && panicValue != http.ErrAbortHandler
|
|
|
|
}
|