1 // Copyright 2016 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
14 // Package promhttp provides tooling around HTTP servers and clients.
16 // First, the package allows the creation of http.Handler instances to expose
17 // Prometheus metrics via HTTP. promhttp.Handler acts on the
18 // prometheus.DefaultGatherer. With HandlerFor, you can create a handler for a
19 // custom registry or anything that implements the Gatherer interface. It also
20 // allows the creation of handlers that act differently on errors or allow to
23 // Second, the package provides tooling to instrument instances of http.Handler
24 // via middleware. Middleware wrappers follow the naming scheme
25 // InstrumentHandlerX, where X describes the intended use of the middleware.
26 // See each function's doc comment for specific details.
28 // Finally, the package allows for an http.RoundTripper to be instrumented via
29 // middleware. Middleware wrappers follow the naming scheme
30 // InstrumentRoundTripperX, where X describes the intended use of the
31 // middleware. See each function's doc comment for specific details.
43 "github.com/prometheus/common/expfmt"
45 "github.com/prometheus/client_golang/prometheus"
49 contentTypeHeader = "Content-Type"
50 contentEncodingHeader = "Content-Encoding"
51 acceptEncodingHeader = "Accept-Encoding"
54 var gzipPool = sync.Pool{
55 New: func() interface{} {
56 return gzip.NewWriter(nil)
60 // Handler returns an http.Handler for the prometheus.DefaultGatherer, using
61 // default HandlerOpts, i.e. it reports the first error as an HTTP error, it has
62 // no error logging, and it applies compression if requested by the client.
64 // The returned http.Handler is already instrumented using the
65 // InstrumentMetricHandler function and the prometheus.DefaultRegisterer. If you
66 // create multiple http.Handlers by separate calls of the Handler function, the
67 // metrics used for instrumentation will be shared between them, providing
68 // global scrape counts.
70 // This function is meant to cover the bulk of basic use cases. If you are doing
71 // anything that requires more customization (including using a non-default
72 // Gatherer, different instrumentation, and non-default HandlerOpts), use the
73 // HandlerFor function. See there for details.
74 func Handler() http.Handler {
75 return InstrumentMetricHandler(
76 prometheus.DefaultRegisterer, HandlerFor(prometheus.DefaultGatherer, HandlerOpts{}),
80 // HandlerFor returns an uninstrumented http.Handler for the provided
81 // Gatherer. The behavior of the Handler is defined by the provided
82 // HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom
83 // Gatherers, with non-default HandlerOpts, and/or with custom (or no)
84 // instrumentation. Use the InstrumentMetricHandler function to apply the same
85 // kind of instrumentation as it is used by the Handler function.
86 func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
87 var inFlightSem chan struct{}
88 if opts.MaxRequestsInFlight > 0 {
89 inFlightSem = make(chan struct{}, opts.MaxRequestsInFlight)
92 h := http.HandlerFunc(func(rsp http.ResponseWriter, req *http.Request) {
93 if inFlightSem != nil {
95 case inFlightSem <- struct{}{}: // All good, carry on.
96 defer func() { <-inFlightSem }()
98 http.Error(rsp, fmt.Sprintf(
99 "Limit of concurrent requests reached (%d), try again later.", opts.MaxRequestsInFlight,
100 ), http.StatusServiceUnavailable)
104 mfs, err := reg.Gather()
106 if opts.ErrorLog != nil {
107 opts.ErrorLog.Println("error gathering metrics:", err)
109 switch opts.ErrorHandling {
112 case ContinueOnError:
114 // Still report the error if no metrics have been gathered.
118 case HTTPErrorOnError:
124 contentType := expfmt.Negotiate(req.Header)
125 header := rsp.Header()
126 header.Set(contentTypeHeader, string(contentType))
129 if !opts.DisableCompression && gzipAccepted(req.Header) {
130 header.Set(contentEncodingHeader, "gzip")
131 gz := gzipPool.Get().(*gzip.Writer)
132 defer gzipPool.Put(gz)
140 enc := expfmt.NewEncoder(w, contentType)
143 for _, mf := range mfs {
144 if err := enc.Encode(mf); err != nil {
146 if opts.ErrorLog != nil {
147 opts.ErrorLog.Println("error encoding and sending metric family:", err)
149 switch opts.ErrorHandling {
152 case ContinueOnError:
154 case HTTPErrorOnError:
162 httpError(rsp, lastErr)
166 if opts.Timeout <= 0 {
169 return http.TimeoutHandler(h, opts.Timeout, fmt.Sprintf(
170 "Exceeded configured timeout of %v.\n",
175 // InstrumentMetricHandler is usually used with an http.Handler returned by the
176 // HandlerFor function. It instruments the provided http.Handler with two
177 // metrics: A counter vector "promhttp_metric_handler_requests_total" to count
178 // scrapes partitioned by HTTP status code, and a gauge
179 // "promhttp_metric_handler_requests_in_flight" to track the number of
180 // simultaneous scrapes. This function idempotently registers collectors for
181 // both metrics with the provided Registerer. It panics if the registration
182 // fails. The provided metrics are useful to see how many scrapes hit the
183 // monitored target (which could be from different Prometheus servers or other
184 // scrapers), and how often they overlap (which would result in more than one
185 // scrape in flight at the same time). Note that the scrapes-in-flight gauge
186 // will contain the scrape by which it is exposed, while the scrape counter will
187 // only get incremented after the scrape is complete (as only then the status
188 // code is known). For tracking scrape durations, use the
189 // "scrape_duration_seconds" gauge created by the Prometheus server upon each
191 func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) http.Handler {
192 cnt := prometheus.NewCounterVec(
193 prometheus.CounterOpts{
194 Name: "promhttp_metric_handler_requests_total",
195 Help: "Total number of scrapes by HTTP status code.",
199 // Initialize the most likely HTTP status codes.
200 cnt.WithLabelValues("200")
201 cnt.WithLabelValues("500")
202 cnt.WithLabelValues("503")
203 if err := reg.Register(cnt); err != nil {
204 if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
205 cnt = are.ExistingCollector.(*prometheus.CounterVec)
211 gge := prometheus.NewGauge(prometheus.GaugeOpts{
212 Name: "promhttp_metric_handler_requests_in_flight",
213 Help: "Current number of scrapes being served.",
215 if err := reg.Register(gge); err != nil {
216 if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
217 gge = are.ExistingCollector.(prometheus.Gauge)
223 return InstrumentHandlerCounter(cnt, InstrumentHandlerInFlight(gge, handler))
226 // HandlerErrorHandling defines how a Handler serving metrics will handle
228 type HandlerErrorHandling int
230 // These constants cause handlers serving metrics to behave as described if
231 // errors are encountered.
233 // Serve an HTTP status code 500 upon the first error
234 // encountered. Report the error message in the body.
235 HTTPErrorOnError HandlerErrorHandling = iota
236 // Ignore errors and try to serve as many metrics as possible. However,
237 // if no metrics can be served, serve an HTTP status code 500 and the
238 // last error message in the body. Only use this in deliberate "best
239 // effort" metrics collection scenarios. It is recommended to at least
240 // log errors (by providing an ErrorLog in HandlerOpts) to not mask
241 // errors completely.
243 // Panic upon the first error encountered (useful for "crash only" apps).
247 // Logger is the minimal interface HandlerOpts needs for logging. Note that
248 // log.Logger from the standard library implements this interface, and it is
249 // easy to implement by custom loggers, if they don't do so already anyway.
250 type Logger interface {
251 Println(v ...interface{})
254 // HandlerOpts specifies options how to serve metrics via an http.Handler. The
255 // zero value of HandlerOpts is a reasonable default.
256 type HandlerOpts struct {
257 // ErrorLog specifies an optional logger for errors collecting and
258 // serving metrics. If nil, errors are not logged at all.
260 // ErrorHandling defines how errors are handled. Note that errors are
261 // logged regardless of the configured ErrorHandling provided ErrorLog
263 ErrorHandling HandlerErrorHandling
264 // If DisableCompression is true, the handler will never compress the
265 // response, even if requested by the client.
266 DisableCompression bool
267 // The number of concurrent HTTP requests is limited to
268 // MaxRequestsInFlight. Additional requests are responded to with 503
269 // Service Unavailable and a suitable message in the body. If
270 // MaxRequestsInFlight is 0 or negative, no limit is applied.
271 MaxRequestsInFlight int
272 // If handling a request takes longer than Timeout, it is responded to
273 // with 503 ServiceUnavailable and a suitable Message. No timeout is
274 // applied if Timeout is 0 or negative. Note that with the current
275 // implementation, reaching the timeout simply ends the HTTP requests as
276 // described above (and even that only if sending of the body hasn't
277 // started yet), while the bulk work of gathering all the metrics keeps
278 // running in the background (with the eventual result to be thrown
279 // away). Until the implementation is improved, it is recommended to
280 // implement a separate timeout in potentially slow Collectors.
281 Timeout time.Duration
284 // gzipAccepted returns whether the client will accept gzip-encoded content.
285 func gzipAccepted(header http.Header) bool {
286 a := header.Get(acceptEncodingHeader)
287 parts := strings.Split(a, ",")
288 for _, part := range parts {
289 part = strings.TrimSpace(part)
290 if part == "gzip" || strings.HasPrefix(part, "gzip;") {
297 // httpError removes any content-encoding header and then calls http.Error with
298 // the provided error and http.StatusInternalServerErrer. Error contents is
299 // supposed to be uncompressed plain text. However, same as with a plain
300 // http.Error, any header settings will be void if the header has already been
301 // sent. The error message will still be written to the writer, but it will
302 // probably be of limited use.
303 func httpError(rsp http.ResponseWriter, err error) {
304 rsp.Header().Del(contentEncodingHeader)
307 "An error has occurred while serving metrics:\n\n"+err.Error(),
308 http.StatusInternalServerError,