Debian Codegraph @

prometheus/registry.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 package prometheus
15
16 import (
17 "bytes"
18 "errors"
19 "fmt"
20 "os"
21 "path/filepath"
22 "runtime"
23 "sort"
24 "strconv"
25 "strings"
26 "sync"
27 "unicode/utf8"
28
29 "github.com/prometheus/client_golang/prometheus/internal"
30
31 "github.com/cespare/xxhash/v2"
32 dto "github.com/prometheus/client_model/go"
33 "github.com/prometheus/common/expfmt"
34 "google.golang.org/protobuf/proto"
35 )
36
37 const (
38 // Capacity for the channel to collect metrics and descriptors.
39 capMetricChan = 1000
40 capDescChan = 10
41 )
42
43 // DefaultRegisterer and DefaultGatherer are the implementations of the
44 // Registerer and Gatherer interface a number of convenience functions in this
45 // package act on. Initially, both variables point to the same Registry, which
46 // has a process collector (currently on Linux only, see NewProcessCollector)
47 // and a Go collector (see NewGoCollector, in particular the note about
48 // stop-the-world implication with Go versions older than 1.9) already
49 // registered. This approach to keep default instances as global state mirrors
50 // the approach of other packages in the Go standard library. Note that there
51 // are caveats. Change the variables with caution and only if you understand the
52 // consequences. Users who want to avoid global state altogether should not use
53 // the convenience functions and act on custom instances instead.
54 var (
55 defaultRegistry = NewRegistry()
56 DefaultRegisterer Registerer = defaultRegistry
57 DefaultGatherer Gatherer = defaultRegistry
58 )
59
60 func init() {
61 MustRegister(NewProcessCollector(ProcessCollectorOpts{}))
62 MustRegister(NewGoCollector())
63 }
64
65 // NewRegistry creates a new vanilla Registry without any Collectors
66 // pre-registered.
67 func NewRegistry() *Registry {
68 return &Registry{
69 collectorsByID: map[uint64]Collector{},
70 descIDs: map[uint64]struct{}{},
71 dimHashesByName: map[string]uint64{},
72 }
73 }
74
75 // NewPedanticRegistry returns a registry that checks during collection if each
76 // collected Metric is consistent with its reported Desc, and if the Desc has
77 // actually been registered with the registry. Unchecked Collectors (those whose
78 // Describe method does not yield any descriptors) are excluded from the check.
79 //
80 // Usually, a Registry will be happy as long as the union of all collected
81 // Metrics is consistent and valid even if some metrics are not consistent with
82 // their own Desc or a Desc provided by their registered Collector. Well-behaved
83 // Collectors and Metrics will only provide consistent Descs. This Registry is
84 // useful to test the implementation of Collectors and Metrics.
85 func NewPedanticRegistry() *Registry {
86 r := NewRegistry()
87 r.pedanticChecksEnabled = true
88 return r
89 }
90
91 // Registerer is the interface for the part of a registry in charge of
92 // registering and unregistering. Users of custom registries should use
93 // Registerer as type for registration purposes (rather than the Registry type
94 // directly). In that way, they are free to use custom Registerer implementation
95 // (e.g. for testing purposes).
96 type Registerer interface {
97 // Register registers a new Collector to be included in metrics
98 // collection. It returns an error if the descriptors provided by the
99 // Collector are invalid or if they — in combination with descriptors of
100 // already registered Collectors — do not fulfill the consistency and
101 // uniqueness criteria described in the documentation of metric.Desc.
102 //
103 // If the provided Collector is equal to a Collector already registered
104 // (which includes the case of re-registering the same Collector), the
105 // returned error is an instance of AlreadyRegisteredError, which
106 // contains the previously registered Collector.
107 //
108 // A Collector whose Describe method does not yield any Desc is treated
109 // as unchecked. Registration will always succeed. No check for
110 // re-registering (see previous paragraph) is performed. Thus, the
111 // caller is responsible for not double-registering the same unchecked
112 // Collector, and for providing a Collector that will not cause
113 // inconsistent metrics on collection. (This would lead to scrape
114 // errors.)
115 Register(Collector) error
116 // MustRegister works like Register but registers any number of
117 // Collectors and panics upon the first registration that causes an
118 // error.
119 MustRegister(...Collector)
120 // Unregister unregisters the Collector that equals the Collector passed
121 // in as an argument. (Two Collectors are considered equal if their
122 // Describe method yields the same set of descriptors.) The function
123 // returns whether a Collector was unregistered. Note that an unchecked
124 // Collector cannot be unregistered (as its Describe method does not
125 // yield any descriptor).
126 //
127 // Note that even after unregistering, it will not be possible to
128 // register a new Collector that is inconsistent with the unregistered
129 // Collector, e.g. a Collector collecting metrics with the same name but
130 // a different help string. The rationale here is that the same registry
131 // instance must only collect consistent metrics throughout its
132 // lifetime.
133 Unregister(Collector) bool
134 }
135
136 // Gatherer is the interface for the part of a registry in charge of gathering
137 // the collected metrics into a number of MetricFamilies. The Gatherer interface
138 // comes with the same general implication as described for the Registerer
139 // interface.
140 type Gatherer interface {
141 // Gather calls the Collect method of the registered Collectors and then
142 // gathers the collected metrics into a lexicographically sorted slice
143 // of uniquely named MetricFamily protobufs. Gather ensures that the
144 // returned slice is valid and self-consistent so that it can be used
145 // for valid exposition. As an exception to the strict consistency
146 // requirements described for metric.Desc, Gather will tolerate
147 // different sets of label names for metrics of the same metric family.
148 //
149 // Even if an error occurs, Gather attempts to gather as many metrics as
150 // possible. Hence, if a non-nil error is returned, the returned
151 // MetricFamily slice could be nil (in case of a fatal error that
152 // prevented any meaningful metric collection) or contain a number of
153 // MetricFamily protobufs, some of which might be incomplete, and some
154 // might be missing altogether. The returned error (which might be a
155 // MultiError) explains the details. Note that this is mostly useful for
156 // debugging purposes. If the gathered protobufs are to be used for
157 // exposition in actual monitoring, it is almost always better to not
158 // expose an incomplete result and instead disregard the returned
159 // MetricFamily protobufs in case the returned error is non-nil.
160 Gather() ([]*dto.MetricFamily, error)
161 }
162
163 // Register registers the provided Collector with the DefaultRegisterer.
164 //
165 // Register is a shortcut for DefaultRegisterer.Register(c). See there for more
166 // details.
167 func Register(c Collector) error {
168 return DefaultRegisterer.Register(c)
169 }
170
171 // MustRegister registers the provided Collectors with the DefaultRegisterer and
172 // panics if any error occurs.
173 //
174 // MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See
175 // there for more details.
176 func MustRegister(cs ...Collector) {
177 DefaultRegisterer.MustRegister(cs...)
178 }
179
180 // Unregister removes the registration of the provided Collector from the
181 // DefaultRegisterer.
182 //
183 // Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for
184 // more details.
185 func Unregister(c Collector) bool {
186 return DefaultRegisterer.Unregister(c)
187 }
188
189 // GathererFunc turns a function into a Gatherer.
190 type GathererFunc func() ([]*dto.MetricFamily, error)
191
192 // Gather implements Gatherer.
193 func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error) {
194 return gf()
195 }
196
197 // AlreadyRegisteredError is returned by the Register method if the Collector to
198 // be registered has already been registered before, or a different Collector
199 // that collects the same metrics has been registered before. Registration fails
200 // in that case, but you can detect from the kind of error what has
201 // happened. The error contains fields for the existing Collector and the
202 // (rejected) new Collector that equals the existing one. This can be used to
203 // find out if an equal Collector has been registered before and switch over to
204 // using the old one, as demonstrated in the example.
205 type AlreadyRegisteredError struct {
206 ExistingCollector, NewCollector Collector
207 }
208
209 func (err AlreadyRegisteredError) Error() string {
210 return "duplicate metrics collector registration attempted"
211 }
212
213 // MultiError is a slice of errors implementing the error interface. It is used
214 // by a Gatherer to report multiple errors during MetricFamily gathering.
215 type MultiError []error
216
217 // Error formats the contained errors as a bullet point list, preceded by the
218 // total number of errors. Note that this results in a multi-line string.
219 func (errs MultiError) Error() string {
220 if len(errs) == 0 {
221 return ""
222 }
223 buf := &bytes.Buffer{}
224 fmt.Fprintf(buf, "%d error(s) occurred:", len(errs))
225 for _, err := range errs {
226 fmt.Fprintf(buf, "\n* %s", err)
227 }
228 return buf.String()
229 }
230
231 // Append appends the provided error if it is not nil.
232 func (errs *MultiError) Append(err error) {
233 if err != nil {
234 *errs = append(*errs, err)
235 }
236 }
237
238 // MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only
239 // contained error as error if len(errs is 1). In all other cases, it returns
240 // the MultiError directly. This is helpful for returning a MultiError in a way
241 // that only uses the MultiError if needed.
242 func (errs MultiError) MaybeUnwrap() error {
243 switch len(errs) {
244 case 0:
245 return nil
246 case 1:
247 return errs[0]
248 default:
249 return errs
250 }
251 }
252
253 // Registry registers Prometheus collectors, collects their metrics, and gathers
254 // them into MetricFamilies for exposition. It implements Registerer, Gatherer,
255 // and Collector. The zero value is not usable. Create instances with
256 // NewRegistry or NewPedanticRegistry.
257 //
258 // Registry implements Collector to allow it to be used for creating groups of
259 // metrics. See the Grouping example for how this can be done.
260 type Registry struct {
261 mtx sync.RWMutex
262 collectorsByID map[uint64]Collector // ID is a hash of the descIDs.
263 descIDs map[uint64]struct{}
264 dimHashesByName map[string]uint64
265 uncheckedCollectors []Collector
266 pedanticChecksEnabled bool
267 }
268
269 // Register implements Registerer.
270 func (r *Registry) Register(c Collector) error {
271 var (
272 descChan = make(chan *Desc, capDescChan)
273 newDescIDs = map[uint64]struct{}{}
274 newDimHashesByName = map[string]uint64{}
275 collectorID uint64 // All desc IDs XOR'd together.
276 duplicateDescErr error
277 )
278 go func() {
279 c.Describe(descChan)
280 close(descChan)
281 }()
282 r.mtx.Lock()
283 defer func() {
284 // Drain channel in case of premature return to not leak a goroutine.
285 for range descChan {
286 }
287 r.mtx.Unlock()
288 }()
289 // Conduct various tests...
290 for desc := range descChan {
291
292 // Is the descriptor valid at all?
293 if desc.err != nil {
294 return fmt.Errorf("descriptor %s is invalid: %w", desc, desc.err)
295 }
296
297 // Is the descID unique?
298 // (In other words: Is the fqName + constLabel combination unique?)
299 if _, exists := r.descIDs[desc.id]; exists {
300 duplicateDescErr = fmt.Errorf("descriptor %s already exists with the same fully-qualified name and const label values", desc)
301 }
302 // If it is not a duplicate desc in this collector, XOR it to
303 // the collectorID. (We allow duplicate descs within the same
304 // collector, but their existence must be a no-op.)
305 if _, exists := newDescIDs[desc.id]; !exists {
306 newDescIDs[desc.id] = struct{}{}
307 collectorID ^= desc.id
308 }
309
310 // Are all the label names and the help string consistent with
311 // previous descriptors of the same name?
312 // First check existing descriptors...
313 if dimHash, exists := r.dimHashesByName[desc.fqName]; exists {
314 if dimHash != desc.dimHash {
315 return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
316 }
317 continue
318 }
319
320 // ...then check the new descriptors already seen.
321 if dimHash, exists := newDimHashesByName[desc.fqName]; exists {
322 if dimHash != desc.dimHash {
323 return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
324 }
325 continue
326 }
327 newDimHashesByName[desc.fqName] = desc.dimHash
328 }
329 // A Collector yielding no Desc at all is considered unchecked.
330 if len(newDescIDs) == 0 {
331 r.uncheckedCollectors = append(r.uncheckedCollectors, c)
332 return nil
333 }
334 if existing, exists := r.collectorsByID[collectorID]; exists {
335 switch e := existing.(type) {
336 case *wrappingCollector:
337 return AlreadyRegisteredError{
338 ExistingCollector: e.unwrapRecursively(),
339 NewCollector: c,
340 }
341 default:
342 return AlreadyRegisteredError{
343 ExistingCollector: e,
344 NewCollector: c,
345 }
346 }
347 }
348 // If the collectorID is new, but at least one of the descs existed
349 // before, we are in trouble.
350 if duplicateDescErr != nil {
351 return duplicateDescErr
352 }
353
354 // Only after all tests have passed, actually register.
355 r.collectorsByID[collectorID] = c
356 for hash := range newDescIDs {
357 r.descIDs[hash] = struct{}{}
358 }
359 for name, dimHash := range newDimHashesByName {
360 r.dimHashesByName[name] = dimHash
361 }
362 return nil
363 }
364
365 // Unregister implements Registerer.
366 func (r *Registry) Unregister(c Collector) bool {
367 var (
368 descChan = make(chan *Desc, capDescChan)
369 descIDs = map[uint64]struct{}{}
370 collectorID uint64 // All desc IDs XOR'd together.
371 )
372 go func() {
373 c.Describe(descChan)
374 close(descChan)
375 }()
376 for desc := range descChan {
377 if _, exists := descIDs[desc.id]; !exists {
378 collectorID ^= desc.id
379 descIDs[desc.id] = struct{}{}
380 }
381 }
382
383 r.mtx.RLock()
384 if _, exists := r.collectorsByID[collectorID]; !exists {
385 r.mtx.RUnlock()
386 return false
387 }
388 r.mtx.RUnlock()
389
390 r.mtx.Lock()
391 defer r.mtx.Unlock()
392
393 delete(r.collectorsByID, collectorID)
394 for id := range descIDs {
395 delete(r.descIDs, id)
396 }
397 // dimHashesByName is left untouched as those must be consistent
398 // throughout the lifetime of a program.
399 return true
400 }
401
402 // MustRegister implements Registerer.
403 func (r *Registry) MustRegister(cs ...Collector) {
404 for _, c := range cs {
405 if err := r.Register(c); err != nil {
406 panic(err)
407 }
408 }
409 }
410
411 // Gather implements Gatherer.
412 func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
413 r.mtx.RLock()
414
415 if len(r.collectorsByID) == 0 && len(r.uncheckedCollectors) == 0 {
416 // Fast path.
417 r.mtx.RUnlock()
418 return nil, nil
419 }
420
421 var (
422 checkedMetricChan = make(chan Metric, capMetricChan)
423 uncheckedMetricChan = make(chan Metric, capMetricChan)
424 metricHashes = map[uint64]struct{}{}
425 wg sync.WaitGroup
426 errs MultiError // The collected errors to return in the end.
427 registeredDescIDs map[uint64]struct{} // Only used for pedantic checks
428 )
429
430 goroutineBudget := len(r.collectorsByID) + len(r.uncheckedCollectors)
431 metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName))
432 checkedCollectors := make(chan Collector, len(r.collectorsByID))
433 uncheckedCollectors := make(chan Collector, len(r.uncheckedCollectors))
434 for _, collector := range r.collectorsByID {
435 checkedCollectors <- collector
436 }
437 for _, collector := range r.uncheckedCollectors {
438 uncheckedCollectors <- collector
439 }
440 // In case pedantic checks are enabled, we have to copy the map before
441 // giving up the RLock.
442 if r.pedanticChecksEnabled {
443 registeredDescIDs = make(map[uint64]struct{}, len(r.descIDs))
444 for id := range r.descIDs {
445 registeredDescIDs[id] = struct{}{}
446 }
447 }
448 r.mtx.RUnlock()
449
450 wg.Add(goroutineBudget)
451
452 collectWorker := func() {
453 for {
454 select {
455 case collector := <-checkedCollectors:
456 collector.Collect(checkedMetricChan)
457 case collector := <-uncheckedCollectors:
458 collector.Collect(uncheckedMetricChan)
459 default:
460 return
461 }
462 wg.Done()
463 }
464 }
465
466 // Start the first worker now to make sure at least one is running.
467 go collectWorker()
468 goroutineBudget--
469
470 // Close checkedMetricChan and uncheckedMetricChan once all collectors
471 // are collected.
472 go func() {
473 wg.Wait()
474 close(checkedMetricChan)
475 close(uncheckedMetricChan)
476 }()
477
478 // Drain checkedMetricChan and uncheckedMetricChan in case of premature return.
479 defer func() {
480 if checkedMetricChan != nil {
481 for range checkedMetricChan {
482 }
483 }
484 if uncheckedMetricChan != nil {
485 for range uncheckedMetricChan {
486 }
487 }
488 }()
489
490 // Copy the channel references so we can nil them out later to remove
491 // them from the select statements below.
492 cmc := checkedMetricChan
493 umc := uncheckedMetricChan
494
495 for {
496 select {
497 case metric, ok := <-cmc:
498 if !ok {
499 cmc = nil
500 break
501 }
502 errs.Append(processMetric(
503 metric, metricFamiliesByName,
504 metricHashes,
505 registeredDescIDs,
506 ))
507 case metric, ok := <-umc:
508 if !ok {
509 umc = nil
510 break
511 }
512 errs.Append(processMetric(
513 metric, metricFamiliesByName,
514 metricHashes,
515 nil,
516 ))
517 default:
518 if goroutineBudget <= 0 || len(checkedCollectors)+len(uncheckedCollectors) == 0 {
519 // All collectors are already being worked on or
520 // we have already as many goroutines started as
521 // there are collectors. Do the same as above,
522 // just without the default.
523 select {
524 case metric, ok := <-cmc:
525 if !ok {
526 cmc = nil
527 break
528 }
529 errs.Append(processMetric(
530 metric, metricFamiliesByName,
531 metricHashes,
532 registeredDescIDs,
533 ))
534 case metric, ok := <-umc:
535 if !ok {
536 umc = nil
537 break
538 }
539 errs.Append(processMetric(
540 metric, metricFamiliesByName,
541 metricHashes,
542 nil,
543 ))
544 }
545 break
546 }
547 // Start more workers.
548 go collectWorker()
549 goroutineBudget--
550 runtime.Gosched()
551 }
552 // Once both checkedMetricChan and uncheckedMetricChan are closed
553 // and drained, the contraption above will nil out cmc and umc,
554 // and then we can leave the collect loop here.
555 if cmc == nil && umc == nil {
556 break
557 }
558 }
559 return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
560 }
561
562 // Describe implements Collector.
563 func (r *Registry) Describe(ch chan<- *Desc) {
564 r.mtx.RLock()
565 defer r.mtx.RUnlock()
566
567 // Only report the checked Collectors; unchecked collectors don't report any
568 // Desc.
569 for _, c := range r.collectorsByID {
570 c.Describe(ch)
571 }
572 }
573
574 // Collect implements Collector.
575 func (r *Registry) Collect(ch chan<- Metric) {
576 r.mtx.RLock()
577 defer r.mtx.RUnlock()
578
579 for _, c := range r.collectorsByID {
580 c.Collect(ch)
581 }
582 for _, c := range r.uncheckedCollectors {
583 c.Collect(ch)
584 }
585 }
586
587 // WriteToTextfile calls Gather on the provided Gatherer, encodes the result in the
588 // Prometheus text format, and writes it to a temporary file. Upon success, the
589 // temporary file is renamed to the provided filename.
590 //
591 // This is intended for use with the textfile collector of the node exporter.
592 // Note that the node exporter expects the filename to be suffixed with ".prom".
593 func WriteToTextfile(filename string, g Gatherer) error {
594 tmp, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename))
595 if err != nil {
596 return err
597 }
598 defer os.Remove(tmp.Name())
599
600 mfs, err := g.Gather()
601 if err != nil {
602 return err
603 }
604 for _, mf := range mfs {
605 if _, err := expfmt.MetricFamilyToText(tmp, mf); err != nil {
606 return err
607 }
608 }
609 if err := tmp.Close(); err != nil {
610 return err
611 }
612
613 if err := os.Chmod(tmp.Name(), 0o644); err != nil {
614 return err
615 }
616 return os.Rename(tmp.Name(), filename)
617 }
618
619 // processMetric is an internal helper method only used by the Gather method.
620 func processMetric(
621 metric Metric,
622 metricFamiliesByName map[string]*dto.MetricFamily,
623 metricHashes map[uint64]struct{},
624 registeredDescIDs map[uint64]struct{},
625 ) error {
626 desc := metric.Desc()
627 // Wrapped metrics collected by an unchecked Collector can have an
628 // invalid Desc.
629 if desc.err != nil {
630 return desc.err
631 }
632 dtoMetric := &dto.Metric{}
633 if err := metric.Write(dtoMetric); err != nil {
634 return fmt.Errorf("error collecting metric %v: %w", desc, err)
635 }
636 metricFamily, ok := metricFamiliesByName[desc.fqName]
637 if ok { // Existing name.
638 if metricFamily.GetHelp() != desc.help {
639 return fmt.Errorf(
640 "collected metric %s %s has help %q but should have %q",
641 desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(),
642 )
643 }
644 // TODO(beorn7): Simplify switch once Desc has type.
645 switch metricFamily.GetType() {
646 case dto.MetricType_COUNTER:
647 if dtoMetric.Counter == nil {
648 return fmt.Errorf(
649 "collected metric %s %s should be a Counter",
650 desc.fqName, dtoMetric,
651 )
652 }
653 case dto.MetricType_GAUGE:
654 if dtoMetric.Gauge == nil {
655 return fmt.Errorf(
656 "collected metric %s %s should be a Gauge",
657 desc.fqName, dtoMetric,
658 )
659 }
660 case dto.MetricType_SUMMARY:
661 if dtoMetric.Summary == nil {
662 return fmt.Errorf(
663 "collected metric %s %s should be a Summary",
664 desc.fqName, dtoMetric,
665 )
666 }
667 case dto.MetricType_UNTYPED:
668 if dtoMetric.Untyped == nil {
669 return fmt.Errorf(
670 "collected metric %s %s should be Untyped",
671 desc.fqName, dtoMetric,
672 )
673 }
674 case dto.MetricType_HISTOGRAM:
675 if dtoMetric.Histogram == nil {
676 return fmt.Errorf(
677 "collected metric %s %s should be a Histogram",
678 desc.fqName, dtoMetric,
679 )
680 }
681 default:
682 panic("encountered MetricFamily with invalid type")
683 }
684 } else { // New name.
685 metricFamily = &dto.MetricFamily{}
686 metricFamily.Name = proto.String(desc.fqName)
687 metricFamily.Help = proto.String(desc.help)
688 // TODO(beorn7): Simplify switch once Desc has type.
689 switch {
690 case dtoMetric.Gauge != nil:
691 metricFamily.Type = dto.MetricType_GAUGE.Enum()
692 case dtoMetric.Counter != nil:
693 metricFamily.Type = dto.MetricType_COUNTER.Enum()
694 case dtoMetric.Summary != nil:
695 metricFamily.Type = dto.MetricType_SUMMARY.Enum()
696 case dtoMetric.Untyped != nil:
697 metricFamily.Type = dto.MetricType_UNTYPED.Enum()
698 case dtoMetric.Histogram != nil:
699 metricFamily.Type = dto.MetricType_HISTOGRAM.Enum()
700 default:
701 return fmt.Errorf("empty metric collected: %s", dtoMetric)
702 }
703 if err := checkSuffixCollisions(metricFamily, metricFamiliesByName); err != nil {
704 return err
705 }
706 metricFamiliesByName[desc.fqName] = metricFamily
707 }
708 if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes); err != nil {
709 return err
710 }
711 if registeredDescIDs != nil {
712 // Is the desc registered at all?
713 if _, exist := registeredDescIDs[desc.id]; !exist {
714 return fmt.Errorf(
715 "collected metric %s %s with unregistered descriptor %s",
716 metricFamily.GetName(), dtoMetric, desc,
717 )
718 }
719 if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil {
720 return err
721 }
722 }
723 metricFamily.Metric = append(metricFamily.Metric, dtoMetric)
724 return nil
725 }
726
727 // Gatherers is a slice of Gatherer instances that implements the Gatherer
728 // interface itself. Its Gather method calls Gather on all Gatherers in the
729 // slice in order and returns the merged results. Errors returned from the
730 // Gather calls are all returned in a flattened MultiError. Duplicate and
731 // inconsistent Metrics are skipped (first occurrence in slice order wins) and
732 // reported in the returned error.
733 //
734 // Gatherers can be used to merge the Gather results from multiple
735 // Registries. It also provides a way to directly inject existing MetricFamily
736 // protobufs into the gathering by creating a custom Gatherer with a Gather
737 // method that simply returns the existing MetricFamily protobufs. Note that no
738 // registration is involved (in contrast to Collector registration), so
739 // obviously registration-time checks cannot happen. Any inconsistencies between
740 // the gathered MetricFamilies are reported as errors by the Gather method, and
741 // inconsistent Metrics are dropped. Invalid parts of the MetricFamilies
742 // (e.g. syntactically invalid metric or label names) will go undetected.
743 type Gatherers []Gatherer
744
745 // Gather implements Gatherer.
746 func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) {
747 var (
748 metricFamiliesByName = map[string]*dto.MetricFamily{}
749 metricHashes = map[uint64]struct{}{}
750 errs MultiError // The collected errors to return in the end.
751 )
752
753 for i, g := range gs {
754 mfs, err := g.Gather()
755 if err != nil {
756 multiErr := MultiError{}
757 if errors.As(err, &multiErr) {
758 for _, err := range multiErr {
759 errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err))
760 }
761 } else {
762 errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err))
763 }
764 }
765 for _, mf := range mfs {
766 existingMF, exists := metricFamiliesByName[mf.GetName()]
767 if exists {
768 if existingMF.GetHelp() != mf.GetHelp() {
769 errs = append(errs, fmt.Errorf(
770 "gathered metric family %s has help %q but should have %q",
771 mf.GetName(), mf.GetHelp(), existingMF.GetHelp(),
772 ))
773 continue
774 }
775 if existingMF.GetType() != mf.GetType() {
776 errs = append(errs, fmt.Errorf(
777 "gathered metric family %s has type %s but should have %s",
778 mf.GetName(), mf.GetType(), existingMF.GetType(),
779 ))
780 continue
781 }
782 } else {
783 existingMF = &dto.MetricFamily{}
784 existingMF.Name = mf.Name
785 existingMF.Help = mf.Help
786 existingMF.Type = mf.Type
787 if err := checkSuffixCollisions(existingMF, metricFamiliesByName); err != nil {
788 errs = append(errs, err)
789 continue
790 }
791 metricFamiliesByName[mf.GetName()] = existingMF
792 }
793 for _, m := range mf.Metric {
794 if err := checkMetricConsistency(existingMF, m, metricHashes); err != nil {
795 errs = append(errs, err)
796 continue
797 }
798 existingMF.Metric = append(existingMF.Metric, m)
799 }
800 }
801 }
802 return internal.NormalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
803 }
804
805 // checkSuffixCollisions checks for collisions with the “magic” suffixes the
806 // Prometheus text format and the internal metric representation of the
807 // Prometheus server add while flattening Summaries and Histograms.
808 func checkSuffixCollisions(mf *dto.MetricFamily, mfs map[string]*dto.MetricFamily) error {
809 var (
810 newName = mf.GetName()
811 newType = mf.GetType()
812 newNameWithoutSuffix = ""
813 )
814 switch {
815 case strings.HasSuffix(newName, "_count"):
816 newNameWithoutSuffix = newName[:len(newName)-6]
817 case strings.HasSuffix(newName, "_sum"):
818 newNameWithoutSuffix = newName[:len(newName)-4]
819 case strings.HasSuffix(newName, "_bucket"):
820 newNameWithoutSuffix = newName[:len(newName)-7]
821 }
822 if newNameWithoutSuffix != "" {
823 if existingMF, ok := mfs[newNameWithoutSuffix]; ok {
824 switch existingMF.GetType() {
825 case dto.MetricType_SUMMARY:
826 if !strings.HasSuffix(newName, "_bucket") {
827 return fmt.Errorf(
828 "collected metric named %q collides with previously collected summary named %q",
829 newName, newNameWithoutSuffix,
830 )
831 }
832 case dto.MetricType_HISTOGRAM:
833 return fmt.Errorf(
834 "collected metric named %q collides with previously collected histogram named %q",
835 newName, newNameWithoutSuffix,
836 )
837 }
838 }
839 }
840 if newType == dto.MetricType_SUMMARY || newType == dto.MetricType_HISTOGRAM {
841 if _, ok := mfs[newName+"_count"]; ok {
842 return fmt.Errorf(
843 "collected histogram or summary named %q collides with previously collected metric named %q",
844 newName, newName+"_count",
845 )
846 }
847 if _, ok := mfs[newName+"_sum"]; ok {
848 return fmt.Errorf(
849 "collected histogram or summary named %q collides with previously collected metric named %q",
850 newName, newName+"_sum",
851 )
852 }
853 }
854 if newType == dto.MetricType_HISTOGRAM {
855 if _, ok := mfs[newName+"_bucket"]; ok {
856 return fmt.Errorf(
857 "collected histogram named %q collides with previously collected metric named %q",
858 newName, newName+"_bucket",
859 )
860 }
861 }
862 return nil
863 }
864
865 // checkMetricConsistency checks if the provided Metric is consistent with the
866 // provided MetricFamily. It also hashes the Metric labels and the MetricFamily
867 // name. If the resulting hash is already in the provided metricHashes, an error
868 // is returned. If not, it is added to metricHashes.
869 func checkMetricConsistency(
870 metricFamily *dto.MetricFamily,
871 dtoMetric *dto.Metric,
872 metricHashes map[uint64]struct{},
873 ) error {
874 name := metricFamily.GetName()
875
876 // Type consistency with metric family.
877 if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil ||
878 metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil ||
879 metricFamily.GetType() == dto.MetricType_SUMMARY && dtoMetric.Summary == nil ||
880 metricFamily.GetType() == dto.MetricType_HISTOGRAM && dtoMetric.Histogram == nil ||
881 metricFamily.GetType() == dto.MetricType_UNTYPED && dtoMetric.Untyped == nil {
882 return fmt.Errorf(
883 "collected metric %q { %s} is not a %s",
884 name, dtoMetric, metricFamily.GetType(),
885 )
886 }
887
888 previousLabelName := ""
889 for _, labelPair := range dtoMetric.GetLabel() {
890 labelName := labelPair.GetName()
891 if labelName == previousLabelName {
892 return fmt.Errorf(
893 "collected metric %q { %s} has two or more labels with the same name: %s",
894 name, dtoMetric, labelName,
895 )
896 }
897 if !checkLabelName(labelName) {
898 return fmt.Errorf(
899 "collected metric %q { %s} has a label with an invalid name: %s",
900 name, dtoMetric, labelName,
901 )
902 }
903 if dtoMetric.Summary != nil && labelName == quantileLabel {
904 return fmt.Errorf(
905 "collected metric %q { %s} must not have an explicit %q label",
906 name, dtoMetric, quantileLabel,
907 )
908 }
909 if !utf8.ValidString(labelPair.GetValue()) {
910 return fmt.Errorf(
911 "collected metric %q { %s} has a label named %q whose value is not utf8: %#v",
912 name, dtoMetric, labelName, labelPair.GetValue())
913 }
914 previousLabelName = labelName
915 }
916
917 // Is the metric unique (i.e. no other metric with the same name and the same labels)?
918 h := xxhash.New()
919 h.WriteString(name)
920 h.Write(separatorByteSlice)
921 // Make sure label pairs are sorted. We depend on it for the consistency
922 // check.
923 if !sort.IsSorted(internal.LabelPairSorter(dtoMetric.Label)) {
924 // We cannot sort dtoMetric.Label in place as it is immutable by contract.
925 copiedLabels := make([]*dto.LabelPair, len(dtoMetric.Label))
926 copy(copiedLabels, dtoMetric.Label)
927 sort.Sort(internal.LabelPairSorter(copiedLabels))
928 dtoMetric.Label = copiedLabels
929 }
930 for _, lp := range dtoMetric.Label {
931 h.WriteString(lp.GetName())
932 h.Write(separatorByteSlice)
933 h.WriteString(lp.GetValue())
934 h.Write(separatorByteSlice)
935 }
936 if dtoMetric.TimestampMs != nil {
937 h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10))
938 h.Write(separatorByteSlice)
939 }
940 hSum := h.Sum64()
941 if _, exists := metricHashes[hSum]; exists {
942 return fmt.Errorf(
943 "collected metric %q { %s} was collected before with the same name and label values",
944 name, dtoMetric,
945 )
946 }
947 metricHashes[hSum] = struct{}{}
948 return nil
949 }
950
951 func checkDescConsistency(
952 metricFamily *dto.MetricFamily,
953 dtoMetric *dto.Metric,
954 desc *Desc,
955 ) error {
956 // Desc help consistency with metric family help.
957 if metricFamily.GetHelp() != desc.help {
958 return fmt.Errorf(
959 "collected metric %s %s has help %q but should have %q",
960 metricFamily.GetName(), dtoMetric, metricFamily.GetHelp(), desc.help,
961 )
962 }
963
964 // Is the desc consistent with the content of the metric?
965 lpsFromDesc := make([]*dto.LabelPair, len(desc.constLabelPairs), len(dtoMetric.Label))
966 copy(lpsFromDesc, desc.constLabelPairs)
967 for _, l := range desc.variableLabels.names {
968 lpsFromDesc = append(lpsFromDesc, &dto.LabelPair{
969 Name: proto.String(l),
970 })
971 }
972 if len(lpsFromDesc) != len(dtoMetric.Label) {
973 return fmt.Errorf(
974 "labels in collected metric %s %s are inconsistent with descriptor %s",
975 metricFamily.GetName(), dtoMetric, desc,
976 )
977 }
978 sort.Sort(internal.LabelPairSorter(lpsFromDesc))
979 for i, lpFromDesc := range lpsFromDesc {
980 lpFromMetric := dtoMetric.Label[i]
981 if lpFromDesc.GetName() != lpFromMetric.GetName() ||
982 lpFromDesc.Value != nil && lpFromDesc.GetValue() != lpFromMetric.GetValue() {
983 return fmt.Errorf(
984 "labels in collected metric %s %s are inconsistent with descriptor %s",
985 metricFamily.GetName(), dtoMetric, desc,
986 )
987 }
988 }
989 return nil
990 }
991
992 var _ TransactionalGatherer = &MultiTRegistry{}
993
994 // MultiTRegistry is a TransactionalGatherer that joins gathered metrics from multiple
995 // transactional gatherers.
996 //
997 // It is caller responsibility to ensure two registries have mutually exclusive metric families,
998 // no deduplication will happen.
999 type MultiTRegistry struct {
1000 tGatherers []TransactionalGatherer
1001 }
1002
1003 // NewMultiTRegistry creates MultiTRegistry.
1004 func NewMultiTRegistry(tGatherers ...TransactionalGatherer) *MultiTRegistry {
1005 return &MultiTRegistry{
1006 tGatherers: tGatherers,
1007 }
1008 }
1009
1010 // Gather implements TransactionalGatherer interface.
1011 func (r *MultiTRegistry) Gather() (mfs []*dto.MetricFamily, done func(), err error) {
1012 errs := MultiError{}
1013
1014 dFns := make([]func(), 0, len(r.tGatherers))
1015 // TODO(bwplotka): Implement concurrency for those?
1016 for _, g := range r.tGatherers {
1017 // TODO(bwplotka): Check for duplicates?
1018 m, d, err := g.Gather()
1019 errs.Append(err)
1020
1021 mfs = append(mfs, m...)
1022 dFns = append(dFns, d)
1023 }
1024
1025 // TODO(bwplotka): Consider sort in place, given metric family in gather is sorted already.
1026 sort.Slice(mfs, func(i, j int) bool {
1027 return *mfs[i].Name < *mfs[j].Name
1028 })
1029 return mfs, func() {
1030 for _, d := range dFns {
1031 d()
1032 }
1033 }, errs.MaybeUnwrap()
1034 }
1035
1036 // TransactionalGatherer represents transactional gatherer that can be triggered to notify gatherer that memory
1037 // used by metric family is no longer used by a caller. This allows implementations with cache.
1038 type TransactionalGatherer interface {
1039 // Gather returns metrics in a lexicographically sorted slice
1040 // of uniquely named MetricFamily protobufs. Gather ensures that the
1041 // returned slice is valid and self-consistent so that it can be used
1042 // for valid exposition. As an exception to the strict consistency
1043 // requirements described for metric.Desc, Gather will tolerate
1044 // different sets of label names for metrics of the same metric family.
1045 //
1046 // Even if an error occurs, Gather attempts to gather as many metrics as
1047 // possible. Hence, if a non-nil error is returned, the returned
1048 // MetricFamily slice could be nil (in case of a fatal error that
1049 // prevented any meaningful metric collection) or contain a number of
1050 // MetricFamily protobufs, some of which might be incomplete, and some
1051 // might be missing altogether. The returned error (which might be a
1052 // MultiError) explains the details. Note that this is mostly useful for
1053 // debugging purposes. If the gathered protobufs are to be used for
1054 // exposition in actual monitoring, it is almost always better to not
1055 // expose an incomplete result and instead disregard the returned
1056 // MetricFamily protobufs in case the returned error is non-nil.
1057 //
1058 // Important: done is expected to be triggered (even if the error occurs!)
1059 // once caller does not need returned slice of dto.MetricFamily.
1060 Gather() (_ []*dto.MetricFamily, done func(), err error)
1061 }
1062
1063 // ToTransactionalGatherer transforms Gatherer to transactional one with noop as done function.
1064 func ToTransactionalGatherer(g Gatherer) TransactionalGatherer {
1065 return &noTransactionGatherer{g: g}
1066 }
1067
1068 type noTransactionGatherer struct {
1069 g Gatherer
1070 }
1071
1072 // Gather implements TransactionalGatherer interface.
1073 func (g *noTransactionGatherer) Gather() (_ []*dto.MetricFamily, done func(), err error) {
1074 mfs, err := g.g.Gather()
1075 return mfs, func() {}, err
1076 }