2019-08-26 10:20:06 +00:00
|
|
|
package inflightreq
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"github.com/opentracing/opentracing-go/ext"
|
2020-09-16 13:46:04 +00:00
|
|
|
"github.com/traefik/traefik/v2/pkg/config/dynamic"
|
|
|
|
"github.com/traefik/traefik/v2/pkg/log"
|
|
|
|
"github.com/traefik/traefik/v2/pkg/middlewares"
|
|
|
|
"github.com/traefik/traefik/v2/pkg/tracing"
|
2022-12-05 10:30:05 +00:00
|
|
|
"github.com/vulcand/oxy/v2/connlimit"
|
2019-08-26 10:20:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
typeName = "InFlightReq"
|
|
|
|
)
|
|
|
|
|
|
|
|
type inFlightReq struct {
|
|
|
|
handler http.Handler
|
|
|
|
name string
|
|
|
|
}
|
|
|
|
|
|
|
|
// New creates a max request middleware.
|
2020-04-29 16:32:05 +00:00
|
|
|
// If no source criterion is provided in the config, it defaults to RequestHost.
|
2019-08-26 10:20:06 +00:00
|
|
|
func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, name string) (http.Handler, error) {
|
|
|
|
ctxLog := log.With(ctx, log.Str(log.MiddlewareName, name), log.Str(log.MiddlewareType, typeName))
|
|
|
|
log.FromContext(ctxLog).Debug("Creating middleware")
|
|
|
|
|
|
|
|
if config.SourceCriterion == nil ||
|
|
|
|
config.SourceCriterion.IPStrategy == nil &&
|
|
|
|
config.SourceCriterion.RequestHeaderName == "" && !config.SourceCriterion.RequestHost {
|
|
|
|
config.SourceCriterion = &dynamic.SourceCriterion{
|
|
|
|
RequestHost: true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion)
|
|
|
|
if err != nil {
|
2020-05-11 10:06:07 +00:00
|
|
|
return nil, fmt.Errorf("error creating requests limiter: %w", err)
|
2019-08-26 10:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
handler, err := connlimit.New(next, sourceMatcher, config.Amount)
|
|
|
|
if err != nil {
|
2020-05-11 10:06:07 +00:00
|
|
|
return nil, fmt.Errorf("error creating connection limit: %w", err)
|
2019-08-26 10:20:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return &inFlightReq{handler: handler, name: name}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *inFlightReq) GetTracingInformation() (string, ext.SpanKindEnum) {
|
|
|
|
return i.name, tracing.SpanKindNoneEnum
|
|
|
|
}
|
|
|
|
|
|
|
|
func (i *inFlightReq) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
i.handler.ServeHTTP(rw, req)
|
|
|
|
}
|