Debian Codegraph @

prometheus/promhttp/instrument_server.go

raw
1 // Copyright 2017 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
15
16 import (
17 "errors"
18 "net/http"
19 "strconv"
20 "strings"
21 "time"
22
23 dto "github.com/prometheus/client_model/go"
24
25 "github.com/prometheus/client_golang/prometheus"
26 )
27
28 // magicString is used for the hacky label test in checkLabels. Remove once fixed.
29 const magicString = "zZgWfBxLqvG8kc8IMv3POi2Bb0tZI3vAnBx+gBaFi9FyPzB/CzKUer1yufDa"
30
31 // observeWithExemplar is a wrapper for [prometheus.ExemplarAdder.ExemplarObserver],
32 // which falls back to [prometheus.Observer.Observe] if no labels are provided.
33 func observeWithExemplar(obs prometheus.Observer, val float64, labels map[string]string) {
34 if labels == nil {
35 obs.Observe(val)
36 return
37 }
38 obs.(prometheus.ExemplarObserver).ObserveWithExemplar(val, labels)
39 }
40
41 // addWithExemplar is a wrapper for [prometheus.ExemplarAdder.AddWithExemplar],
42 // which falls back to [prometheus.Counter.Add] if no labels are provided.
43 func addWithExemplar(obs prometheus.Counter, val float64, labels map[string]string) {
44 if labels == nil {
45 obs.Add(val)
46 return
47 }
48 obs.(prometheus.ExemplarAdder).AddWithExemplar(val, labels)
49 }
50
51 // InstrumentHandlerInFlight is a middleware that wraps the provided
52 // http.Handler. It sets the provided prometheus.Gauge to the number of
53 // requests currently handled by the wrapped http.Handler.
54 //
55 // See the example for InstrumentHandlerDuration for example usage.
56 func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handler {
57 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
58 g.Inc()
59 defer g.Dec()
60 next.ServeHTTP(w, r)
61 })
62 }
63
64 // InstrumentHandlerDuration is a middleware that wraps the provided
65 // http.Handler to observe the request duration with the provided ObserverVec.
66 // The ObserverVec must have valid metric and label names and must have zero,
67 // one, or two non-const non-curried labels. For those, the only allowed label
68 // names are "code" and "method". The function panics otherwise. For the "method"
69 // label a predefined default label value set is used to filter given values.
70 // Values besides predefined values will count as `unknown` method.
71 // `WithExtraMethods` can be used to add more methods to the set. The Observe
72 // method of the Observer in the ObserverVec is called with the request duration
73 // in seconds. Partitioning happens by HTTP status code and/or HTTP method if
74 // the respective instance label names are present in the ObserverVec. For
75 // unpartitioned observations, use an ObserverVec with zero labels. Note that
76 // partitioning of Histograms is expensive and should be used judiciously.
77 //
78 // If the wrapped Handler does not set a status code, a status code of 200 is assumed.
79 //
80 // If the wrapped Handler panics, no values are reported.
81 //
82 // Note that this method is only guaranteed to never observe negative durations
83 // if used with Go1.9+.
84 func InstrumentHandlerDuration(obs prometheus.ObserverVec, next http.Handler, opts ...Option) http.HandlerFunc {
85 hOpts := defaultOptions()
86 for _, o := range opts {
87 o.apply(hOpts)
88 }
89
90 // Curry the observer with dynamic labels before checking the remaining labels.
91 code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
92
93 if code {
94 return func(w http.ResponseWriter, r *http.Request) {
95 now := time.Now()
96 d := newDelegator(w, nil)
97 next.ServeHTTP(d, r)
98
99 l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
100 for label, resolve := range hOpts.extraLabelsFromCtx {
101 l[label] = resolve(r.Context())
102 }
103 observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
104 }
105 }
106
107 return func(w http.ResponseWriter, r *http.Request) {
108 now := time.Now()
109 next.ServeHTTP(w, r)
110 l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
111 for label, resolve := range hOpts.extraLabelsFromCtx {
112 l[label] = resolve(r.Context())
113 }
114 observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
115 }
116 }
117
118 // InstrumentHandlerCounter is a middleware that wraps the provided http.Handler
119 // to observe the request result with the provided CounterVec. The CounterVec
120 // must have valid metric and label names and must have zero, one, or two
121 // non-const non-curried labels. For those, the only allowed label names are
122 // "code" and "method". The function panics otherwise. For the "method"
123 // label a predefined default label value set is used to filter given values.
124 // Values besides predefined values will count as `unknown` method.
125 // `WithExtraMethods` can be used to add more methods to the set. Partitioning of the
126 // CounterVec happens by HTTP status code and/or HTTP method if the respective
127 // instance label names are present in the CounterVec. For unpartitioned
128 // counting, use a CounterVec with zero labels.
129 //
130 // If the wrapped Handler does not set a status code, a status code of 200 is assumed.
131 //
132 // If the wrapped Handler panics, the Counter is not incremented.
133 //
134 // See the example for InstrumentHandlerDuration for example usage.
135 func InstrumentHandlerCounter(counter *prometheus.CounterVec, next http.Handler, opts ...Option) http.HandlerFunc {
136 hOpts := defaultOptions()
137 for _, o := range opts {
138 o.apply(hOpts)
139 }
140
141 // Curry the counter with dynamic labels before checking the remaining labels.
142 code, method := checkLabels(counter.MustCurryWith(hOpts.emptyDynamicLabels()))
143
144 if code {
145 return func(w http.ResponseWriter, r *http.Request) {
146 d := newDelegator(w, nil)
147 next.ServeHTTP(d, r)
148
149 l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
150 for label, resolve := range hOpts.extraLabelsFromCtx {
151 l[label] = resolve(r.Context())
152 }
153 addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
154 }
155 }
156
157 return func(w http.ResponseWriter, r *http.Request) {
158 next.ServeHTTP(w, r)
159
160 l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
161 for label, resolve := range hOpts.extraLabelsFromCtx {
162 l[label] = resolve(r.Context())
163 }
164 addWithExemplar(counter.With(l), 1, hOpts.getExemplarFn(r.Context()))
165 }
166 }
167
168 // InstrumentHandlerTimeToWriteHeader is a middleware that wraps the provided
169 // http.Handler to observe with the provided ObserverVec the request duration
170 // until the response headers are written. The ObserverVec must have valid
171 // metric and label names and must have zero, one, or two non-const non-curried
172 // labels. For those, the only allowed label names are "code" and "method". The
173 // function panics otherwise. For the "method" label a predefined default label
174 // value set is used to filter given values. Values besides predefined values
175 // will count as `unknown` method.`WithExtraMethods` can be used to add more
176 // methods to the set. The Observe method of the Observer in the
177 // ObserverVec is called with the request duration in seconds. Partitioning
178 // happens by HTTP status code and/or HTTP method if the respective instance
179 // label names are present in the ObserverVec. For unpartitioned observations,
180 // use an ObserverVec with zero labels. Note that partitioning of Histograms is
181 // expensive and should be used judiciously.
182 //
183 // If the wrapped Handler panics before calling WriteHeader, no value is
184 // reported.
185 //
186 // Note that this method is only guaranteed to never observe negative durations
187 // if used with Go1.9+.
188 //
189 // See the example for InstrumentHandlerDuration for example usage.
190 func InstrumentHandlerTimeToWriteHeader(obs prometheus.ObserverVec, next http.Handler, opts ...Option) http.HandlerFunc {
191 hOpts := defaultOptions()
192 for _, o := range opts {
193 o.apply(hOpts)
194 }
195
196 // Curry the observer with dynamic labels before checking the remaining labels.
197 code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
198
199 return func(w http.ResponseWriter, r *http.Request) {
200 now := time.Now()
201 d := newDelegator(w, func(status int) {
202 l := labels(code, method, r.Method, status, hOpts.extraMethods...)
203 for label, resolve := range hOpts.extraLabelsFromCtx {
204 l[label] = resolve(r.Context())
205 }
206 observeWithExemplar(obs.With(l), time.Since(now).Seconds(), hOpts.getExemplarFn(r.Context()))
207 })
208 next.ServeHTTP(d, r)
209 }
210 }
211
212 // InstrumentHandlerRequestSize is a middleware that wraps the provided
213 // http.Handler to observe the request size with the provided ObserverVec. The
214 // ObserverVec must have valid metric and label names and must have zero, one,
215 // or two non-const non-curried labels. For those, the only allowed label names
216 // are "code" and "method". The function panics otherwise. For the "method"
217 // label a predefined default label value set is used to filter given values.
218 // Values besides predefined values will count as `unknown` method.
219 // `WithExtraMethods` can be used to add more methods to the set. The Observe
220 // method of the Observer in the ObserverVec is called with the request size in
221 // bytes. Partitioning happens by HTTP status code and/or HTTP method if the
222 // respective instance label names are present in the ObserverVec. For
223 // unpartitioned observations, use an ObserverVec with zero labels. Note that
224 // partitioning of Histograms is expensive and should be used judiciously.
225 //
226 // If the wrapped Handler does not set a status code, a status code of 200 is assumed.
227 //
228 // If the wrapped Handler panics, no values are reported.
229 //
230 // See the example for InstrumentHandlerDuration for example usage.
231 func InstrumentHandlerRequestSize(obs prometheus.ObserverVec, next http.Handler, opts ...Option) http.HandlerFunc {
232 hOpts := defaultOptions()
233 for _, o := range opts {
234 o.apply(hOpts)
235 }
236
237 // Curry the observer with dynamic labels before checking the remaining labels.
238 code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
239
240 if code {
241 return func(w http.ResponseWriter, r *http.Request) {
242 d := newDelegator(w, nil)
243 next.ServeHTTP(d, r)
244 size := computeApproximateRequestSize(r)
245
246 l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
247 for label, resolve := range hOpts.extraLabelsFromCtx {
248 l[label] = resolve(r.Context())
249 }
250 observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
251 }
252 }
253
254 return func(w http.ResponseWriter, r *http.Request) {
255 next.ServeHTTP(w, r)
256 size := computeApproximateRequestSize(r)
257
258 l := labels(code, method, r.Method, 0, hOpts.extraMethods...)
259 for label, resolve := range hOpts.extraLabelsFromCtx {
260 l[label] = resolve(r.Context())
261 }
262 observeWithExemplar(obs.With(l), float64(size), hOpts.getExemplarFn(r.Context()))
263 }
264 }
265
266 // InstrumentHandlerResponseSize is a middleware that wraps the provided
267 // http.Handler to observe the response size with the provided ObserverVec. The
268 // ObserverVec must have valid metric and label names and must have zero, one,
269 // or two non-const non-curried labels. For those, the only allowed label names
270 // are "code" and "method". The function panics otherwise. For the "method"
271 // label a predefined default label value set is used to filter given values.
272 // Values besides predefined values will count as `unknown` method.
273 // `WithExtraMethods` can be used to add more methods to the set. The Observe
274 // method of the Observer in the ObserverVec is called with the response size in
275 // bytes. Partitioning happens by HTTP status code and/or HTTP method if the
276 // respective instance label names are present in the ObserverVec. For
277 // unpartitioned observations, use an ObserverVec with zero labels. Note that
278 // partitioning of Histograms is expensive and should be used judiciously.
279 //
280 // If the wrapped Handler does not set a status code, a status code of 200 is assumed.
281 //
282 // If the wrapped Handler panics, no values are reported.
283 //
284 // See the example for InstrumentHandlerDuration for example usage.
285 func InstrumentHandlerResponseSize(obs prometheus.ObserverVec, next http.Handler, opts ...Option) http.Handler {
286 hOpts := defaultOptions()
287 for _, o := range opts {
288 o.apply(hOpts)
289 }
290
291 // Curry the observer with dynamic labels before checking the remaining labels.
292 code, method := checkLabels(obs.MustCurryWith(hOpts.emptyDynamicLabels()))
293
294 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
295 d := newDelegator(w, nil)
296 next.ServeHTTP(d, r)
297
298 l := labels(code, method, r.Method, d.Status(), hOpts.extraMethods...)
299 for label, resolve := range hOpts.extraLabelsFromCtx {
300 l[label] = resolve(r.Context())
301 }
302 observeWithExemplar(obs.With(l), float64(d.Written()), hOpts.getExemplarFn(r.Context()))
303 })
304 }
305
306 // checkLabels returns whether the provided Collector has a non-const,
307 // non-curried label named "code" and/or "method". It panics if the provided
308 // Collector does not have a Desc or has more than one Desc or its Desc is
309 // invalid. It also panics if the Collector has any non-const, non-curried
310 // labels that are not named "code" or "method".
311 func checkLabels(c prometheus.Collector) (code, method bool) {
312 // TODO(beorn7): Remove this hacky way to check for instance labels
313 // once Descriptors can have their dimensionality queried.
314 var (
315 desc *prometheus.Desc
316 m prometheus.Metric
317 pm dto.Metric
318 lvs []string
319 )
320
321 // Get the Desc from the Collector.
322 descc := make(chan *prometheus.Desc, 1)
323 c.Describe(descc)
324
325 select {
326 case desc = <-descc:
327 default:
328 panic("no description provided by collector")
329 }
330 select {
331 case <-descc:
332 panic("more than one description provided by collector")
333 default:
334 }
335
336 close(descc)
337
338 // Make sure the Collector has a valid Desc by registering it with a
339 // temporary registry.
340 prometheus.NewRegistry().MustRegister(c)
341
342 // Create a ConstMetric with the Desc. Since we don't know how many
343 // variable labels there are, try for as long as it needs.
344 for err := errors.New("dummy"); err != nil; lvs = append(lvs, magicString) {
345 m, err = prometheus.NewConstMetric(desc, prometheus.UntypedValue, 0, lvs...)
346 }
347
348 // Write out the metric into a proto message and look at the labels.
349 // If the value is not the magicString, it is a constLabel, which doesn't interest us.
350 // If the label is curried, it doesn't interest us.
351 // In all other cases, only "code" or "method" is allowed.
352 if err := m.Write(&pm); err != nil {
353 panic("error checking metric for labels")
354 }
355 for _, label := range pm.Label {
356 name, value := label.GetName(), label.GetValue()
357 if value != magicString || isLabelCurried(c, name) {
358 continue
359 }
360 switch name {
361 case "code":
362 code = true
363 case "method":
364 method = true
365 default:
366 panic("metric partitioned with non-supported labels")
367 }
368 }
369 return
370 }
371
372 func isLabelCurried(c prometheus.Collector, label string) bool {
373 // This is even hackier than the label test above.
374 // We essentially try to curry again and see if it works.
375 // But for that, we need to type-convert to the two
376 // types we use here, ObserverVec or *CounterVec.
377 switch v := c.(type) {
378 case *prometheus.CounterVec:
379 if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil {
380 return false
381 }
382 case prometheus.ObserverVec:
383 if _, err := v.CurryWith(prometheus.Labels{label: "dummy"}); err == nil {
384 return false
385 }
386 default:
387 panic("unsupported metric vec type")
388 }
389 return true
390 }
391
392 func labels(code, method bool, reqMethod string, status int, extraMethods ...string) prometheus.Labels {
393 labels := prometheus.Labels{}
394
395 if !code && !method {
396 return labels
397 }
398
399 if code {
400 labels["code"] = sanitizeCode(status)
401 }
402 if method {
403 labels["method"] = sanitizeMethod(reqMethod, extraMethods...)
404 }
405
406 return labels
407 }
408
409 func computeApproximateRequestSize(r *http.Request) int {
410 s := 0
411 if r.URL != nil {
412 s += len(r.URL.String())
413 }
414
415 s += len(r.Method)
416 s += len(r.Proto)
417 for name, values := range r.Header {
418 s += len(name)
419 for _, value := range values {
420 s += len(value)
421 }
422 }
423 s += len(r.Host)
424
425 // N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
426
427 if r.ContentLength != -1 {
428 s += int(r.ContentLength)
429 }
430 return s
431 }
432
433 // If the wrapped http.Handler has a known method, it will be sanitized and returned.
434 // Otherwise, "unknown" will be returned. The known method list can be extended
435 // as needed by using extraMethods parameter.
436 func sanitizeMethod(m string, extraMethods ...string) string {
437 // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods for
438 // the methods chosen as default.
439 switch m {
440 case "GET", "get":
441 return "get"
442 case "PUT", "put":
443 return "put"
444 case "HEAD", "head":
445 return "head"
446 case "POST", "post":
447 return "post"
448 case "DELETE", "delete":
449 return "delete"
450 case "CONNECT", "connect":
451 return "connect"
452 case "OPTIONS", "options":
453 return "options"
454 case "NOTIFY", "notify":
455 return "notify"
456 case "TRACE", "trace":
457 return "trace"
458 case "PATCH", "patch":
459 return "patch"
460 default:
461 for _, method := range extraMethods {
462 if strings.EqualFold(m, method) {
463 return strings.ToLower(m)
464 }
465 }
466 return "unknown"
467 }
468 }
469
470 // If the wrapped http.Handler has not set a status code, i.e. the value is
471 // currently 0, sanitizeCode will return 200, for consistency with behavior in
472 // the stdlib.
473 func sanitizeCode(s int) string {
474 // See for accepted codes https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
475 switch s {
476 case 100:
477 return "100"
478 case 101:
479 return "101"
480
481 case 200, 0:
482 return "200"
483 case 201:
484 return "201"
485 case 202:
486 return "202"
487 case 203:
488 return "203"
489 case 204:
490 return "204"
491 case 205:
492 return "205"
493 case 206:
494 return "206"
495
496 case 300:
497 return "300"
498 case 301:
499 return "301"
500 case 302:
501 return "302"
502 case 304:
503 return "304"
504 case 305:
505 return "305"
506 case 307:
507 return "307"
508
509 case 400:
510 return "400"
511 case 401:
512 return "401"
513 case 402:
514 return "402"
515 case 403:
516 return "403"
517 case 404:
518 return "404"
519 case 405:
520 return "405"
521 case 406:
522 return "406"
523 case 407:
524 return "407"
525 case 408:
526 return "408"
527 case 409:
528 return "409"
529 case 410:
530 return "410"
531 case 411:
532 return "411"
533 case 412:
534 return "412"
535 case 413:
536 return "413"
537 case 414:
538 return "414"
539 case 415:
540 return "415"
541 case 416:
542 return "416"
543 case 417:
544 return "417"
545 case 418:
546 return "418"
547
548 case 500:
549 return "500"
550 case 501:
551 return "501"
552 case 502:
553 return "502"
554 case 503:
555 return "503"
556 case 504:
557 return "504"
558 case 505:
559 return "505"
560
561 case 428:
562 return "428"
563 case 429:
564 return "429"
565 case 431:
566 return "431"
567 case 511:
568 return "511"
569
570 default:
571 if s >= 100 && s <= 599 {
572 return strconv.Itoa(s)
573 }
574 return "unknown"
575 }
576 }