Debian Codegraph @

prometheus/promhttp/http_test.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
15
16 import (
17 "bytes"
18 "compress/gzip"
19 "errors"
20 "fmt"
21 "io"
22 "log"
23 "net/http"
24 "net/http/httptest"
25 "strings"
26 "testing"
27 "time"
28
29 "github.com/klauspost/compress/zstd"
30 dto "github.com/prometheus/client_model/go"
31
32 "github.com/prometheus/client_golang/prometheus"
33 _ "github.com/prometheus/client_golang/prometheus/promhttp/zstd"
34 )
35
36 type errorCollector struct{}
37
38 const (
39 acceptHeader = "Accept"
40 acceptTextPlain = "text/plain"
41 )
42
43 func (e errorCollector) Describe(ch chan<- *prometheus.Desc) {
44 ch <- prometheus.NewDesc("invalid_metric", "not helpful", nil, nil)
45 }
46
47 func (e errorCollector) Collect(ch chan<- prometheus.Metric) {
48 ch <- prometheus.NewInvalidMetric(
49 prometheus.NewDesc("invalid_metric", "not helpful", nil, nil),
50 errors.New("collect error"),
51 )
52 }
53
54 type blockingCollector struct {
55 CollectStarted, Block chan struct{}
56 }
57
58 func (b blockingCollector) Describe(ch chan<- *prometheus.Desc) {
59 ch <- prometheus.NewDesc("dummy_desc", "not helpful", nil, nil)
60 }
61
62 func (b blockingCollector) Collect(ch chan<- prometheus.Metric) {
63 select {
64 case b.CollectStarted <- struct{}{}:
65 default:
66 }
67 // Collects nothing, just waits for a channel receive.
68 <-b.Block
69 }
70
71 type mockTransactionGatherer struct {
72 g prometheus.Gatherer
73 gatherInvoked int
74 doneInvoked int
75 }
76
77 func (g *mockTransactionGatherer) Gather() (_ []*dto.MetricFamily, done func(), err error) {
78 g.gatherInvoked++
79 mfs, err := g.g.Gather()
80 return mfs, func() { g.doneInvoked++ }, err
81 }
82
83 func readCompressedBody(r io.Reader, comp Compression) (string, error) {
84 switch comp {
85 case Gzip:
86 reader, err := gzip.NewReader(r)
87 if err != nil {
88 return "", err
89 }
90 defer reader.Close()
91 got, err := io.ReadAll(reader)
92 return string(got), err
93 case Zstd:
94 reader, err := zstd.NewReader(r)
95 if err != nil {
96 return "", err
97 }
98 defer reader.Close()
99 got, err := io.ReadAll(reader)
100 return string(got), err
101 }
102 return "", errors.New("Unsupported compression")
103 }
104
105 func TestHandlerErrorHandling(t *testing.T) {
106 // Create a registry that collects a MetricFamily with two elements,
107 // another with one, and reports an error. Further down, we'll use the
108 // same registry in the HandlerOpts.
109 reg := prometheus.NewRegistry()
110
111 cnt := prometheus.NewCounter(prometheus.CounterOpts{
112 Name: "the_count",
113 Help: "Ah-ah-ah! Thunder and lightning!",
114 })
115 reg.MustRegister(cnt)
116
117 cntVec := prometheus.NewCounterVec(
118 prometheus.CounterOpts{
119 Name: "name",
120 Help: "docstring",
121 ConstLabels: prometheus.Labels{"constname": "constvalue"},
122 },
123 []string{"labelname"},
124 )
125 cntVec.WithLabelValues("val1").Inc()
126 cntVec.WithLabelValues("val2").Inc()
127 reg.MustRegister(cntVec)
128
129 reg.MustRegister(errorCollector{})
130
131 logBuf := &bytes.Buffer{}
132 logger := log.New(logBuf, "", 0)
133
134 writer := httptest.NewRecorder()
135 request, _ := http.NewRequest(http.MethodGet, "/", nil)
136 request.Header.Add("Accept", "test/plain")
137
138 mReg := &mockTransactionGatherer{g: reg}
139 errorHandler := HandlerForTransactional(mReg, HandlerOpts{
140 ErrorLog: logger,
141 ErrorHandling: HTTPErrorOnError,
142 Registry: reg,
143 })
144 continueHandler := HandlerForTransactional(mReg, HandlerOpts{
145 ErrorLog: logger,
146 ErrorHandling: ContinueOnError,
147 Registry: reg,
148 })
149 panicHandler := HandlerForTransactional(mReg, HandlerOpts{
150 ErrorLog: logger,
151 ErrorHandling: PanicOnError,
152 Registry: reg,
153 })
154 // Expect gatherer not touched.
155 if got := mReg.gatherInvoked; got != 0 {
156 t.Fatalf("unexpected number of gather invokes, want 0, got %d", got)
157 }
158 if got := mReg.doneInvoked; got != 0 {
159 t.Fatalf("unexpected number of done invokes, want 0, got %d", got)
160 }
161
162 wantMsg := `error gathering metrics: error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: {}}: collect error
163 `
164 wantErrorBody := `An error has occurred while serving metrics:
165
166 error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: {}}: collect error
167 `
168 wantOKBody1 := `# HELP name docstring
169 # TYPE name counter
170 name{constname="constvalue",labelname="val1"} 1
171 name{constname="constvalue",labelname="val2"} 1
172 # HELP promhttp_metric_handler_errors_total Total number of internal errors encountered by the promhttp metric handler.
173 # TYPE promhttp_metric_handler_errors_total counter
174 promhttp_metric_handler_errors_total{cause="encoding"} 0
175 promhttp_metric_handler_errors_total{cause="gathering"} 1
176 # HELP the_count Ah-ah-ah! Thunder and lightning!
177 # TYPE the_count counter
178 the_count 0
179 `
180 // It might happen that counting the gathering error makes it to the
181 // promhttp_metric_handler_errors_total counter before it is gathered
182 // itself. Thus, we have to bodies that are acceptable for the test.
183 wantOKBody2 := `# HELP name docstring
184 # TYPE name counter
185 name{constname="constvalue",labelname="val1"} 1
186 name{constname="constvalue",labelname="val2"} 1
187 # HELP promhttp_metric_handler_errors_total Total number of internal errors encountered by the promhttp metric handler.
188 # TYPE promhttp_metric_handler_errors_total counter
189 promhttp_metric_handler_errors_total{cause="encoding"} 0
190 promhttp_metric_handler_errors_total{cause="gathering"} 2
191 # HELP the_count Ah-ah-ah! Thunder and lightning!
192 # TYPE the_count counter
193 the_count 0
194 `
195
196 errorHandler.ServeHTTP(writer, request)
197 if got := mReg.gatherInvoked; got != 1 {
198 t.Fatalf("unexpected number of gather invokes, want 1, got %d", got)
199 }
200 if got := mReg.doneInvoked; got != 1 {
201 t.Fatalf("unexpected number of done invokes, want 1, got %d", got)
202 }
203 if got, want := writer.Code, http.StatusInternalServerError; got != want {
204 t.Errorf("got HTTP status code %d, want %d", got, want)
205 }
206 if got, want := logBuf.String(), wantMsg; got != want {
207 t.Errorf("got log buf %q, want %q", got, want)
208 }
209 if got, want := writer.Body.String(), wantErrorBody; got != want {
210 t.Errorf("got body %q, want %q", got, want)
211 }
212
213 logBuf.Reset()
214 writer.Body.Reset()
215 writer.Code = http.StatusOK
216
217 continueHandler.ServeHTTP(writer, request)
218
219 if got := mReg.gatherInvoked; got != 2 {
220 t.Fatalf("unexpected number of gather invokes, want 2, got %d", got)
221 }
222 if got := mReg.doneInvoked; got != 2 {
223 t.Fatalf("unexpected number of done invokes, want 2, got %d", got)
224 }
225 if got, want := writer.Code, http.StatusOK; got != want {
226 t.Errorf("got HTTP status code %d, want %d", got, want)
227 }
228 if got, want := logBuf.String(), wantMsg; got != want {
229 t.Errorf("got log buf %q, want %q", got, want)
230 }
231 if got := writer.Body.String(); got != wantOKBody1 && got != wantOKBody2 {
232 t.Errorf("got body %q, want either %q or %q", got, wantOKBody1, wantOKBody2)
233 }
234
235 defer func() {
236 if err := recover(); err == nil {
237 t.Error("expected panic from panicHandler")
238 }
239 if got := mReg.gatherInvoked; got != 3 {
240 t.Fatalf("unexpected number of gather invokes, want 3, got %d", got)
241 }
242 if got := mReg.doneInvoked; got != 3 {
243 t.Fatalf("unexpected number of done invokes, want 3, got %d", got)
244 }
245 }()
246 panicHandler.ServeHTTP(writer, request)
247 }
248
249 func TestInstrumentMetricHandler(t *testing.T) {
250 reg := prometheus.NewRegistry()
251 mReg := &mockTransactionGatherer{g: reg}
252 handler := InstrumentMetricHandler(reg, HandlerForTransactional(mReg, HandlerOpts{}))
253 // Do it again to test idempotency.
254 InstrumentMetricHandler(reg, HandlerForTransactional(mReg, HandlerOpts{}))
255 writer := httptest.NewRecorder()
256 request, _ := http.NewRequest(http.MethodGet, "/", nil)
257 request.Header.Add(acceptHeader, acceptTextPlain)
258
259 handler.ServeHTTP(writer, request)
260 if got := mReg.gatherInvoked; got != 1 {
261 t.Fatalf("unexpected number of gather invokes, want 1, got %d", got)
262 }
263 if got := mReg.doneInvoked; got != 1 {
264 t.Fatalf("unexpected number of done invokes, want 1, got %d", got)
265 }
266
267 if got, want := writer.Code, http.StatusOK; got != want {
268 t.Errorf("got HTTP status code %d, want %d", got, want)
269 }
270
271 if got, want := writer.Header().Get(contentEncodingHeader), ""; got != want {
272 t.Errorf("got HTTP content encoding header %s, want %s", got, want)
273 }
274
275 want := "promhttp_metric_handler_requests_in_flight 1\n"
276 if got := writer.Body.String(); !strings.Contains(got, want) {
277 t.Errorf("got body %q, does not contain %q", got, want)
278 }
279 want = "promhttp_metric_handler_requests_total{code=\"200\"} 0\n"
280 if got := writer.Body.String(); !strings.Contains(got, want) {
281 t.Errorf("got body %q, does not contain %q", got, want)
282 }
283
284 for i := 0; i < 100; i++ {
285 writer.Body.Reset()
286 handler.ServeHTTP(writer, request)
287
288 if got, want := mReg.gatherInvoked, i+2; got != want {
289 t.Fatalf("unexpected number of gather invokes, want %d, got %d", want, got)
290 }
291 if got, want := mReg.doneInvoked, i+2; got != want {
292 t.Fatalf("unexpected number of done invokes, want %d, got %d", want, got)
293 }
294 if got, want := writer.Code, http.StatusOK; got != want {
295 t.Errorf("got HTTP status code %d, want %d", got, want)
296 }
297
298 want := "promhttp_metric_handler_requests_in_flight 1\n"
299 if got := writer.Body.String(); !strings.Contains(got, want) {
300 t.Errorf("got body %q, does not contain %q", got, want)
301 }
302 want = fmt.Sprintf("promhttp_metric_handler_requests_total{code=\"200\"} %d\n", i+1)
303 if got := writer.Body.String(); !strings.Contains(got, want) {
304 t.Errorf("got body %q, does not contain %q", got, want)
305 }
306 }
307 }
308
309 func TestHandlerMaxRequestsInFlight(t *testing.T) {
310 reg := prometheus.NewRegistry()
311 handler := HandlerFor(reg, HandlerOpts{MaxRequestsInFlight: 1})
312 w1 := httptest.NewRecorder()
313 w2 := httptest.NewRecorder()
314 w3 := httptest.NewRecorder()
315 request, _ := http.NewRequest(http.MethodGet, "/", nil)
316 request.Header.Add(acceptHeader, acceptTextPlain)
317
318 c := blockingCollector{Block: make(chan struct{}), CollectStarted: make(chan struct{}, 1)}
319 reg.MustRegister(c)
320
321 rq1Done := make(chan struct{})
322 go func() {
323 handler.ServeHTTP(w1, request)
324 close(rq1Done)
325 }()
326 <-c.CollectStarted
327
328 handler.ServeHTTP(w2, request)
329
330 if got, want := w2.Code, http.StatusServiceUnavailable; got != want {
331 t.Errorf("got HTTP status code %d, want %d", got, want)
332 }
333 if got, want := w2.Body.String(), "Limit of concurrent requests reached (1), try again later.\n"; got != want {
334 t.Errorf("got body %q, want %q", got, want)
335 }
336
337 close(c.Block)
338 <-rq1Done
339
340 handler.ServeHTTP(w3, request)
341
342 if got, want := w3.Code, http.StatusOK; got != want {
343 t.Errorf("got HTTP status code %d, want %d", got, want)
344 }
345 }
346
347 func TestHandlerTimeout(t *testing.T) {
348 reg := prometheus.NewRegistry()
349 handler := HandlerFor(reg, HandlerOpts{Timeout: time.Millisecond})
350 w := httptest.NewRecorder()
351
352 request, _ := http.NewRequest(http.MethodGet, "/", nil)
353 request.Header.Add("Accept", "test/plain")
354
355 c := blockingCollector{Block: make(chan struct{}), CollectStarted: make(chan struct{}, 1)}
356 reg.MustRegister(c)
357
358 handler.ServeHTTP(w, request)
359
360 if got, want := w.Code, http.StatusServiceUnavailable; got != want {
361 t.Errorf("got HTTP status code %d, want %d", got, want)
362 }
363 if got, want := w.Body.String(), "Exceeded configured timeout of 1ms.\n"; got != want {
364 t.Errorf("got body %q, want %q", got, want)
365 }
366
367 close(c.Block) // To not leak a goroutine.
368 }
369
370 func TestInstrumentMetricHandlerWithCompression(t *testing.T) {
371 reg := prometheus.NewRegistry()
372 mReg := &mockTransactionGatherer{g: reg}
373 handler := InstrumentMetricHandler(reg, HandlerForTransactional(mReg, HandlerOpts{DisableCompression: false}))
374 compression := Zstd
375 writer := httptest.NewRecorder()
376 request, _ := http.NewRequest(http.MethodGet, "/", nil)
377 request.Header.Add(acceptHeader, acceptTextPlain)
378 request.Header.Add(acceptEncodingHeader, string(compression))
379
380 handler.ServeHTTP(writer, request)
381 if got := mReg.gatherInvoked; got != 1 {
382 t.Fatalf("unexpected number of gather invokes, want 1, got %d", got)
383 }
384 if got := mReg.doneInvoked; got != 1 {
385 t.Fatalf("unexpected number of done invokes, want 1, got %d", got)
386 }
387
388 if got, want := writer.Code, http.StatusOK; got != want {
389 t.Errorf("got HTTP status code %d, want %d", got, want)
390 }
391
392 if got, want := writer.Header().Get(contentEncodingHeader), string(compression); got != want {
393 t.Errorf("got HTTP content encoding header %s, want %s", got, want)
394 }
395
396 body, err := readCompressedBody(writer.Body, compression)
397 want := "promhttp_metric_handler_requests_in_flight 1\n"
398 if got := body; !strings.Contains(got, want) {
399 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
400 }
401
402 want = "promhttp_metric_handler_requests_total{code=\"200\"} 0\n"
403 if got := body; !strings.Contains(got, want) {
404 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
405 }
406
407 for i := 0; i < 100; i++ {
408 writer.Body.Reset()
409 handler.ServeHTTP(writer, request)
410
411 if got, want := mReg.gatherInvoked, i+2; got != want {
412 t.Fatalf("unexpected number of gather invokes, want %d, got %d", want, got)
413 }
414 if got, want := mReg.doneInvoked, i+2; got != want {
415 t.Fatalf("unexpected number of done invokes, want %d, got %d", want, got)
416 }
417 if got, want := writer.Code, http.StatusOK; got != want {
418 t.Errorf("got HTTP status code %d, want %d", got, want)
419 }
420 body, err := readCompressedBody(writer.Body, compression)
421
422 want := "promhttp_metric_handler_requests_in_flight 1\n"
423 if got := body; !strings.Contains(got, want) {
424 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
425 }
426
427 want = fmt.Sprintf("promhttp_metric_handler_requests_total{code=\"200\"} %d\n", i+1)
428 if got := body; !strings.Contains(got, want) {
429 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
430 }
431 }
432
433 // Test with Zstd
434 compression = Zstd
435 request.Header.Set(acceptEncodingHeader, string(compression))
436
437 handler.ServeHTTP(writer, request)
438
439 if got, want := writer.Code, http.StatusOK; got != want {
440 t.Errorf("got HTTP status code %d, want %d", got, want)
441 }
442
443 if got, want := writer.Header().Get(contentEncodingHeader), string(compression); got != want {
444 t.Errorf("got HTTP content encoding header %s, want %s", got, want)
445 }
446
447 body, err = readCompressedBody(writer.Body, compression)
448 want = "promhttp_metric_handler_requests_in_flight 1\n"
449 if got := body; !strings.Contains(got, want) {
450 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
451 }
452
453 want = "promhttp_metric_handler_requests_total{code=\"200\"} 101\n"
454 if got := body; !strings.Contains(got, want) {
455 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
456 }
457
458 for i := 101; i < 201; i++ {
459 writer.Body.Reset()
460 handler.ServeHTTP(writer, request)
461
462 if got, want := mReg.gatherInvoked, i+2; got != want {
463 t.Fatalf("unexpected number of gather invokes, want %d, got %d", want, got)
464 }
465 if got, want := mReg.doneInvoked, i+2; got != want {
466 t.Fatalf("unexpected number of done invokes, want %d, got %d", want, got)
467 }
468 if got, want := writer.Code, http.StatusOK; got != want {
469 t.Errorf("got HTTP status code %d, want %d", got, want)
470 }
471 body, err := readCompressedBody(writer.Body, compression)
472
473 want := "promhttp_metric_handler_requests_in_flight 1\n"
474 if got := body; !strings.Contains(got, want) {
475 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
476 }
477
478 want = fmt.Sprintf("promhttp_metric_handler_requests_total{code=\"200\"} %d\n", i+1)
479 if got := body; !strings.Contains(got, want) {
480 t.Errorf("got body %q, does not contain %q, err: %v", got, want, err)
481 }
482 }
483 }
484
485 func TestNegotiateEncodingWriter(t *testing.T) {
486 var defaultCompressions []string
487
488 for _, comp := range defaultCompressionFormats() {
489 defaultCompressions = append(defaultCompressions, string(comp))
490 }
491
492 testCases := []struct {
493 name string
494 offeredCompressions []string
495 acceptEncoding string
496 expectedCompression string
497 err error
498 }{
499 {
500 name: "test without compression enabled",
501 offeredCompressions: []string{},
502 acceptEncoding: "",
503 expectedCompression: "identity",
504 err: nil,
505 },
506 {
507 name: "test with compression enabled with empty accept-encoding header",
508 offeredCompressions: defaultCompressions,
509 acceptEncoding: "",
510 expectedCompression: "identity",
511 err: nil,
512 },
513 {
514 name: "test with gzip compression requested",
515 offeredCompressions: defaultCompressions,
516 acceptEncoding: "gzip",
517 expectedCompression: "gzip",
518 err: nil,
519 },
520 {
521 name: "test with gzip, zstd compression requested",
522 offeredCompressions: defaultCompressions,
523 acceptEncoding: "gzip,zstd",
524 expectedCompression: "gzip",
525 err: nil,
526 },
527 {
528 name: "test with zstd, gzip compression requested",
529 offeredCompressions: defaultCompressions,
530 acceptEncoding: "zstd,gzip",
531 expectedCompression: "gzip",
532 err: nil,
533 },
534 }
535
536 for _, test := range testCases {
537 request, _ := http.NewRequest(http.MethodGet, "/", nil)
538 request.Header.Add(acceptEncodingHeader, test.acceptEncoding)
539 rr := httptest.NewRecorder()
540 _, encodingHeader, _, err := negotiateEncodingWriter(request, rr, test.offeredCompressions)
541
542 if !errors.Is(err, test.err) {
543 t.Errorf("got error: %v, expected: %v", err, test.err)
544 }
545
546 if encodingHeader != test.expectedCompression {
547 t.Errorf("got different compression type: %v, expected: %v", encodingHeader, test.expectedCompression)
548 }
549 }
550 }
551
552 func BenchmarkCompression(b *testing.B) {
553 benchmarks := []struct {
554 name string
555 compressionType string
556 }{
557 {
558 name: "test with gzip compression",
559 compressionType: "gzip",
560 },
561 {
562 name: "test with zstd compression",
563 compressionType: "zstd",
564 },
565 {
566 name: "test with no compression",
567 compressionType: "identity",
568 },
569 }
570 sizes := []struct {
571 name string
572 metricCount int
573 labelCount int
574 labelLength int
575 metricLength int
576 }{
577 {
578 name: "small",
579 metricCount: 50,
580 labelCount: 5,
581 labelLength: 5,
582 metricLength: 5,
583 },
584 {
585 name: "medium",
586 metricCount: 500,
587 labelCount: 10,
588 labelLength: 5,
589 metricLength: 10,
590 },
591 {
592 name: "large",
593 metricCount: 5000,
594 labelCount: 10,
595 labelLength: 5,
596 metricLength: 10,
597 },
598 {
599 name: "extra-large",
600 metricCount: 50000,
601 labelCount: 20,
602 labelLength: 5,
603 metricLength: 10,
604 },
605 }
606
607 for _, size := range sizes {
608 reg := prometheus.NewRegistry()
609 handler := HandlerFor(reg, HandlerOpts{})
610
611 // Generate Metrics
612 // Original source: https://github.com/prometheus-community/avalanche/blob/main/metrics/serve.go
613 labelKeys := make([]string, size.labelCount)
614 for idx := 0; idx < size.labelCount; idx++ {
615 labelKeys[idx] = fmt.Sprintf("label_key_%s_%v", strings.Repeat("k", size.labelLength), idx)
616 }
617 labelValues := make([]string, size.labelCount)
618 for idx := 0; idx < size.labelCount; idx++ {
619 labelValues[idx] = fmt.Sprintf("label_val_%s_%v", strings.Repeat("v", size.labelLength), idx)
620 }
621 metrics := make([]*prometheus.GaugeVec, size.metricCount)
622 for idx := 0; idx < size.metricCount; idx++ {
623 gauge := prometheus.NewGaugeVec(prometheus.GaugeOpts{
624 Name: fmt.Sprintf("avalanche_metric_%s_%v_%v", strings.Repeat("m", size.metricLength), 0, idx),
625 Help: "A tasty metric morsel",
626 }, append([]string{"series_id", "cycle_id"}, labelKeys...))
627 reg.MustRegister(gauge)
628 metrics[idx] = gauge
629 }
630
631 for _, benchmark := range benchmarks {
632 b.Run(benchmark.name+"_"+size.name, func(b *testing.B) {
633 for i := 0; i < b.N; i++ {
634 writer := httptest.NewRecorder()
635 request, _ := http.NewRequest(http.MethodGet, "/", nil)
636 request.Header.Add(acceptEncodingHeader, benchmark.compressionType)
637 handler.ServeHTTP(writer, request)
638 }
639 })
640 }
641 }
642 }