Debian Codegraph @

prometheus/promhttp/instrument_server_test.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 "context"
18 "io"
19 "log"
20 "net/http"
21 "net/http/httptest"
22 "testing"
23
24 "github.com/prometheus/client_golang/prometheus"
25 )
26
27 func TestLabelCheck(t *testing.T) {
28 scenarios := map[string]struct {
29 metricName string // Defaults to "c".
30 varLabels []string
31 constLabels []string
32 curriedLabels []string
33 dynamicLabels []string
34 ok bool
35 }{
36 "empty": {
37 varLabels: []string{},
38 constLabels: []string{},
39 curriedLabels: []string{},
40 ok: true,
41 },
42 "code as single var label": {
43 varLabels: []string{"code"},
44 constLabels: []string{},
45 curriedLabels: []string{},
46 ok: true,
47 },
48 "method as single var label": {
49 varLabels: []string{"method"},
50 constLabels: []string{},
51 curriedLabels: []string{},
52 ok: true,
53 },
54 "code and method as var labels": {
55 varLabels: []string{"method", "code"},
56 constLabels: []string{},
57 curriedLabels: []string{},
58 ok: true,
59 },
60 "valid case with all labels used": {
61 varLabels: []string{"code", "method"},
62 constLabels: []string{"foo", "bar"},
63 curriedLabels: []string{"dings", "bums"},
64 dynamicLabels: []string{"dyn", "amics"},
65 ok: true,
66 },
67 "all labels used with an invalid const label name": {
68 varLabels: []string{"code", "method"},
69 constLabels: []string{"in\x80valid", "bar"},
70 curriedLabels: []string{"dings", "bums"},
71 dynamicLabels: []string{"dyn", "amics"},
72 ok: false,
73 },
74 "unsupported var label": {
75 varLabels: []string{"foo"},
76 constLabels: []string{},
77 curriedLabels: []string{},
78 ok: false,
79 },
80 "mixed var labels": {
81 varLabels: []string{"method", "foo", "code"},
82 constLabels: []string{},
83 curriedLabels: []string{},
84 ok: false,
85 },
86 "unsupported var label but curried": {
87 varLabels: []string{},
88 constLabels: []string{},
89 curriedLabels: []string{"foo"},
90 ok: true,
91 },
92 "mixed var labels but unsupported curried": {
93 varLabels: []string{"code", "method"},
94 constLabels: []string{},
95 curriedLabels: []string{"foo"},
96 ok: true,
97 },
98 "supported label as const and curry": {
99 varLabels: []string{},
100 constLabels: []string{"code"},
101 curriedLabels: []string{"method"},
102 ok: true,
103 },
104 "supported label as const and dynamic": {
105 varLabels: []string{},
106 constLabels: []string{"code"},
107 dynamicLabels: []string{"method"},
108 ok: true,
109 },
110 "supported label as curried and dynamic": {
111 varLabels: []string{},
112 curriedLabels: []string{"code"},
113 dynamicLabels: []string{"method"},
114 ok: true,
115 },
116 "supported label as const and curry with unsupported as var": {
117 varLabels: []string{"foo"},
118 constLabels: []string{"code"},
119 curriedLabels: []string{"method"},
120 ok: false,
121 },
122 "invalid name and otherwise empty": {
123 metricName: "in\x80valid",
124 varLabels: []string{},
125 constLabels: []string{},
126 curriedLabels: []string{},
127 ok: false,
128 },
129 "invalid name with all the otherwise valid labels": {
130 metricName: "in\x80valid",
131 varLabels: []string{"code", "method"},
132 constLabels: []string{"foo", "bar"},
133 curriedLabels: []string{"dings", "bums"},
134 dynamicLabels: []string{"dyn", "amics"},
135 ok: false,
136 },
137 }
138
139 for name, sc := range scenarios {
140 t.Run(name, func(t *testing.T) {
141 metricName := sc.metricName
142 if metricName == "" {
143 metricName = "c"
144 }
145 constLabels := prometheus.Labels{}
146 for _, l := range sc.constLabels {
147 constLabels[l] = "dummy"
148 }
149 labelNames := append(append(sc.varLabels, sc.curriedLabels...), sc.dynamicLabels...)
150 c := prometheus.V2.NewCounterVec(
151 prometheus.CounterVecOpts{
152 CounterOpts: prometheus.CounterOpts{
153 Name: metricName,
154 Help: "c help",
155 ConstLabels: constLabels,
156 },
157 VariableLabels: prometheus.UnconstrainedLabels(labelNames),
158 },
159 )
160 o := prometheus.ObserverVec(prometheus.V2.NewHistogramVec(
161 prometheus.HistogramVecOpts{
162 HistogramOpts: prometheus.HistogramOpts{
163 Name: metricName,
164 Help: "c help",
165 ConstLabels: constLabels,
166 },
167 VariableLabels: prometheus.UnconstrainedLabels(labelNames),
168 },
169 ))
170 for _, l := range sc.curriedLabels {
171 c = c.MustCurryWith(prometheus.Labels{l: "dummy"})
172 o = o.MustCurryWith(prometheus.Labels{l: "dummy"})
173 }
174 opts := []Option{}
175 for _, l := range sc.dynamicLabels {
176 opts = append(opts, WithLabelFromCtx(l,
177 func(_ context.Context) string {
178 return "foo"
179 },
180 ))
181 }
182
183 func() {
184 defer func() {
185 if err := recover(); err != nil {
186 if sc.ok {
187 t.Error("unexpected panic:", err)
188 }
189 } else if !sc.ok {
190 t.Error("expected panic")
191 }
192 }()
193 InstrumentHandlerCounter(c, nil, opts...)
194 }()
195 func() {
196 defer func() {
197 if err := recover(); err != nil {
198 if sc.ok {
199 t.Error("unexpected panic:", err)
200 }
201 } else if !sc.ok {
202 t.Error("expected panic")
203 }
204 }()
205 InstrumentHandlerDuration(o, nil, opts...)
206 }()
207 if sc.ok {
208 // Test if wantCode and wantMethod were detected correctly.
209 var wantCode, wantMethod bool
210 for _, l := range sc.varLabels {
211 if l == "code" {
212 wantCode = true
213 }
214 if l == "method" {
215 wantMethod = true
216 }
217 }
218 // Curry the dynamic labels since this is done normally behind the scenes for the check
219 for _, l := range sc.dynamicLabels {
220 c = c.MustCurryWith(prometheus.Labels{l: "dummy"})
221 o = o.MustCurryWith(prometheus.Labels{l: "dummy"})
222 }
223 gotCode, gotMethod := checkLabels(c)
224 if gotCode != wantCode {
225 t.Errorf("wanted code=%t for counter, got code=%t", wantCode, gotCode)
226 }
227 if gotMethod != wantMethod {
228 t.Errorf("wanted method=%t for counter, got method=%t", wantMethod, gotMethod)
229 }
230 gotCode, gotMethod = checkLabels(o)
231 if gotCode != wantCode {
232 t.Errorf("wanted code=%t for observer, got code=%t", wantCode, gotCode)
233 }
234 if gotMethod != wantMethod {
235 t.Errorf("wanted method=%t for observer, got method=%t", wantMethod, gotMethod)
236 }
237 }
238 })
239 }
240 }
241
242 func TestLabels(t *testing.T) {
243 scenarios := map[string]struct {
244 varLabels []string
245 reqMethod string
246 respStatus int
247 extraMethods []string
248 wantLabels prometheus.Labels
249 ok bool
250 }{
251 "empty": {
252 varLabels: []string{},
253 wantLabels: prometheus.Labels{},
254 reqMethod: "GET",
255 respStatus: 200,
256 ok: true,
257 },
258 "code as single var label": {
259 varLabels: []string{"code"},
260 reqMethod: "GET",
261 respStatus: 200,
262 wantLabels: prometheus.Labels{"code": "200"},
263 ok: true,
264 },
265 "code as single var label and out-of-range code": {
266 varLabels: []string{"code"},
267 reqMethod: "GET",
268 respStatus: 99,
269 wantLabels: prometheus.Labels{"code": "unknown"},
270 ok: true,
271 },
272 "code as single var label and in-range but unrecognized code": {
273 varLabels: []string{"code"},
274 reqMethod: "GET",
275 respStatus: 308,
276 wantLabels: prometheus.Labels{"code": "308"},
277 ok: true,
278 },
279 "method as single var label": {
280 varLabels: []string{"method"},
281 reqMethod: "GET",
282 respStatus: 200,
283 wantLabels: prometheus.Labels{"method": "get"},
284 ok: true,
285 },
286 "method as single var label and unknown method": {
287 varLabels: []string{"method"},
288 reqMethod: "CUSTOM_METHOD",
289 respStatus: 200,
290 wantLabels: prometheus.Labels{"method": "unknown"},
291 ok: true,
292 },
293 "code and method as var labels": {
294 varLabels: []string{"method", "code"},
295 reqMethod: "GET",
296 respStatus: 200,
297 wantLabels: prometheus.Labels{"method": "get", "code": "200"},
298 ok: true,
299 },
300 "method as single var label with extra methods specified": {
301 varLabels: []string{"method"},
302 reqMethod: "CUSTOM_METHOD",
303 respStatus: 200,
304 extraMethods: []string{"CUSTOM_METHOD", "CUSTOM_METHOD_1"},
305 wantLabels: prometheus.Labels{"method": "custom_method"},
306 ok: true,
307 },
308 "all labels used with an unknown method and out-of-range code": {
309 varLabels: []string{"code", "method"},
310 reqMethod: "CUSTOM_METHOD",
311 respStatus: 99,
312 wantLabels: prometheus.Labels{"method": "unknown", "code": "unknown"},
313 ok: false,
314 },
315 }
316 checkLabels := func(labels []string) (gotCode, gotMethod bool) {
317 for _, label := range labels {
318 switch label {
319 case "code":
320 gotCode = true
321 case "method":
322 gotMethod = true
323 default:
324 panic("metric partitioned with non-supported labels for this test")
325 }
326 }
327 return
328 }
329 equalLabels := func(gotLabels, wantLabels prometheus.Labels) bool {
330 if len(gotLabels) != len(wantLabels) {
331 return false
332 }
333 for ln, lv := range gotLabels {
334 olv, ok := wantLabels[ln]
335 if !ok {
336 return false
337 }
338 if olv != lv {
339 return false
340 }
341 }
342 return true
343 }
344
345 for name, sc := range scenarios {
346 t.Run(name, func(t *testing.T) {
347 if sc.ok {
348 gotCode, gotMethod := checkLabels(sc.varLabels)
349 gotLabels := labels(gotCode, gotMethod, sc.reqMethod, sc.respStatus, sc.extraMethods...)
350 if !equalLabels(gotLabels, sc.wantLabels) {
351 t.Errorf("wanted labels=%v for counter, got code=%v", sc.wantLabels, gotLabels)
352 }
353 }
354 })
355 }
356 }
357
358 func makeInstrumentedHandler(handler http.HandlerFunc, opts ...Option) (http.Handler, *prometheus.Registry) {
359 reg := prometheus.NewRegistry()
360
361 inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
362 Name: "in_flight_requests",
363 Help: "A gauge of requests currently being served by the wrapped handler.",
364 })
365
366 counter := prometheus.NewCounterVec(
367 prometheus.CounterOpts{
368 Name: "api_requests_total",
369 Help: "A counter for requests to the wrapped handler.",
370 },
371 []string{"code", "method"},
372 )
373
374 histVec := prometheus.NewHistogramVec(
375 prometheus.HistogramOpts{
376 Name: "response_duration_seconds",
377 Help: "A histogram of request latencies.",
378 Buckets: prometheus.DefBuckets,
379 ConstLabels: prometheus.Labels{"handler": "api"},
380 },
381 []string{"method"},
382 )
383
384 writeHeaderVec := prometheus.NewHistogramVec(
385 prometheus.HistogramOpts{
386 Name: "write_header_duration_seconds",
387 Help: "A histogram of time to first write latencies.",
388 Buckets: prometheus.DefBuckets,
389 ConstLabels: prometheus.Labels{"handler": "api"},
390 },
391 []string{},
392 )
393
394 responseSize := prometheus.NewHistogramVec(
395 prometheus.HistogramOpts{
396 Name: "push_request_size_bytes",
397 Help: "A histogram of request sizes for requests.",
398 Buckets: []float64{200, 500, 900, 1500},
399 },
400 []string{},
401 )
402
403 reg.MustRegister(inFlightGauge, counter, histVec, responseSize, writeHeaderVec)
404
405 return InstrumentHandlerInFlight(inFlightGauge,
406 InstrumentHandlerCounter(counter,
407 InstrumentHandlerDuration(histVec,
408 InstrumentHandlerTimeToWriteHeader(writeHeaderVec,
409 InstrumentHandlerResponseSize(responseSize, handler, opts...),
410 opts...),
411 opts...),
412 opts...),
413 ), reg
414 }
415
416 func TestMiddlewareAPI(t *testing.T) {
417 chain, reg := makeInstrumentedHandler(func(w http.ResponseWriter, r *http.Request) {
418 _, _ = w.Write([]byte("OK"))
419 })
420
421 r, _ := http.NewRequest(http.MethodGet, "www.example.com", nil)
422 w := httptest.NewRecorder()
423 chain.ServeHTTP(w, r)
424
425 assetMetricAndExemplars(t, reg, 5, nil)
426 }
427
428 func TestMiddlewareAPI_WithExemplars(t *testing.T) {
429 exemplar := prometheus.Labels{"traceID": "example situation observed by this metric"}
430
431 chain, reg := makeInstrumentedHandler(func(w http.ResponseWriter, r *http.Request) {
432 _, _ = w.Write([]byte("OK"))
433 }, WithExemplarFromContext(func(_ context.Context) prometheus.Labels { return exemplar }))
434
435 r, _ := http.NewRequest(http.MethodGet, "www.example.com", nil)
436 w := httptest.NewRecorder()
437 chain.ServeHTTP(w, r)
438
439 assetMetricAndExemplars(t, reg, 5, labelsToLabelPair(exemplar))
440 }
441
442 func TestInstrumentTimeToFirstWrite(t *testing.T) {
443 var i int
444 dobs := &responseWriterDelegator{
445 ResponseWriter: httptest.NewRecorder(),
446 observeWriteHeader: func(status int) {
447 i = status
448 },
449 }
450 d := newDelegator(dobs, nil)
451
452 d.WriteHeader(http.StatusOK)
453
454 if i != http.StatusOK {
455 t.Fatalf("failed to execute observeWriteHeader")
456 }
457 }
458
459 // testResponseWriter is an http.ResponseWriter that also implements
460 // http.CloseNotifier, http.Flusher, and io.ReaderFrom.
461 type testResponseWriter struct {
462 closeNotifyCalled, flushCalled, readFromCalled bool
463 }
464
465 func (t *testResponseWriter) Header() http.Header { return nil }
466 func (t *testResponseWriter) Write([]byte) (int, error) { return 0, nil }
467 func (t *testResponseWriter) WriteHeader(int) {}
468 func (t *testResponseWriter) CloseNotify() <-chan bool {
469 t.closeNotifyCalled = true
470 return nil
471 }
472 func (t *testResponseWriter) Flush() { t.flushCalled = true }
473 func (t *testResponseWriter) ReadFrom(io.Reader) (int64, error) {
474 t.readFromCalled = true
475 return 0, nil
476 }
477
478 // testFlusher is an http.ResponseWriter that also implements http.Flusher.
479 type testFlusher struct {
480 flushCalled bool
481 }
482
483 func (t *testFlusher) Header() http.Header { return nil }
484 func (t *testFlusher) Write([]byte) (int, error) { return 0, nil }
485 func (t *testFlusher) WriteHeader(int) {}
486 func (t *testFlusher) Flush() { t.flushCalled = true }
487
488 func TestInterfaceUpgrade(t *testing.T) {
489 w := &testResponseWriter{}
490 d := newDelegator(w, nil)
491 //nolint:staticcheck // Ignore SA1019. http.CloseNotifier is deprecated but we keep it here to not break existing users.
492 d.(http.CloseNotifier).CloseNotify()
493 if !w.closeNotifyCalled {
494 t.Error("CloseNotify not called")
495 }
496 d.(http.Flusher).Flush()
497 if !w.flushCalled {
498 t.Error("Flush not called")
499 }
500 d.(io.ReaderFrom).ReadFrom(nil)
501 if !w.readFromCalled {
502 t.Error("ReadFrom not called")
503 }
504 if _, ok := d.(http.Hijacker); ok {
505 t.Error("delegator unexpectedly implements http.Hijacker")
506 }
507
508 f := &testFlusher{}
509 d = newDelegator(f, nil)
510 //nolint:staticcheck // Ignore SA1019. http.CloseNotifier is deprecated but we keep it here to not break existing users.
511 if _, ok := d.(http.CloseNotifier); ok {
512 t.Error("delegator unexpectedly implements http.CloseNotifier")
513 }
514 d.(http.Flusher).Flush()
515 if !w.flushCalled {
516 t.Error("Flush not called")
517 }
518 if _, ok := d.(io.ReaderFrom); ok {
519 t.Error("delegator unexpectedly implements io.ReaderFrom")
520 }
521 if _, ok := d.(http.Hijacker); ok {
522 t.Error("delegator unexpectedly implements http.Hijacker")
523 }
524 }
525
526 func ExampleInstrumentHandlerDuration() {
527 inFlightGauge := prometheus.NewGauge(prometheus.GaugeOpts{
528 Name: "in_flight_requests",
529 Help: "A gauge of requests currently being served by the wrapped handler.",
530 })
531
532 counter := prometheus.NewCounterVec(
533 prometheus.CounterOpts{
534 Name: "api_requests_total",
535 Help: "A counter for requests to the wrapped handler.",
536 },
537 []string{"code", "method"},
538 )
539
540 // duration is partitioned by the HTTP method and handler. It uses custom
541 // buckets based on the expected request duration.
542 duration := prometheus.NewHistogramVec(
543 prometheus.HistogramOpts{
544 Name: "request_duration_seconds",
545 Help: "A histogram of latencies for requests.",
546 Buckets: []float64{.25, .5, 1, 2.5, 5, 10},
547 },
548 []string{"handler", "method"},
549 )
550
551 // responseSize has no labels, making it a zero-dimensional
552 // ObserverVec.
553 responseSize := prometheus.NewHistogramVec(
554 prometheus.HistogramOpts{
555 Name: "response_size_bytes",
556 Help: "A histogram of response sizes for requests.",
557 Buckets: []float64{200, 500, 900, 1500},
558 },
559 []string{},
560 )
561
562 // Create the handlers that will be wrapped by the middleware.
563 pushHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
564 w.Write([]byte("Push"))
565 })
566 pullHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
567 w.Write([]byte("Pull"))
568 })
569
570 // Register all of the metrics in the standard registry.
571 prometheus.MustRegister(inFlightGauge, counter, duration, responseSize)
572
573 // Instrument the handlers with all the metrics, injecting the "handler"
574 // label by currying.
575 pushChain := InstrumentHandlerInFlight(inFlightGauge,
576 InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "push"}),
577 InstrumentHandlerCounter(counter,
578 InstrumentHandlerResponseSize(responseSize, pushHandler),
579 ),
580 ),
581 )
582 pullChain := InstrumentHandlerInFlight(inFlightGauge,
583 InstrumentHandlerDuration(duration.MustCurryWith(prometheus.Labels{"handler": "pull"}),
584 InstrumentHandlerCounter(counter,
585 InstrumentHandlerResponseSize(responseSize, pullHandler),
586 ),
587 ),
588 )
589
590 http.Handle("/metrics", Handler())
591 http.Handle("/push", pushChain)
592 http.Handle("/pull", pullChain)
593
594 if err := http.ListenAndServe(":3000", nil); err != nil {
595 log.Fatal(err)
596 }
597 }