Debian Codegraph @

prometheus/promhttp/http.go

raw
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
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
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.
13
14 // Package promhttp provides tooling around HTTP servers and clients.
15 //
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
21 // log errors.
22 //
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.
27 //
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.
32 package promhttp
33
34 import (
35 "compress/gzip"
36 "errors"
37 "fmt"
38 "io"
39 "net/http"
40 "strconv"
41 "sync"
42 "time"
43
44 "github.com/prometheus/common/expfmt"
45
46 "github.com/prometheus/client_golang/internal/github.com/golang/gddo/httputil"
47 "github.com/prometheus/client_golang/prometheus"
48 "github.com/prometheus/client_golang/prometheus/promhttp/internal"
49 )
50
51 const (
52 contentTypeHeader = "Content-Type"
53 contentEncodingHeader = "Content-Encoding"
54 acceptEncodingHeader = "Accept-Encoding"
55 processStartTimeHeader = "Process-Start-Time-Unix"
56 )
57
58 // Compression represents the content encodings handlers support for the HTTP
59 // responses.
60 type Compression string
61
62 const (
63 Identity Compression = "identity"
64 Gzip Compression = "gzip"
65 Zstd Compression = "zstd"
66 )
67
68 func defaultCompressionFormats() []Compression {
69 if internal.NewZstdWriter != nil {
70 return []Compression{Identity, Gzip, Zstd}
71 } else {
72 return []Compression{Identity, Gzip}
73 }
74 }
75
76 var gzipPool = sync.Pool{
77 New: func() interface{} {
78 return gzip.NewWriter(nil)
79 },
80 }
81
82 // Handler returns an http.Handler for the prometheus.DefaultGatherer, using
83 // default HandlerOpts, i.e. it reports the first error as an HTTP error, it has
84 // no error logging, and it applies compression if requested by the client.
85 //
86 // The returned http.Handler is already instrumented using the
87 // InstrumentMetricHandler function and the prometheus.DefaultRegisterer. If you
88 // create multiple http.Handlers by separate calls of the Handler function, the
89 // metrics used for instrumentation will be shared between them, providing
90 // global scrape counts.
91 //
92 // This function is meant to cover the bulk of basic use cases. If you are doing
93 // anything that requires more customization (including using a non-default
94 // Gatherer, different instrumentation, and non-default HandlerOpts), use the
95 // HandlerFor function. See there for details.
96 func Handler() http.Handler {
97 return InstrumentMetricHandler(
98 prometheus.DefaultRegisterer, HandlerFor(prometheus.DefaultGatherer, HandlerOpts{}),
99 )
100 }
101
102 // HandlerFor returns an uninstrumented http.Handler for the provided
103 // Gatherer. The behavior of the Handler is defined by the provided
104 // HandlerOpts. Thus, HandlerFor is useful to create http.Handlers for custom
105 // Gatherers, with non-default HandlerOpts, and/or with custom (or no)
106 // instrumentation. Use the InstrumentMetricHandler function to apply the same
107 // kind of instrumentation as it is used by the Handler function.
108 func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
109 return HandlerForTransactional(prometheus.ToTransactionalGatherer(reg), opts)
110 }
111
112 // HandlerForTransactional is like HandlerFor, but it uses transactional gather, which
113 // can safely change in-place returned *dto.MetricFamily before call to `Gather` and after
114 // call to `done` of that `Gather`.
115 func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerOpts) http.Handler {
116 var (
117 inFlightSem chan struct{}
118 errCnt = prometheus.NewCounterVec(
119 prometheus.CounterOpts{
120 Name: "promhttp_metric_handler_errors_total",
121 Help: "Total number of internal errors encountered by the promhttp metric handler.",
122 },
123 []string{"cause"},
124 )
125 )
126
127 if opts.MaxRequestsInFlight > 0 {
128 inFlightSem = make(chan struct{}, opts.MaxRequestsInFlight)
129 }
130 if opts.Registry != nil {
131 // Initialize all possibilities that can occur below.
132 errCnt.WithLabelValues("gathering")
133 errCnt.WithLabelValues("encoding")
134 if err := opts.Registry.Register(errCnt); err != nil {
135 are := &prometheus.AlreadyRegisteredError{}
136 if errors.As(err, are) {
137 errCnt = are.ExistingCollector.(*prometheus.CounterVec)
138 } else {
139 panic(err)
140 }
141 }
142 }
143
144 // Select compression formats to offer based on default or user choice.
145 var compressions []string
146 if !opts.DisableCompression {
147 offers := defaultCompressionFormats()
148 if len(opts.OfferedCompressions) > 0 {
149 offers = opts.OfferedCompressions
150 }
151 for _, comp := range offers {
152 compressions = append(compressions, string(comp))
153 }
154 }
155
156 h := http.HandlerFunc(func(rsp http.ResponseWriter, req *http.Request) {
157 if !opts.ProcessStartTime.IsZero() {
158 rsp.Header().Set(processStartTimeHeader, strconv.FormatInt(opts.ProcessStartTime.Unix(), 10))
159 }
160 if inFlightSem != nil {
161 select {
162 case inFlightSem <- struct{}{}: // All good, carry on.
163 defer func() { <-inFlightSem }()
164 default:
165 http.Error(rsp, fmt.Sprintf(
166 "Limit of concurrent requests reached (%d), try again later.", opts.MaxRequestsInFlight,
167 ), http.StatusServiceUnavailable)
168 return
169 }
170 }
171 mfs, done, err := reg.Gather()
172 defer done()
173 if err != nil {
174 if opts.ErrorLog != nil {
175 opts.ErrorLog.Println("error gathering metrics:", err)
176 }
177 errCnt.WithLabelValues("gathering").Inc()
178 switch opts.ErrorHandling {
179 case PanicOnError:
180 panic(err)
181 case ContinueOnError:
182 if len(mfs) == 0 {
183 // Still report the error if no metrics have been gathered.
184 httpError(rsp, err)
185 return
186 }
187 case HTTPErrorOnError:
188 httpError(rsp, err)
189 return
190 }
191 }
192
193 var contentType expfmt.Format
194 if opts.EnableOpenMetrics {
195 contentType = expfmt.NegotiateIncludingOpenMetrics(req.Header)
196 } else {
197 contentType = expfmt.Negotiate(req.Header)
198 }
199 rsp.Header().Set(contentTypeHeader, string(contentType))
200
201 w, encodingHeader, closeWriter, err := negotiateEncodingWriter(req, rsp, compressions)
202 if err != nil {
203 if opts.ErrorLog != nil {
204 opts.ErrorLog.Println("error getting writer", err)
205 }
206 w = io.Writer(rsp)
207 encodingHeader = string(Identity)
208 }
209
210 defer closeWriter()
211
212 // Set Content-Encoding only when data is compressed
213 if encodingHeader != string(Identity) {
214 rsp.Header().Set(contentEncodingHeader, encodingHeader)
215 }
216
217 var enc expfmt.Encoder
218 if opts.EnableOpenMetricsTextCreatedSamples {
219 enc = expfmt.NewEncoder(w, contentType, expfmt.WithCreatedLines())
220 } else {
221 enc = expfmt.NewEncoder(w, contentType)
222 }
223
224 // handleError handles the error according to opts.ErrorHandling
225 // and returns true if we have to abort after the handling.
226 handleError := func(err error) bool {
227 if err == nil {
228 return false
229 }
230 if opts.ErrorLog != nil {
231 opts.ErrorLog.Println("error encoding and sending metric family:", err)
232 }
233 errCnt.WithLabelValues("encoding").Inc()
234 switch opts.ErrorHandling {
235 case PanicOnError:
236 panic(err)
237 case HTTPErrorOnError:
238 // We cannot really send an HTTP error at this
239 // point because we most likely have written
240 // something to rsp already. But at least we can
241 // stop sending.
242 return true
243 }
244 // Do nothing in all other cases, including ContinueOnError.
245 return false
246 }
247
248 for _, mf := range mfs {
249 if handleError(enc.Encode(mf)) {
250 return
251 }
252 }
253 if closer, ok := enc.(expfmt.Closer); ok {
254 // This in particular takes care of the final "# EOF\n" line for OpenMetrics.
255 if handleError(closer.Close()) {
256 return
257 }
258 }
259 })
260
261 if opts.Timeout <= 0 {
262 return h
263 }
264 return http.TimeoutHandler(h, opts.Timeout, fmt.Sprintf(
265 "Exceeded configured timeout of %v.\n",
266 opts.Timeout,
267 ))
268 }
269
270 // InstrumentMetricHandler is usually used with an http.Handler returned by the
271 // HandlerFor function. It instruments the provided http.Handler with two
272 // metrics: A counter vector "promhttp_metric_handler_requests_total" to count
273 // scrapes partitioned by HTTP status code, and a gauge
274 // "promhttp_metric_handler_requests_in_flight" to track the number of
275 // simultaneous scrapes. This function idempotently registers collectors for
276 // both metrics with the provided Registerer. It panics if the registration
277 // fails. The provided metrics are useful to see how many scrapes hit the
278 // monitored target (which could be from different Prometheus servers or other
279 // scrapers), and how often they overlap (which would result in more than one
280 // scrape in flight at the same time). Note that the scrapes-in-flight gauge
281 // will contain the scrape by which it is exposed, while the scrape counter will
282 // only get incremented after the scrape is complete (as only then the status
283 // code is known). For tracking scrape durations, use the
284 // "scrape_duration_seconds" gauge created by the Prometheus server upon each
285 // scrape.
286 func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) http.Handler {
287 cnt := prometheus.NewCounterVec(
288 prometheus.CounterOpts{
289 Name: "promhttp_metric_handler_requests_total",
290 Help: "Total number of scrapes by HTTP status code.",
291 },
292 []string{"code"},
293 )
294 // Initialize the most likely HTTP status codes.
295 cnt.WithLabelValues("200")
296 cnt.WithLabelValues("500")
297 cnt.WithLabelValues("503")
298 if err := reg.Register(cnt); err != nil {
299 are := &prometheus.AlreadyRegisteredError{}
300 if errors.As(err, are) {
301 cnt = are.ExistingCollector.(*prometheus.CounterVec)
302 } else {
303 panic(err)
304 }
305 }
306
307 gge := prometheus.NewGauge(prometheus.GaugeOpts{
308 Name: "promhttp_metric_handler_requests_in_flight",
309 Help: "Current number of scrapes being served.",
310 })
311 if err := reg.Register(gge); err != nil {
312 are := &prometheus.AlreadyRegisteredError{}
313 if errors.As(err, are) {
314 gge = are.ExistingCollector.(prometheus.Gauge)
315 } else {
316 panic(err)
317 }
318 }
319
320 return InstrumentHandlerCounter(cnt, InstrumentHandlerInFlight(gge, handler))
321 }
322
323 // HandlerErrorHandling defines how a Handler serving metrics will handle
324 // errors.
325 type HandlerErrorHandling int
326
327 // These constants cause handlers serving metrics to behave as described if
328 // errors are encountered.
329 const (
330 // Serve an HTTP status code 500 upon the first error
331 // encountered. Report the error message in the body. Note that HTTP
332 // errors cannot be served anymore once the beginning of a regular
333 // payload has been sent. Thus, in the (unlikely) case that encoding the
334 // payload into the negotiated wire format fails, serving the response
335 // will simply be aborted. Set an ErrorLog in HandlerOpts to detect
336 // those errors.
337 HTTPErrorOnError HandlerErrorHandling = iota
338 // Ignore errors and try to serve as many metrics as possible. However,
339 // if no metrics can be served, serve an HTTP status code 500 and the
340 // last error message in the body. Only use this in deliberate "best
341 // effort" metrics collection scenarios. In this case, it is highly
342 // recommended to provide other means of detecting errors: By setting an
343 // ErrorLog in HandlerOpts, the errors are logged. By providing a
344 // Registry in HandlerOpts, the exposed metrics include an error counter
345 // "promhttp_metric_handler_errors_total", which can be used for
346 // alerts.
347 ContinueOnError
348 // Panic upon the first error encountered (useful for "crash only" apps).
349 PanicOnError
350 )
351
352 // Logger is the minimal interface HandlerOpts needs for logging. Note that
353 // log.Logger from the standard library implements this interface, and it is
354 // easy to implement by custom loggers, if they don't do so already anyway.
355 type Logger interface {
356 Println(v ...interface{})
357 }
358
359 // HandlerOpts specifies options how to serve metrics via an http.Handler. The
360 // zero value of HandlerOpts is a reasonable default.
361 type HandlerOpts struct {
362 // ErrorLog specifies an optional Logger for errors collecting and
363 // serving metrics. If nil, errors are not logged at all. Note that the
364 // type of a reported error is often prometheus.MultiError, which
365 // formats into a multi-line error string. If you want to avoid the
366 // latter, create a Logger implementation that detects a
367 // prometheus.MultiError and formats the contained errors into one line.
368 ErrorLog Logger
369 // ErrorHandling defines how errors are handled. Note that errors are
370 // logged regardless of the configured ErrorHandling provided ErrorLog
371 // is not nil.
372 ErrorHandling HandlerErrorHandling
373 // If Registry is not nil, it is used to register a metric
374 // "promhttp_metric_handler_errors_total", partitioned by "cause". A
375 // failed registration causes a panic. Note that this error counter is
376 // different from the instrumentation you get from the various
377 // InstrumentHandler... helpers. It counts errors that don't necessarily
378 // result in a non-2xx HTTP status code. There are two typical cases:
379 // (1) Encoding errors that only happen after streaming of the HTTP body
380 // has already started (and the status code 200 has been sent). This
381 // should only happen with custom collectors. (2) Collection errors with
382 // no effect on the HTTP status code because ErrorHandling is set to
383 // ContinueOnError.
384 Registry prometheus.Registerer
385 // DisableCompression disables the response encoding (compression) and
386 // encoding negotiation. If true, the handler will
387 // never compress the response, even if requested
388 // by the client and the OfferedCompressions field is set.
389 DisableCompression bool
390 // OfferedCompressions is a set of encodings (compressions) handler will
391 // try to offer when negotiating with the client. This defaults to identity, gzip
392 // and zstd.
393 // NOTE: If handler can't agree with the client on the encodings or
394 // unsupported or empty encodings are set in OfferedCompressions,
395 // handler always fallbacks to no compression (identity), for
396 // compatibility reasons. In such cases ErrorLog will be used if set.
397 OfferedCompressions []Compression
398 // The number of concurrent HTTP requests is limited to
399 // MaxRequestsInFlight. Additional requests are responded to with 503
400 // Service Unavailable and a suitable message in the body. If
401 // MaxRequestsInFlight is 0 or negative, no limit is applied.
402 MaxRequestsInFlight int
403 // If handling a request takes longer than Timeout, it is responded to
404 // with 503 ServiceUnavailable and a suitable Message. No timeout is
405 // applied if Timeout is 0 or negative. Note that with the current
406 // implementation, reaching the timeout simply ends the HTTP requests as
407 // described above (and even that only if sending of the body hasn't
408 // started yet), while the bulk work of gathering all the metrics keeps
409 // running in the background (with the eventual result to be thrown
410 // away). Until the implementation is improved, it is recommended to
411 // implement a separate timeout in potentially slow Collectors.
412 Timeout time.Duration
413 // If true, the experimental OpenMetrics encoding is added to the
414 // possible options during content negotiation. Note that Prometheus
415 // 2.5.0+ will negotiate OpenMetrics as first priority. OpenMetrics is
416 // the only way to transmit exemplars. However, the move to OpenMetrics
417 // is not completely transparent. Most notably, the values of "quantile"
418 // labels of Summaries and "le" labels of Histograms are formatted with
419 // a trailing ".0" if they would otherwise look like integer numbers
420 // (which changes the identity of the resulting series on the Prometheus
421 // server).
422 EnableOpenMetrics bool
423 // EnableOpenMetricsTextCreatedSamples specifies if this handler should add, extra, synthetic
424 // Created Timestamps for counters, histograms and summaries, which for the current
425 // version of OpenMetrics are defined as extra series with the same name and "_created"
426 // suffix. See also the OpenMetrics specification for more details
427 // https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#counter-1
428 //
429 // Created timestamps are used to improve the accuracy of reset detection,
430 // but the way it's designed in OpenMetrics 1.0 it also dramatically increases cardinality
431 // if the scraper does not handle those metrics correctly (converting to created timestamp
432 // instead of leaving those series as-is). New OpenMetrics versions might improve
433 // this situation.
434 //
435 // Prometheus introduced the feature flag 'created-timestamp-zero-ingestion'
436 // in version 2.50.0 to handle this situation.
437 EnableOpenMetricsTextCreatedSamples bool
438 // ProcessStartTime allows setting process start timevalue that will be exposed
439 // with "Process-Start-Time-Unix" response header along with the metrics
440 // payload. This allow callers to have efficient transformations to cumulative
441 // counters (e.g. OpenTelemetry) or generally _created timestamp estimation per
442 // scrape target.
443 // NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus
444 // exposition format.
445 ProcessStartTime time.Time
446 }
447
448 // httpError removes any content-encoding header and then calls http.Error with
449 // the provided error and http.StatusInternalServerError. Error contents is
450 // supposed to be uncompressed plain text. Same as with a plain http.Error, this
451 // must not be called if the header or any payload has already been sent.
452 func httpError(rsp http.ResponseWriter, err error) {
453 rsp.Header().Del(contentEncodingHeader)
454 http.Error(
455 rsp,
456 "An error has occurred while serving metrics:\n\n"+err.Error(),
457 http.StatusInternalServerError,
458 )
459 }
460
461 // negotiateEncodingWriter reads the Accept-Encoding header from a request and
462 // selects the right compression based on an allow-list of supported
463 // compressions. It returns a writer implementing the compression and an the
464 // correct value that the caller can set in the response header.
465 func negotiateEncodingWriter(r *http.Request, rw io.Writer, compressions []string) (_ io.Writer, encodingHeaderValue string, closeWriter func(), _ error) {
466 if len(compressions) == 0 {
467 return rw, string(Identity), func() {}, nil
468 }
469
470 // TODO(mrueg): Replace internal/github.com/gddo once https://github.com/golang/go/issues/19307 is implemented.
471 selected := httputil.NegotiateContentEncoding(r, compressions)
472
473 switch selected {
474 case "zstd":
475 if internal.NewZstdWriter == nil {
476 // The content encoding was not implemented yet.
477 return nil, "", func() {}, fmt.Errorf("content compression format not recognized: %s. Valid formats are: %s", selected, defaultCompressionFormats())
478 }
479 writer, closeWriter, err := internal.NewZstdWriter(rw)
480 return writer, selected, closeWriter, err
481 case "gzip":
482 gz := gzipPool.Get().(*gzip.Writer)
483 gz.Reset(rw)
484 return gz, selected, func() { _ = gz.Close(); gzipPool.Put(gz) }, nil
485 case "identity":
486 // This means the content is not compressed.
487 return rw, selected, func() {}, nil
488 default:
489 // The content encoding was not implemented yet.
490 return nil, "", func() {}, fmt.Errorf("content compression format not recognized: %s. Valid formats are: %s", selected, defaultCompressionFormats())
491 }
492 }