Debian Codegraph @

prometheus/registry_test.go

raw
1 // Copyright 2014 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 // Copyright (c) 2013, The Prometheus Authors
15 // All rights reserved.
16 //
17 // Use of this source code is governed by a BSD-style license that can be found
18 // in the LICENSE file.
19
20 package prometheus_test
21
22 import (
23 "bytes"
24 "errors"
25 "fmt"
26 "math/rand"
27 "net/http"
28 "net/http/httptest"
29 "os"
30 "strconv"
31 "sync"
32 "testing"
33 "time"
34
35 "github.com/prometheus/client_golang/prometheus"
36 "github.com/prometheus/client_golang/prometheus/promhttp"
37
38 dto "github.com/prometheus/client_model/go"
39 "github.com/prometheus/common/expfmt"
40 "go.uber.org/goleak"
41 "google.golang.org/protobuf/proto"
42 "google.golang.org/protobuf/types/known/timestamppb"
43 )
44
45 // uncheckedCollector wraps a Collector but its Describe method yields no Desc.
46 type uncheckedCollector struct {
47 c prometheus.Collector
48 }
49
50 func (u uncheckedCollector) Describe(_ chan<- *prometheus.Desc) {}
51 func (u uncheckedCollector) Collect(c chan<- prometheus.Metric) {
52 u.c.Collect(c)
53 }
54
55 func testHandler(t testing.TB) {
56 // TODO(beorn7): This test is a bit too "end-to-end". It tests quite a
57 // few moving parts that are not strongly coupled. They could/should be
58 // tested separately. However, the changes planned for v2 will
59 // require a major rework of this test anyway, at which time I will
60 // structure it in a better way.
61
62 metricVec := prometheus.NewCounterVec(
63 prometheus.CounterOpts{
64 Name: "name",
65 Help: "docstring",
66 ConstLabels: prometheus.Labels{"constname": "constvalue"},
67 },
68 []string{"labelname"},
69 )
70
71 metricVec.WithLabelValues("val1").Inc()
72 metricVec.WithLabelValues("val2").Inc()
73
74 externalMetricFamily := &dto.MetricFamily{
75 Name: proto.String("externalname"),
76 Help: proto.String("externaldocstring"),
77 Type: dto.MetricType_COUNTER.Enum(),
78 Metric: []*dto.Metric{
79 {
80 Label: []*dto.LabelPair{
81 {
82 Name: proto.String("externalconstname"),
83 Value: proto.String("externalconstvalue"),
84 },
85 {
86 Name: proto.String("externallabelname"),
87 Value: proto.String("externalval1"),
88 },
89 },
90 Counter: &dto.Counter{
91 Value: proto.Float64(1),
92 },
93 },
94 },
95 }
96 externalBuf := &bytes.Buffer{}
97 enc := expfmt.NewEncoder(externalBuf, expfmt.NewFormat(expfmt.TypeProtoDelim))
98 if err := enc.Encode(externalMetricFamily); err != nil {
99 t.Fatal(err)
100 }
101 externalMetricFamilyAsBytes := externalBuf.Bytes()
102 externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring
103 # TYPE externalname counter
104 externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1
105 `)
106 externalMetricFamilyAsProtoText := []byte(`name: "externalname"
107 help: "externaldocstring"
108 type: COUNTER
109 metric: <
110 label: <
111 name: "externalconstname"
112 value: "externalconstvalue"
113 >
114 label: <
115 name: "externallabelname"
116 value: "externalval1"
117 >
118 counter: <
119 value: 1
120 >
121 >
122
123 `)
124 externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric:<label:<name:"externalconstname" value:"externalconstvalue" > label:<name:"externallabelname" value:"externalval1" > counter:<value:1 > >`)
125 externalMetricFamilyAsProtoCompactText = append(externalMetricFamilyAsProtoCompactText, []byte(" \n")...)
126
127 expectedMetricFamily := &dto.MetricFamily{
128 Name: proto.String("name"),
129 Help: proto.String("docstring"),
130 Type: dto.MetricType_COUNTER.Enum(),
131 Metric: []*dto.Metric{
132 {
133 Label: []*dto.LabelPair{
134 {
135 Name: proto.String("constname"),
136 Value: proto.String("constvalue"),
137 },
138 {
139 Name: proto.String("labelname"),
140 Value: proto.String("val1"),
141 },
142 },
143 Counter: &dto.Counter{
144 Value: proto.Float64(1),
145 CreatedTimestamp: timestamppb.New(time.Now()),
146 },
147 },
148 {
149 Label: []*dto.LabelPair{
150 {
151 Name: proto.String("constname"),
152 Value: proto.String("constvalue"),
153 },
154 {
155 Name: proto.String("labelname"),
156 Value: proto.String("val2"),
157 },
158 },
159 Counter: &dto.Counter{
160 Value: proto.Float64(1),
161 CreatedTimestamp: timestamppb.New(time.Now()),
162 },
163 },
164 },
165 }
166 buf := &bytes.Buffer{}
167 enc = expfmt.NewEncoder(buf, expfmt.NewFormat(expfmt.TypeProtoDelim))
168 if err := enc.Encode(expectedMetricFamily); err != nil {
169 t.Fatal(err)
170 }
171 expectedMetricFamilyAsBytes := buf.Bytes()
172 expectedMetricFamilyAsText := []byte(`# HELP name docstring
173 # TYPE name counter
174 name{constname="constvalue",labelname="val1"} 1
175 name{constname="constvalue",labelname="val2"} 1
176 `)
177 expectedMetricFamilyAsProtoText := []byte(`name: "name"
178 help: "docstring"
179 type: COUNTER
180 metric: <
181 label: <
182 name: "constname"
183 value: "constvalue"
184 >
185 label: <
186 name: "labelname"
187 value: "val1"
188 >
189 counter: <
190 value: 1
191 >
192 >
193 metric: <
194 label: <
195 name: "constname"
196 value: "constvalue"
197 >
198 label: <
199 name: "labelname"
200 value: "val2"
201 >
202 counter: <
203 value: 1
204 >
205 >
206
207 `)
208 expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >`)
209 expectedMetricFamilyAsProtoCompactText = append(expectedMetricFamilyAsProtoCompactText, []byte(" \n")...)
210
211 externalMetricFamilyWithSameName := &dto.MetricFamily{
212 Name: proto.String("name"),
213 Help: proto.String("docstring"),
214 Type: dto.MetricType_COUNTER.Enum(),
215 Metric: []*dto.Metric{
216 {
217 Label: []*dto.LabelPair{
218 {
219 Name: proto.String("constname"),
220 Value: proto.String("constvalue"),
221 },
222 {
223 Name: proto.String("labelname"),
224 Value: proto.String("different_val"),
225 },
226 },
227 Counter: &dto.Counter{
228 Value: proto.Float64(42),
229 },
230 },
231 },
232 }
233
234 expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"different_val" > counter:<value:42 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >`)
235 expectedMetricFamilyMergedWithExternalAsProtoCompactText = append(expectedMetricFamilyMergedWithExternalAsProtoCompactText, []byte(" \n")...)
236
237 externalMetricFamilyWithInvalidLabelValue := &dto.MetricFamily{
238 Name: proto.String("name"),
239 Help: proto.String("docstring"),
240 Type: dto.MetricType_COUNTER.Enum(),
241 Metric: []*dto.Metric{
242 {
243 Label: []*dto.LabelPair{
244 {
245 Name: proto.String("constname"),
246 Value: proto.String("\xFF"),
247 },
248 {
249 Name: proto.String("labelname"),
250 Value: proto.String("different_val"),
251 },
252 },
253 Counter: &dto.Counter{
254 Value: proto.Float64(42),
255 },
256 },
257 },
258 }
259
260 expectedMetricFamilyInvalidLabelValueAsText := []byte(`An error has occurred while serving metrics:
261
262 collected metric "name" { label:<name:"constname" value:"\377" > label:<name:"labelname" value:"different_val" > counter:<value:42 > } has a label named "constname" whose value is not utf8: "\xff"
263 `)
264
265 summary := prometheus.NewSummary(prometheus.SummaryOpts{
266 Name: "complex",
267 Help: "A metric to check collisions with _sum and _count.",
268 Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
269 })
270 summaryAsText := []byte(`# HELP complex A metric to check collisions with _sum and _count.
271 # TYPE complex summary
272 complex{quantile="0.5"} NaN
273 complex{quantile="0.9"} NaN
274 complex{quantile="0.99"} NaN
275 complex_sum 0
276 complex_count 0
277 `)
278 histogram := prometheus.NewHistogram(prometheus.HistogramOpts{
279 Name: "complex",
280 Help: "A metric to check collisions with _sun, _count, and _bucket.",
281 })
282 externalMetricFamilyWithBucketSuffix := &dto.MetricFamily{
283 Name: proto.String("complex_bucket"),
284 Help: proto.String("externaldocstring"),
285 Type: dto.MetricType_COUNTER.Enum(),
286 Metric: []*dto.Metric{
287 {
288 Counter: &dto.Counter{
289 Value: proto.Float64(1),
290 },
291 },
292 },
293 }
294 externalMetricFamilyWithBucketSuffixAsText := []byte(`# HELP complex_bucket externaldocstring
295 # TYPE complex_bucket counter
296 complex_bucket 1
297 `)
298 externalMetricFamilyWithCountSuffix := &dto.MetricFamily{
299 Name: proto.String("complex_count"),
300 Help: proto.String("externaldocstring"),
301 Type: dto.MetricType_COUNTER.Enum(),
302 Metric: []*dto.Metric{
303 {
304 Counter: &dto.Counter{
305 Value: proto.Float64(1),
306 },
307 },
308 },
309 }
310 bucketCollisionMsg := []byte(`An error has occurred while serving metrics:
311
312 collected metric named "complex_bucket" collides with previously collected histogram named "complex"
313 `)
314 summaryCountCollisionMsg := []byte(`An error has occurred while serving metrics:
315
316 collected metric named "complex_count" collides with previously collected summary named "complex"
317 `)
318 histogramCountCollisionMsg := []byte(`An error has occurred while serving metrics:
319
320 collected metric named "complex_count" collides with previously collected histogram named "complex"
321 `)
322 externalMetricFamilyWithDuplicateLabel := &dto.MetricFamily{
323 Name: proto.String("broken_metric"),
324 Help: proto.String("The registry should detect the duplicate label."),
325 Type: dto.MetricType_COUNTER.Enum(),
326 Metric: []*dto.Metric{
327 {
328 Label: []*dto.LabelPair{
329 {
330 Name: proto.String("foo"),
331 Value: proto.String("bar"),
332 },
333 {
334 Name: proto.String("foo"),
335 Value: proto.String("baz"),
336 },
337 },
338 Counter: &dto.Counter{
339 Value: proto.Float64(2.7),
340 },
341 },
342 },
343 }
344 duplicateLabelMsg := []byte(`An error has occurred while serving metrics:
345
346 collected metric "broken_metric" { label:<name:"foo" value:"bar" > label:<name:"foo" value:"baz" > counter:<value:2.7 > } has two or more labels with the same name: foo
347 `)
348
349 type output struct {
350 headers map[string]string
351 body []byte
352 }
353
354 scenarios := []struct {
355 headers map[string]string
356 out output
357 collector prometheus.Collector
358 externalMF []*dto.MetricFamily
359 }{
360 { // 0
361 headers: map[string]string{
362 "Accept": "foo/bar;q=0.2, dings/bums;q=0.8",
363 },
364 out: output{
365 headers: map[string]string{
366 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
367 },
368 body: []byte{},
369 },
370 },
371 { // 1
372 headers: map[string]string{
373 "Accept": "foo/bar;q=0.2, application/quark;q=0.8",
374 },
375 out: output{
376 headers: map[string]string{
377 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
378 },
379 body: []byte{},
380 },
381 },
382 { // 2
383 headers: map[string]string{
384 "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8",
385 },
386 out: output{
387 headers: map[string]string{
388 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
389 },
390 body: []byte{},
391 },
392 },
393 { // 3
394 headers: map[string]string{
395 "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8",
396 },
397 out: output{
398 headers: map[string]string{
399 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited; escaping=underscores`,
400 },
401 body: []byte{},
402 },
403 },
404 { // 4
405 headers: map[string]string{
406 "Accept": "application/json",
407 },
408 out: output{
409 headers: map[string]string{
410 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
411 },
412 body: expectedMetricFamilyAsText,
413 },
414 collector: metricVec,
415 },
416 { // 5
417 headers: map[string]string{
418 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited",
419 },
420 out: output{
421 headers: map[string]string{
422 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited; escaping=underscores`,
423 },
424 body: expectedMetricFamilyAsBytes,
425 },
426 collector: metricVec,
427 },
428 { // 6
429 headers: map[string]string{
430 "Accept": "application/json",
431 },
432 out: output{
433 headers: map[string]string{
434 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
435 },
436 body: externalMetricFamilyAsText,
437 },
438 externalMF: []*dto.MetricFamily{externalMetricFamily},
439 },
440 { // 7
441 headers: map[string]string{
442 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited",
443 },
444 out: output{
445 headers: map[string]string{
446 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited; escaping=underscores`,
447 },
448 body: externalMetricFamilyAsBytes,
449 },
450 externalMF: []*dto.MetricFamily{externalMetricFamily},
451 },
452 { // 8
453 headers: map[string]string{
454 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited",
455 },
456 out: output{
457 headers: map[string]string{
458 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited; escaping=underscores`,
459 },
460 body: bytes.Join(
461 [][]byte{
462 externalMetricFamilyAsBytes,
463 expectedMetricFamilyAsBytes,
464 },
465 []byte{},
466 ),
467 },
468 collector: metricVec,
469 externalMF: []*dto.MetricFamily{externalMetricFamily},
470 },
471 { // 9
472 headers: map[string]string{
473 "Accept": "text/plain",
474 },
475 out: output{
476 headers: map[string]string{
477 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
478 },
479 body: []byte{},
480 },
481 },
482 { // 10
483 headers: map[string]string{
484 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5",
485 },
486 out: output{
487 headers: map[string]string{
488 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
489 },
490 body: expectedMetricFamilyAsText,
491 },
492 collector: metricVec,
493 },
494 { // 11
495 headers: map[string]string{
496 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4",
497 },
498 out: output{
499 headers: map[string]string{
500 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
501 },
502 body: bytes.Join(
503 [][]byte{
504 externalMetricFamilyAsText,
505 expectedMetricFamilyAsText,
506 },
507 []byte{},
508 ),
509 },
510 collector: metricVec,
511 externalMF: []*dto.MetricFamily{externalMetricFamily},
512 },
513 { // 12
514 headers: map[string]string{
515 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2",
516 },
517 out: output{
518 headers: map[string]string{
519 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited; escaping=underscores`,
520 },
521 body: bytes.Join(
522 [][]byte{
523 externalMetricFamilyAsBytes,
524 expectedMetricFamilyAsBytes,
525 },
526 []byte{},
527 ),
528 },
529 collector: metricVec,
530 externalMF: []*dto.MetricFamily{externalMetricFamily},
531 },
532 { // 13
533 headers: map[string]string{
534 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4",
535 },
536 out: output{
537 headers: map[string]string{
538 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text; escaping=underscores`,
539 },
540 body: bytes.Join(
541 [][]byte{
542 externalMetricFamilyAsProtoText,
543 expectedMetricFamilyAsProtoText,
544 },
545 []byte{},
546 ),
547 },
548 collector: metricVec,
549 externalMF: []*dto.MetricFamily{externalMetricFamily},
550 },
551 { // 14
552 headers: map[string]string{
553 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text",
554 },
555 out: output{
556 headers: map[string]string{
557 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text; escaping=underscores`,
558 },
559 body: bytes.Join(
560 [][]byte{
561 externalMetricFamilyAsProtoCompactText,
562 expectedMetricFamilyAsProtoCompactText,
563 },
564 []byte{},
565 ),
566 },
567 collector: metricVec,
568 externalMF: []*dto.MetricFamily{externalMetricFamily},
569 },
570 { // 15
571 headers: map[string]string{
572 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text",
573 },
574 out: output{
575 headers: map[string]string{
576 "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text; escaping=underscores`,
577 },
578 body: bytes.Join(
579 [][]byte{
580 externalMetricFamilyAsProtoCompactText,
581 expectedMetricFamilyMergedWithExternalAsProtoCompactText,
582 },
583 []byte{},
584 ),
585 },
586 collector: metricVec,
587 externalMF: []*dto.MetricFamily{
588 externalMetricFamily,
589 externalMetricFamilyWithSameName,
590 },
591 },
592 { // 16
593 headers: map[string]string{
594 "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text",
595 },
596 out: output{
597 headers: map[string]string{
598 "Content-Type": `text/plain; charset=utf-8`,
599 },
600 body: expectedMetricFamilyInvalidLabelValueAsText,
601 },
602 collector: metricVec,
603 externalMF: []*dto.MetricFamily{
604 externalMetricFamily,
605 externalMetricFamilyWithInvalidLabelValue,
606 },
607 },
608 { // 17
609 headers: map[string]string{
610 "Accept": "text/plain",
611 },
612 out: output{
613 headers: map[string]string{
614 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
615 },
616 body: expectedMetricFamilyAsText,
617 },
618 collector: uncheckedCollector{metricVec},
619 },
620 { // 18
621 headers: map[string]string{
622 "Accept": "text/plain",
623 },
624 out: output{
625 headers: map[string]string{
626 "Content-Type": `text/plain; charset=utf-8`,
627 },
628 body: histogramCountCollisionMsg,
629 },
630 collector: histogram,
631 externalMF: []*dto.MetricFamily{
632 externalMetricFamilyWithCountSuffix,
633 },
634 },
635 { // 19
636 headers: map[string]string{
637 "Accept": "text/plain",
638 },
639 out: output{
640 headers: map[string]string{
641 "Content-Type": `text/plain; charset=utf-8`,
642 },
643 body: bucketCollisionMsg,
644 },
645 collector: histogram,
646 externalMF: []*dto.MetricFamily{
647 externalMetricFamilyWithBucketSuffix,
648 },
649 },
650 { // 20
651 headers: map[string]string{
652 "Accept": "text/plain",
653 },
654 out: output{
655 headers: map[string]string{
656 "Content-Type": `text/plain; charset=utf-8`,
657 },
658 body: summaryCountCollisionMsg,
659 },
660 collector: summary,
661 externalMF: []*dto.MetricFamily{
662 externalMetricFamilyWithCountSuffix,
663 },
664 },
665 { // 21
666 headers: map[string]string{
667 "Accept": "text/plain",
668 },
669 out: output{
670 headers: map[string]string{
671 "Content-Type": `text/plain; version=0.0.4; charset=utf-8; escaping=underscores`,
672 },
673 body: bytes.Join(
674 [][]byte{
675 summaryAsText,
676 externalMetricFamilyWithBucketSuffixAsText,
677 },
678 []byte{},
679 ),
680 },
681 collector: summary,
682 externalMF: []*dto.MetricFamily{
683 externalMetricFamilyWithBucketSuffix,
684 },
685 },
686 { // 22
687 headers: map[string]string{
688 "Accept": "text/plain",
689 },
690 out: output{
691 headers: map[string]string{
692 "Content-Type": `text/plain; charset=utf-8`,
693 },
694 body: duplicateLabelMsg,
695 },
696 externalMF: []*dto.MetricFamily{
697 externalMetricFamilyWithDuplicateLabel,
698 },
699 },
700 }
701 for i, scenario := range scenarios {
702 registry := prometheus.NewPedanticRegistry()
703 gatherer := prometheus.Gatherer(registry)
704 if scenario.externalMF != nil {
705 gatherer = prometheus.Gatherers{
706 registry,
707 prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) {
708 return scenario.externalMF, nil
709 }),
710 }
711 }
712
713 if scenario.collector != nil {
714 registry.MustRegister(scenario.collector)
715 }
716 writer := httptest.NewRecorder()
717 handler := promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})
718 request, _ := http.NewRequest(http.MethodGet, "/", nil)
719 for key, value := range scenario.headers {
720 request.Header.Add(key, value)
721 }
722 handler.ServeHTTP(writer, request)
723
724 for key, value := range scenario.out.headers {
725 if writer.Header().Get(key) != value {
726 t.Errorf(
727 "%d. expected %q for header %q, got %q",
728 i, value, key, writer.Header().Get(key),
729 )
730 }
731 }
732
733 var outMF dto.MetricFamily
734 var writerMF dto.MetricFamily
735 proto.Unmarshal(scenario.out.body, &outMF)
736 proto.Unmarshal(writer.Body.Bytes(), &writerMF)
737 if !proto.Equal(&outMF, &writerMF) {
738 t.Errorf(
739 "%d. expected body:\n%s\ngot body:\n%s\n",
740 i, scenario.out.body, writer.Body.Bytes(),
741 )
742 }
743 }
744 }
745
746 func TestHandler(t *testing.T) {
747 testHandler(t)
748 }
749
750 func BenchmarkHandler(b *testing.B) {
751 for i := 0; i < b.N; i++ {
752 testHandler(b)
753 }
754 }
755
756 func TestAlreadyRegistered(t *testing.T) {
757 original := prometheus.NewCounterVec(
758 prometheus.CounterOpts{
759 Name: "test",
760 Help: "help",
761 ConstLabels: prometheus.Labels{"const": "label"},
762 },
763 []string{"foo", "bar"},
764 )
765 equalButNotSame := prometheus.NewCounterVec(
766 prometheus.CounterOpts{
767 Name: "test",
768 Help: "help",
769 ConstLabels: prometheus.Labels{"const": "label"},
770 },
771 []string{"foo", "bar"},
772 )
773 originalWithoutConstLabel := prometheus.NewCounterVec(
774 prometheus.CounterOpts{
775 Name: "test",
776 Help: "help",
777 },
778 []string{"foo", "bar"},
779 )
780 equalButNotSameWithoutConstLabel := prometheus.NewCounterVec(
781 prometheus.CounterOpts{
782 Name: "test",
783 Help: "help",
784 },
785 []string{"foo", "bar"},
786 )
787
788 scenarios := []struct {
789 name string
790 originalCollector prometheus.Collector
791 registerWith func(prometheus.Registerer) prometheus.Registerer
792 newCollector prometheus.Collector
793 reRegisterWith func(prometheus.Registerer) prometheus.Registerer
794 }{
795 {
796 "RegisterNormallyReregisterNormally",
797 original,
798 func(r prometheus.Registerer) prometheus.Registerer { return r },
799 equalButNotSame,
800 func(r prometheus.Registerer) prometheus.Registerer { return r },
801 },
802 {
803 "RegisterNormallyReregisterWrapped",
804 original,
805 func(r prometheus.Registerer) prometheus.Registerer { return r },
806 equalButNotSameWithoutConstLabel,
807 func(r prometheus.Registerer) prometheus.Registerer {
808 return prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r)
809 },
810 },
811 {
812 "RegisterWrappedReregisterWrapped",
813 originalWithoutConstLabel,
814 func(r prometheus.Registerer) prometheus.Registerer {
815 return prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r)
816 },
817 equalButNotSameWithoutConstLabel,
818 func(r prometheus.Registerer) prometheus.Registerer {
819 return prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r)
820 },
821 },
822 {
823 "RegisterWrappedReregisterNormally",
824 originalWithoutConstLabel,
825 func(r prometheus.Registerer) prometheus.Registerer {
826 return prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r)
827 },
828 equalButNotSame,
829 func(r prometheus.Registerer) prometheus.Registerer { return r },
830 },
831 {
832 "RegisterDoublyWrappedReregisterDoublyWrapped",
833 originalWithoutConstLabel,
834 func(r prometheus.Registerer) prometheus.Registerer {
835 return prometheus.WrapRegistererWithPrefix(
836 "wrap_",
837 prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r),
838 )
839 },
840 equalButNotSameWithoutConstLabel,
841 func(r prometheus.Registerer) prometheus.Registerer {
842 return prometheus.WrapRegistererWithPrefix(
843 "wrap_",
844 prometheus.WrapRegistererWith(prometheus.Labels{"const": "label"}, r),
845 )
846 },
847 },
848 }
849
850 for _, s := range scenarios {
851 t.Run(s.name, func(t *testing.T) {
852 var err error
853 reg := prometheus.NewRegistry()
854 if err = s.registerWith(reg).Register(s.originalCollector); err != nil {
855 t.Fatal(err)
856 }
857 if err = s.reRegisterWith(reg).Register(s.newCollector); err == nil {
858 t.Fatal("expected error when registering new collector")
859 }
860 are := &prometheus.AlreadyRegisteredError{}
861 if errors.As(err, are) {
862 if are.ExistingCollector != s.originalCollector {
863 t.Error("expected original collector but got something else")
864 }
865 if are.ExistingCollector == s.newCollector {
866 t.Error("expected original collector but got new one")
867 }
868 } else {
869 t.Error("unexpected error:", err)
870 }
871 })
872 }
873 }
874
875 // TestRegisterUnregisterCollector ensures registering and unregistering a
876 // collector doesn't leave any dangling metrics.
877 // We use NewGoCollector as a nice concrete example of a collector with
878 // multiple metrics.
879 func TestRegisterUnregisterCollector(t *testing.T) {
880 col := prometheus.NewGoCollector()
881
882 reg := prometheus.NewRegistry()
883 reg.MustRegister(col)
884 reg.Unregister(col)
885 if metrics, err := reg.Gather(); err != nil {
886 t.Error("error gathering sample metric")
887 } else if len(metrics) != 0 {
888 t.Error("should have unregistered metric")
889 }
890 }
891
892 // TestHistogramVecRegisterGatherConcurrency is an end-to-end test that
893 // concurrently calls Observe on random elements of a HistogramVec while the
894 // same HistogramVec is registered concurrently and the Gather method of the
895 // registry is called concurrently.
896 func TestHistogramVecRegisterGatherConcurrency(t *testing.T) {
897 labelNames := make([]string, 16) // Need at least 13 to expose #512.
898 for i := range labelNames {
899 labelNames[i] = fmt.Sprint("label_", i)
900 }
901
902 var (
903 reg = prometheus.NewPedanticRegistry()
904 hv = prometheus.NewHistogramVec(
905 prometheus.HistogramOpts{
906 Name: "test_histogram",
907 Help: "This helps testing.",
908 ConstLabels: prometheus.Labels{"foo": "bar"},
909 },
910 labelNames,
911 )
912 labelValues = []string{"a", "b", "c", "alpha", "beta", "gamma", "aleph", "beth", "gimel"}
913 quit = make(chan struct{})
914 wg sync.WaitGroup
915 )
916
917 observe := func() {
918 defer wg.Done()
919 for {
920 select {
921 case <-quit:
922 return
923 default:
924 obs := rand.NormFloat64()*.1 + .2
925 values := make([]string, 0, len(labelNames))
926 for range labelNames {
927 values = append(values, labelValues[rand.Intn(len(labelValues))])
928 }
929 hv.WithLabelValues(values...).Observe(obs)
930 }
931 }
932 }
933
934 register := func() {
935 defer wg.Done()
936 for {
937 select {
938 case <-quit:
939 return
940 default:
941 if err := reg.Register(hv); err != nil {
942 if !errors.As(err, &prometheus.AlreadyRegisteredError{}) {
943 t.Error("Registering failed:", err)
944 }
945 }
946 time.Sleep(7 * time.Millisecond)
947 }
948 }
949 }
950
951 gather := func() {
952 defer wg.Done()
953 for {
954 select {
955 case <-quit:
956 return
957 default:
958 if g, err := reg.Gather(); err != nil {
959 t.Error("Gathering failed:", err)
960 } else {
961 if len(g) == 0 {
962 continue
963 }
964 if len(g) != 1 {
965 t.Error("Gathered unexpected number of metric families:", len(g))
966 }
967 if len(g[0].Metric[0].Label) != len(labelNames)+1 {
968 t.Error("Gathered unexpected number of label pairs:", len(g[0].Metric[0].Label))
969 }
970 }
971 time.Sleep(4 * time.Millisecond)
972 }
973 }
974 }
975
976 wg.Add(10)
977 go observe()
978 go observe()
979 go register()
980 go observe()
981 go gather()
982 go observe()
983 go register()
984 go observe()
985 go gather()
986 go observe()
987
988 time.Sleep(time.Second)
989 close(quit)
990 wg.Wait()
991 }
992
993 func TestWriteToTextfile(t *testing.T) {
994 expectedOut := `# HELP test_counter test counter
995 # TYPE test_counter counter
996 test_counter{name="qux"} 1
997 # HELP test_gauge test gauge
998 # TYPE test_gauge gauge
999 test_gauge{name="baz"} 1.1
1000 # HELP test_hist test histogram
1001 # TYPE test_hist histogram
1002 test_hist_bucket{name="bar",le="0.005"} 0
1003 test_hist_bucket{name="bar",le="0.01"} 0
1004 test_hist_bucket{name="bar",le="0.025"} 0
1005 test_hist_bucket{name="bar",le="0.05"} 0
1006 test_hist_bucket{name="bar",le="0.1"} 0
1007 test_hist_bucket{name="bar",le="0.25"} 0
1008 test_hist_bucket{name="bar",le="0.5"} 0
1009 test_hist_bucket{name="bar",le="1"} 1
1010 test_hist_bucket{name="bar",le="2.5"} 1
1011 test_hist_bucket{name="bar",le="5"} 2
1012 test_hist_bucket{name="bar",le="10"} 2
1013 test_hist_bucket{name="bar",le="+Inf"} 2
1014 test_hist_sum{name="bar"} 3.64
1015 test_hist_count{name="bar"} 2
1016 # HELP test_summary test summary
1017 # TYPE test_summary summary
1018 test_summary{name="foo",quantile="0.5"} 10
1019 test_summary{name="foo",quantile="0.9"} 20
1020 test_summary{name="foo",quantile="0.99"} 20
1021 test_summary_sum{name="foo"} 30
1022 test_summary_count{name="foo"} 2
1023 `
1024
1025 registry := prometheus.NewRegistry()
1026
1027 summary := prometheus.NewSummaryVec(
1028 prometheus.SummaryOpts{
1029 Name: "test_summary",
1030 Help: "test summary",
1031 Objectives: map[float64]float64{
1032 0.5: 0.05,
1033 0.9: 0.01,
1034 0.99: 0.001,
1035 },
1036 },
1037 []string{"name"},
1038 )
1039
1040 histogram := prometheus.NewHistogramVec(
1041 prometheus.HistogramOpts{
1042 Name: "test_hist",
1043 Help: "test histogram",
1044 },
1045 []string{"name"},
1046 )
1047
1048 gauge := prometheus.NewGaugeVec(
1049 prometheus.GaugeOpts{
1050 Name: "test_gauge",
1051 Help: "test gauge",
1052 },
1053 []string{"name"},
1054 )
1055
1056 counter := prometheus.NewCounterVec(
1057 prometheus.CounterOpts{
1058 Name: "test_counter",
1059 Help: "test counter",
1060 },
1061 []string{"name"},
1062 )
1063
1064 registry.MustRegister(summary)
1065 registry.MustRegister(histogram)
1066 registry.MustRegister(gauge)
1067 registry.MustRegister(counter)
1068
1069 summary.With(prometheus.Labels{"name": "foo"}).Observe(10)
1070 summary.With(prometheus.Labels{"name": "foo"}).Observe(20)
1071 histogram.With(prometheus.Labels{"name": "bar"}).Observe(0.93)
1072 histogram.With(prometheus.Labels{"name": "bar"}).Observe(2.71)
1073 gauge.With(prometheus.Labels{"name": "baz"}).Set(1.1)
1074 counter.With(prometheus.Labels{"name": "qux"}).Inc()
1075
1076 tmpfile, err := os.CreateTemp("", "prom_registry_test")
1077 if err != nil {
1078 t.Fatal(err)
1079 }
1080 defer os.Remove(tmpfile.Name())
1081
1082 if err := prometheus.WriteToTextfile(tmpfile.Name(), registry); err != nil {
1083 t.Fatal(err)
1084 }
1085
1086 fileBytes, err := os.ReadFile(tmpfile.Name())
1087 if err != nil {
1088 t.Fatal(err)
1089 }
1090 fileContents := string(fileBytes)
1091
1092 if fileContents != expectedOut {
1093 t.Errorf(
1094 "files don't match, got:\n%s\nwant:\n%s",
1095 fileContents, expectedOut,
1096 )
1097 }
1098 }
1099
1100 // collidingCollector is a collection of prometheus.Collectors,
1101 // and is itself a prometheus.Collector.
1102 type collidingCollector struct {
1103 i int
1104 name string
1105
1106 a, b, c, d prometheus.Collector
1107 }
1108
1109 // Describe satisfies part of the prometheus.Collector interface.
1110 func (m *collidingCollector) Describe(desc chan<- *prometheus.Desc) {
1111 m.a.Describe(desc)
1112 m.b.Describe(desc)
1113 m.c.Describe(desc)
1114 m.d.Describe(desc)
1115 }
1116
1117 // Collect satisfies part of the prometheus.Collector interface.
1118 func (m *collidingCollector) Collect(metric chan<- prometheus.Metric) {
1119 m.a.Collect(metric)
1120 m.b.Collect(metric)
1121 m.c.Collect(metric)
1122 m.d.Collect(metric)
1123 }
1124
1125 // TestAlreadyRegistered will fail with the old, weaker hash function. It is
1126 // taken from https://play.golang.org/p/HpV7YE6LI_4 , authored by @awilliams.
1127 func TestAlreadyRegisteredCollision(t *testing.T) {
1128 reg := prometheus.NewRegistry()
1129
1130 for i := 0; i < 10000; i++ {
1131 // A collector should be considered unique if its name and const
1132 // label values are unique.
1133
1134 name := fmt.Sprintf("test-collector-%010d", i)
1135
1136 collector := collidingCollector{
1137 i: i,
1138 name: name,
1139
1140 a: prometheus.NewCounter(prometheus.CounterOpts{
1141 Name: "my_collector_a",
1142 ConstLabels: prometheus.Labels{
1143 "name": name,
1144 "type": "test",
1145 },
1146 }),
1147 b: prometheus.NewCounter(prometheus.CounterOpts{
1148 Name: "my_collector_b",
1149 ConstLabels: prometheus.Labels{
1150 "name": name,
1151 "type": "test",
1152 },
1153 }),
1154 c: prometheus.NewCounter(prometheus.CounterOpts{
1155 Name: "my_collector_c",
1156 ConstLabels: prometheus.Labels{
1157 "name": name,
1158 "type": "test",
1159 },
1160 }),
1161 d: prometheus.NewCounter(prometheus.CounterOpts{
1162 Name: "my_collector_d",
1163 ConstLabels: prometheus.Labels{
1164 "name": name,
1165 "type": "test",
1166 },
1167 }),
1168 }
1169
1170 // Register should not fail, since each collector has a unique
1171 // set of sub-collectors, determined by their names and const label values.
1172 if err := reg.Register(&collector); err != nil {
1173 are := &prometheus.AlreadyRegisteredError{}
1174 if !errors.As(err, are) {
1175 t.Fatal(err)
1176 }
1177
1178 previous := are.ExistingCollector.(*collidingCollector)
1179 current := are.NewCollector.(*collidingCollector)
1180
1181 t.Errorf("Unexpected registration error: %q\nprevious collector: %s (i=%d)\ncurrent collector %s (i=%d)", are, previous.name, previous.i, current.name, current.i)
1182 }
1183 }
1184 }
1185
1186 type tGatherer struct {
1187 done bool
1188 err error
1189 }
1190
1191 func (g *tGatherer) Gather() (_ []*dto.MetricFamily, done func(), err error) {
1192 name := "g1"
1193 val := 1.0
1194 return []*dto.MetricFamily{
1195 {Name: &name, Metric: []*dto.Metric{{Gauge: &dto.Gauge{Value: &val}}}},
1196 }, func() { g.done = true }, g.err
1197 }
1198
1199 func TestNewMultiTRegistry(t *testing.T) {
1200 treg := &tGatherer{}
1201
1202 t.Run("one registry", func(t *testing.T) {
1203 m := prometheus.NewMultiTRegistry(treg)
1204 ret, done, err := m.Gather()
1205 if err != nil {
1206 t.Error("gather failed:", err)
1207 }
1208 done()
1209 if len(ret) != 1 {
1210 t.Error("unexpected number of metric families, expected 1, got", ret)
1211 }
1212 if !treg.done {
1213 t.Error("inner transactional registry not marked as done")
1214 }
1215 })
1216
1217 reg := prometheus.NewRegistry()
1218 if err := reg.Register(prometheus.NewCounter(prometheus.CounterOpts{Name: "c1", Help: "help c1"})); err != nil {
1219 t.Error("registration failed:", err)
1220 }
1221
1222 // Note on purpose two registries will have exactly same metric family name (but with different string).
1223 // This behaviour is undefined at the moment.
1224 if err := reg.Register(prometheus.NewGauge(prometheus.GaugeOpts{Name: "g1", Help: "help g1"})); err != nil {
1225 t.Error("registration failed:", err)
1226 }
1227 treg.done = false
1228
1229 t.Run("two registries", func(t *testing.T) {
1230 m := prometheus.NewMultiTRegistry(prometheus.ToTransactionalGatherer(reg), treg)
1231 ret, done, err := m.Gather()
1232 if err != nil {
1233 t.Error("gather failed:", err)
1234 }
1235 done()
1236 if len(ret) != 3 {
1237 t.Error("unexpected number of metric families, expected 3, got", ret)
1238 }
1239 if !treg.done {
1240 t.Error("inner transactional registry not marked as done")
1241 }
1242 })
1243
1244 treg.done = false
1245 // Inject error.
1246 treg.err = errors.New("test err")
1247
1248 t.Run("two registries, one with error", func(t *testing.T) {
1249 m := prometheus.NewMultiTRegistry(prometheus.ToTransactionalGatherer(reg), treg)
1250 ret, done, err := m.Gather()
1251 if !errors.Is(err, treg.err) {
1252 t.Error("unexpected error:", err)
1253 }
1254 done()
1255 if len(ret) != 3 {
1256 t.Error("unexpected number of metric families, expected 3, got", ret)
1257 }
1258 // Still on error, we expect done to be triggered.
1259 if !treg.done {
1260 t.Error("inner transactional registry not marked as done")
1261 }
1262 })
1263 }
1264
1265 // This example shows how to use multiple registries for registering and
1266 // unregistering groups of metrics.
1267 func ExampleRegistry_grouping() {
1268 // Create a global registry.
1269 globalReg := prometheus.NewRegistry()
1270
1271 // Spawn 10 workers, each of which will have their own group of metrics.
1272 for i := 0; i < 10; i++ {
1273 // Create a new registry for each worker, which acts as a group of
1274 // worker-specific metrics.
1275 workerReg := prometheus.NewRegistry()
1276 globalReg.Register(workerReg)
1277
1278 go func(workerID int) {
1279 // Once the worker is done, it can unregister itself.
1280 defer globalReg.Unregister(workerReg)
1281
1282 workTime := prometheus.NewCounter(prometheus.CounterOpts{
1283 Name: "worker_total_work_time_milliseconds",
1284 ConstLabels: prometheus.Labels{
1285 // Generate a label unique to this worker so its metric doesn't
1286 // collide with the metrics from other workers.
1287 "worker_id": strconv.Itoa(workerID),
1288 },
1289 })
1290 workerReg.MustRegister(workTime)
1291
1292 start := time.Now()
1293 time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
1294 workTime.Add(float64(time.Since(start).Milliseconds()))
1295 }(i)
1296 }
1297 }
1298
1299 type customCollector struct {
1300 collectFunc func(ch chan<- prometheus.Metric)
1301 }
1302
1303 func (co *customCollector) Describe(_ chan<- *prometheus.Desc) {}
1304
1305 func (co *customCollector) Collect(ch chan<- prometheus.Metric) {
1306 co.collectFunc(ch)
1307 }
1308
1309 // TestCheckMetricConsistency
1310 func TestCheckMetricConsistency(t *testing.T) {
1311 reg := prometheus.NewRegistry()
1312 timestamp := time.Now()
1313
1314 desc := prometheus.NewDesc("metric_a", "", nil, nil)
1315 metric := prometheus.MustNewConstMetric(desc, prometheus.CounterValue, 1)
1316
1317 validCollector := &customCollector{
1318 collectFunc: func(ch chan<- prometheus.Metric) {
1319 ch <- prometheus.NewMetricWithTimestamp(timestamp.Add(-1*time.Minute), metric)
1320 ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
1321 },
1322 }
1323 reg.MustRegister(validCollector)
1324 _, err := reg.Gather()
1325 if err != nil {
1326 t.Error("metric validation should succeed:", err)
1327 }
1328 reg.Unregister(validCollector)
1329
1330 invalidCollector := &customCollector{
1331 collectFunc: func(ch chan<- prometheus.Metric) {
1332 ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
1333 ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
1334 },
1335 }
1336 reg.MustRegister(invalidCollector)
1337 _, err = reg.Gather()
1338 if err == nil {
1339 t.Error("metric validation should return an error")
1340 }
1341 reg.Unregister(invalidCollector)
1342 }
1343
1344 func TestGatherDoesNotLeakGoroutines(t *testing.T) {
1345 // Use goleak to verify that no unexpected goroutines are leaked during the test.
1346 defer goleak.VerifyNone(t)
1347
1348 // Create a new Prometheus registry without any default collectors.
1349 reg := prometheus.NewRegistry()
1350
1351 // Register 100 simple Gauge metrics with distinct names and constant labels.
1352 for i := 0; i < 100; i++ {
1353 reg.MustRegister(prometheus.NewGauge(prometheus.GaugeOpts{
1354 Name: "test_metric_" + string(rune(i)),
1355 Help: "Test metric",
1356 ConstLabels: prometheus.Labels{"id": string(rune(i))},
1357 }))
1358 }
1359
1360 // Call Gather repeatedly to simulate stress and check for potential goroutine leaks.
1361 for i := 0; i < 1000; i++ {
1362 _, err := reg.Gather()
1363 if err != nil {
1364 t.Fatalf("unexpected error from Gather: %v", err)
1365 }
1366 }
1367 }