-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Introduce concurrency limit for GET requests and a general timeout for HTTP #1743
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -14,7 +14,10 @@ | |
package api | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"net/http" | ||
"runtime" | ||
"time" | ||
|
||
apiv1 "github.com/prometheus/alertmanager/api/v1" | ||
|
@@ -24,6 +27,7 @@ import ( | |
"github.com/prometheus/alertmanager/provider" | ||
"github.com/prometheus/alertmanager/silence" | ||
"github.com/prometheus/alertmanager/types" | ||
"github.com/prometheus/client_golang/prometheus" | ||
"github.com/prometheus/common/model" | ||
"github.com/prometheus/common/route" | ||
|
||
|
@@ -32,56 +36,149 @@ import ( | |
|
||
// API represents all APIs of Alertmanager. | ||
type API struct { | ||
v1 *apiv1.API | ||
v2 *apiv2.API | ||
v1 *apiv1.API | ||
v2 *apiv2.API | ||
requestsInFlight prometheus.Gauge | ||
concurrencyLimitExceeded prometheus.Counter | ||
timeout time.Duration | ||
inFlightSem chan struct{} | ||
} | ||
|
||
// Options for the creation of an API object. Alerts, Silences, and StatusFunc | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for adding detailed comments here. |
||
// are mandatory to set. The zero value for everything else is a safe default. | ||
type Options struct { | ||
// Alerts to be used by the API. Mandatory. | ||
Alerts provider.Alerts | ||
// Silences to be used by the API. Mandatory. | ||
Silences *silence.Silences | ||
// StatusFunc is used be the API to retrieve the AlertStatus of an | ||
// alert. Mandatory. | ||
StatusFunc func(model.Fingerprint) types.AlertStatus | ||
// Peer from the gossip cluster. If nil, no clustering will be used. | ||
Peer *cluster.Peer | ||
// Timeout for all HTTP connections. The zero value (and negative | ||
// values) result in no timeout. | ||
Timeout time.Duration | ||
// Concurrency limit for GET requests. The zero value (and negative | ||
// values) result in a limit of GOMAXPROCS or 8, whichever is | ||
// larger. Status code 503 is served for GET requests that would exceed | ||
// the concurrency limit. | ||
Concurrency int | ||
// Logger is used for logging, if nil, no logging will happen. | ||
Logger log.Logger | ||
// Registry is used to register Prometheus metrics. If nil, no metrics | ||
// registration will happen. | ||
Registry prometheus.Registerer | ||
} | ||
|
||
func (o Options) validate() error { | ||
if o.Alerts == nil { | ||
return errors.New("mandatory field Alerts not set") | ||
} | ||
if o.Silences == nil { | ||
return errors.New("mandatory field Silences not set") | ||
} | ||
if o.StatusFunc == nil { | ||
return errors.New("mandatory field StatusFunc not set") | ||
} | ||
return nil | ||
} | ||
|
||
// New creates a new API object combining all API versions. | ||
func New( | ||
alerts provider.Alerts, | ||
silences *silence.Silences, | ||
sf func(model.Fingerprint) types.AlertStatus, | ||
peer *cluster.Peer, | ||
l log.Logger, | ||
) (*API, error) { | ||
func New(opts Options) (*API, error) { | ||
if err := opts.validate(); err != nil { | ||
return nil, fmt.Errorf("invalid API options: %s", err) | ||
} | ||
l := opts.Logger | ||
if l == nil { | ||
l = log.NewNopLogger() | ||
} | ||
concurrency := opts.Concurrency | ||
if concurrency < 1 { | ||
concurrency = runtime.GOMAXPROCS(0) | ||
if concurrency < 8 { | ||
concurrency = 8 | ||
} | ||
} | ||
|
||
v1 := apiv1.New( | ||
alerts, | ||
silences, | ||
sf, | ||
peer, | ||
opts.Alerts, | ||
opts.Silences, | ||
opts.StatusFunc, | ||
opts.Peer, | ||
log.With(l, "version", "v1"), | ||
opts.Registry, | ||
) | ||
|
||
v2, err := apiv2.NewAPI( | ||
alerts, | ||
sf, | ||
silences, | ||
peer, | ||
opts.Alerts, | ||
opts.StatusFunc, | ||
opts.Silences, | ||
opts.Peer, | ||
log.With(l, "version", "v2"), | ||
) | ||
|
||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// TODO(beorn7): For now, this hardcodes the method="get" label. Other | ||
// methods should get the same instrumentation. | ||
requestsInFlight := prometheus.NewGauge(prometheus.GaugeOpts{ | ||
Name: "alertmanager_http_requests_in_flight", | ||
Help: "Current number of HTTP requests being processed.", | ||
ConstLabels: prometheus.Labels{"method": "get"}, | ||
}) | ||
concurrencyLimitExceeded := prometheus.NewCounter(prometheus.CounterOpts{ | ||
Name: "alertmanager_http_concurrency_limit_exceeded_total", | ||
Help: "Total number of times an HTTP request failed because the concurrency limit was reached.", | ||
ConstLabels: prometheus.Labels{"method": "get"}, | ||
}) | ||
if opts.Registry != nil { | ||
if err := opts.Registry.Register(requestsInFlight); err != nil { | ||
return nil, err | ||
} | ||
if err := opts.Registry.Register(concurrencyLimitExceeded); err != nil { | ||
return nil, err | ||
} | ||
} | ||
|
||
return &API{ | ||
v1: v1, | ||
v2: v2, | ||
v1: v1, | ||
v2: v2, | ||
requestsInFlight: requestsInFlight, | ||
concurrencyLimitExceeded: concurrencyLimitExceeded, | ||
timeout: opts.Timeout, | ||
inFlightSem: make(chan struct{}, concurrency), | ||
}, nil | ||
} | ||
|
||
// Register all APIs with the given router and return a mux. | ||
// Register all APIs. It registers APIv1 with the provided router directly. As | ||
// APIv2 works on the http.Handler level, this method also creates a new | ||
// http.ServeMux and then uses it to register both the provided router (to | ||
// handle "/") and APIv2 (to handle "<routePrefix>/api/v2"). The method returns | ||
// the newly created http.ServeMux. If a timeout has been set on construction of | ||
// API, it is enforced for all HTTP request going through this mux. The same is | ||
// true for the concurrency limit, with the exception that it is only applied to | ||
// GET requests. | ||
func (api *API) Register(r *route.Router, routePrefix string) *http.ServeMux { | ||
api.v1.Register(r.WithPrefix("/api/v1")) | ||
|
||
mux := http.NewServeMux() | ||
mux.Handle("/", r) | ||
mux.Handle("/", api.limitHandler(r)) | ||
|
||
apiPrefix := "" | ||
if routePrefix != "/" { | ||
apiPrefix = routePrefix | ||
} | ||
mux.Handle(apiPrefix+"/api/v2/", http.StripPrefix(apiPrefix+"/api/v2", api.v2.Handler)) | ||
// TODO(beorn7): HTTP instrumentation is only in place for Router. Since | ||
// /api/v2 works on the Handler level, it is currently not instrumented | ||
// at all (with the exception of requestsInFlight, which is handled in | ||
// limitHandler below). | ||
mux.Handle( | ||
apiPrefix+"/api/v2/", | ||
api.limitHandler(http.StripPrefix(apiPrefix+"/api/v2", api.v2.Handler)), | ||
) | ||
|
||
return mux | ||
} | ||
|
@@ -94,3 +191,31 @@ func (api *API) Update(cfg *config.Config, resolveTimeout time.Duration) error { | |
|
||
return api.v2.Update(cfg, resolveTimeout) | ||
} | ||
|
||
func (api *API) limitHandler(h http.Handler) http.Handler { | ||
concLimiter := http.HandlerFunc(func(rsp http.ResponseWriter, req *http.Request) { | ||
if req.Method == http.MethodGet { // Only limit concurrency of GETs. | ||
select { | ||
case api.inFlightSem <- struct{}{}: // All good, carry on. | ||
api.requestsInFlight.Inc() | ||
defer func() { | ||
<-api.inFlightSem | ||
api.requestsInFlight.Dec() | ||
}() | ||
default: | ||
api.concurrencyLimitExceeded.Inc() | ||
http.Error(rsp, fmt.Sprintf( | ||
"Limit of concurrent GET requests reached (%d), try again later.\n", cap(api.inFlightSem), | ||
), http.StatusServiceUnavailable) | ||
return | ||
} | ||
} | ||
h.ServeHTTP(rsp, req) | ||
}) | ||
if api.timeout <= 0 { | ||
return concLimiter | ||
} | ||
return http.TimeoutHandler(concLimiter, api.timeout, fmt.Sprintf( | ||
"Exceeded configured timeout of %v.\n", api.timeout, | ||
)) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is only used in the handler, right? How about initializing it in the handler constructor closure?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The problem is that we call
limitHandler
twice, once to handle the router handler, once to handle the apiv2 handler. If we moved theinFlightSem
intolimitHandler
, we would limit the GET requests separately for each one. But we want one limit for all of the HTTP handling. (That was the reason why I had a function that returns a function (the middleware) that returns a function (the HandlerFunc) in the previous version. I could avoid that confusion by having inFlightSem as a member ofAPI
and limitHandler a method ofAPI
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@mxinden did my comment clarify the issue? Or do you think this should be changed in another way?