Debian Codegraph @

prometheus/go_collector_latest.go

raw
1 // Copyright 2021 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 //go:build go1.17
15 // +build go1.17
16
17 package prometheus
18
19 import (
20 "fmt"
21 "math"
22 "runtime"
23 "runtime/metrics"
24 "strings"
25 "sync"
26
27 "github.com/prometheus/client_golang/prometheus/internal"
28
29 dto "github.com/prometheus/client_model/go"
30 "google.golang.org/protobuf/proto"
31 )
32
33 const (
34 // constants for strings referenced more than once.
35 goGCHeapTinyAllocsObjects = "/gc/heap/tiny/allocs:objects"
36 goGCHeapAllocsObjects = "/gc/heap/allocs:objects"
37 goGCHeapFreesObjects = "/gc/heap/frees:objects"
38 goGCHeapFreesBytes = "/gc/heap/frees:bytes"
39 goGCHeapAllocsBytes = "/gc/heap/allocs:bytes"
40 goGCHeapObjects = "/gc/heap/objects:objects"
41 goGCHeapGoalBytes = "/gc/heap/goal:bytes"
42 goMemoryClassesTotalBytes = "/memory/classes/total:bytes"
43 goMemoryClassesHeapObjectsBytes = "/memory/classes/heap/objects:bytes"
44 goMemoryClassesHeapUnusedBytes = "/memory/classes/heap/unused:bytes"
45 goMemoryClassesHeapReleasedBytes = "/memory/classes/heap/released:bytes"
46 goMemoryClassesHeapFreeBytes = "/memory/classes/heap/free:bytes"
47 goMemoryClassesHeapStacksBytes = "/memory/classes/heap/stacks:bytes"
48 goMemoryClassesOSStacksBytes = "/memory/classes/os-stacks:bytes"
49 goMemoryClassesMetadataMSpanInuseBytes = "/memory/classes/metadata/mspan/inuse:bytes"
50 goMemoryClassesMetadataMSPanFreeBytes = "/memory/classes/metadata/mspan/free:bytes"
51 goMemoryClassesMetadataMCacheInuseBytes = "/memory/classes/metadata/mcache/inuse:bytes"
52 goMemoryClassesMetadataMCacheFreeBytes = "/memory/classes/metadata/mcache/free:bytes"
53 goMemoryClassesProfilingBucketsBytes = "/memory/classes/profiling/buckets:bytes"
54 goMemoryClassesMetadataOtherBytes = "/memory/classes/metadata/other:bytes"
55 goMemoryClassesOtherBytes = "/memory/classes/other:bytes"
56 )
57
58 // rmNamesForMemStatsMetrics represents runtime/metrics names required to populate goRuntimeMemStats from like logic.
59 var rmNamesForMemStatsMetrics = []string{
60 goGCHeapTinyAllocsObjects,
61 goGCHeapAllocsObjects,
62 goGCHeapFreesObjects,
63 goGCHeapAllocsBytes,
64 goGCHeapObjects,
65 goGCHeapGoalBytes,
66 goMemoryClassesTotalBytes,
67 goMemoryClassesHeapObjectsBytes,
68 goMemoryClassesHeapUnusedBytes,
69 goMemoryClassesHeapReleasedBytes,
70 goMemoryClassesHeapFreeBytes,
71 goMemoryClassesHeapStacksBytes,
72 goMemoryClassesOSStacksBytes,
73 goMemoryClassesMetadataMSpanInuseBytes,
74 goMemoryClassesMetadataMSPanFreeBytes,
75 goMemoryClassesMetadataMCacheInuseBytes,
76 goMemoryClassesMetadataMCacheFreeBytes,
77 goMemoryClassesProfilingBucketsBytes,
78 goMemoryClassesMetadataOtherBytes,
79 goMemoryClassesOtherBytes,
80 }
81
82 func bestEffortLookupRM(lookup []string) []metrics.Description {
83 ret := make([]metrics.Description, 0, len(lookup))
84 for _, rm := range metrics.All() {
85 for _, m := range lookup {
86 if m == rm.Name {
87 ret = append(ret, rm)
88 }
89 }
90 }
91 return ret
92 }
93
94 type goCollector struct {
95 base baseGoCollector
96
97 // mu protects updates to all fields ensuring a consistent
98 // snapshot is always produced by Collect.
99 mu sync.Mutex
100
101 // Contains all samples that has to retrieved from runtime/metrics (not all of them will be exposed).
102 sampleBuf []metrics.Sample
103 // sampleMap allows lookup for MemStats metrics and runtime/metrics histograms for exact sums.
104 sampleMap map[string]*metrics.Sample
105
106 // rmExposedMetrics represents all runtime/metrics package metrics
107 // that were configured to be exposed.
108 rmExposedMetrics []collectorMetric
109 rmExactSumMapForHist map[string]string
110
111 // With Go 1.17, the runtime/metrics package was introduced.
112 // From that point on, metric names produced by the runtime/metrics
113 // package could be generated from runtime/metrics names. However,
114 // these differ from the old names for the same values.
115 //
116 // This field exists to export the same values under the old names
117 // as well.
118 msMetrics memStatsMetrics
119 msMetricsEnabled bool
120 }
121
122 type rmMetricDesc struct {
123 metrics.Description
124 }
125
126 func matchRuntimeMetricsRules(rules []internal.GoCollectorRule) []rmMetricDesc {
127 var descs []rmMetricDesc
128 for _, d := range metrics.All() {
129 var (
130 deny = true
131 desc rmMetricDesc
132 )
133
134 for _, r := range rules {
135 if !r.Matcher.MatchString(d.Name) {
136 continue
137 }
138 deny = r.Deny
139 }
140 if deny {
141 continue
142 }
143
144 desc.Description = d
145 descs = append(descs, desc)
146 }
147 return descs
148 }
149
150 func defaultGoCollectorOptions() internal.GoCollectorOptions {
151 return internal.GoCollectorOptions{
152 RuntimeMetricSumForHist: map[string]string{
153 "/gc/heap/allocs-by-size:bytes": goGCHeapAllocsBytes,
154 "/gc/heap/frees-by-size:bytes": goGCHeapFreesBytes,
155 },
156 RuntimeMetricRules: []internal.GoCollectorRule{
157 // Recommended metrics we want by default from runtime/metrics.
158 {Matcher: internal.GoCollectorDefaultRuntimeMetrics},
159 },
160 }
161 }
162
163 // NewGoCollector is the obsolete version of collectors.NewGoCollector.
164 // See there for documentation.
165 //
166 // Deprecated: Use collectors.NewGoCollector instead.
167 func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
168 opt := defaultGoCollectorOptions()
169 for _, o := range opts {
170 o(&opt)
171 }
172
173 exposedDescriptions := matchRuntimeMetricsRules(opt.RuntimeMetricRules)
174
175 // Collect all histogram samples so that we can get their buckets.
176 // The API guarantees that the buckets are always fixed for the lifetime
177 // of the process.
178 var histograms []metrics.Sample
179 for _, d := range exposedDescriptions {
180 if d.Kind == metrics.KindFloat64Histogram {
181 histograms = append(histograms, metrics.Sample{Name: d.Name})
182 }
183 }
184
185 if len(histograms) > 0 {
186 metrics.Read(histograms)
187 }
188
189 bucketsMap := make(map[string][]float64)
190 for i := range histograms {
191 bucketsMap[histograms[i].Name] = histograms[i].Value.Float64Histogram().Buckets
192 }
193
194 // Generate a collector for each exposed runtime/metrics metric.
195 metricSet := make([]collectorMetric, 0, len(exposedDescriptions))
196 // SampleBuf is used for reading from runtime/metrics.
197 // We are assuming the largest case to have stable pointers for sampleMap purposes.
198 sampleBuf := make([]metrics.Sample, 0, len(exposedDescriptions)+len(opt.RuntimeMetricSumForHist)+len(rmNamesForMemStatsMetrics))
199 sampleMap := make(map[string]*metrics.Sample, len(exposedDescriptions))
200 for _, d := range exposedDescriptions {
201 namespace, subsystem, name, ok := internal.RuntimeMetricsToProm(&d.Description)
202 if !ok {
203 // Just ignore this metric; we can't do anything with it here.
204 // If a user decides to use the latest version of Go, we don't want
205 // to fail here. This condition is tested in TestExpectedRuntimeMetrics.
206 continue
207 }
208 help := attachOriginalName(d.Description.Description, d.Name)
209
210 sampleBuf = append(sampleBuf, metrics.Sample{Name: d.Name})
211 sampleMap[d.Name] = &sampleBuf[len(sampleBuf)-1]
212
213 var m collectorMetric
214 if d.Kind == metrics.KindFloat64Histogram {
215 _, hasSum := opt.RuntimeMetricSumForHist[d.Name]
216 unit := d.Name[strings.IndexRune(d.Name, ':')+1:]
217 m = newBatchHistogram(
218 NewDesc(
219 BuildFQName(namespace, subsystem, name),
220 help,
221 nil,
222 nil,
223 ),
224 internal.RuntimeMetricsBucketsForUnit(bucketsMap[d.Name], unit),
225 hasSum,
226 )
227 } else if d.Cumulative {
228 m = NewCounter(CounterOpts{
229 Namespace: namespace,
230 Subsystem: subsystem,
231 Name: name,
232 Help: help,
233 },
234 )
235 } else {
236 m = NewGauge(GaugeOpts{
237 Namespace: namespace,
238 Subsystem: subsystem,
239 Name: name,
240 Help: help,
241 })
242 }
243 metricSet = append(metricSet, m)
244 }
245
246 // Add exact sum metrics to sampleBuf if not added before.
247 for _, h := range histograms {
248 sumMetric, ok := opt.RuntimeMetricSumForHist[h.Name]
249 if !ok {
250 continue
251 }
252
253 if _, ok := sampleMap[sumMetric]; ok {
254 continue
255 }
256 sampleBuf = append(sampleBuf, metrics.Sample{Name: sumMetric})
257 sampleMap[sumMetric] = &sampleBuf[len(sampleBuf)-1]
258 }
259
260 var (
261 msMetrics memStatsMetrics
262 msDescriptions []metrics.Description
263 )
264
265 if !opt.DisableMemStatsLikeMetrics {
266 msMetrics = goRuntimeMemStats()
267 msDescriptions = bestEffortLookupRM(rmNamesForMemStatsMetrics)
268
269 // Check if metric was not exposed before and if not, add to sampleBuf.
270 for _, mdDesc := range msDescriptions {
271 if _, ok := sampleMap[mdDesc.Name]; ok {
272 continue
273 }
274 sampleBuf = append(sampleBuf, metrics.Sample{Name: mdDesc.Name})
275 sampleMap[mdDesc.Name] = &sampleBuf[len(sampleBuf)-1]
276 }
277 }
278
279 return &goCollector{
280 base: newBaseGoCollector(),
281 sampleBuf: sampleBuf,
282 sampleMap: sampleMap,
283 rmExposedMetrics: metricSet,
284 rmExactSumMapForHist: opt.RuntimeMetricSumForHist,
285 msMetrics: msMetrics,
286 msMetricsEnabled: !opt.DisableMemStatsLikeMetrics,
287 }
288 }
289
290 func attachOriginalName(desc, origName string) string {
291 return fmt.Sprintf("%s Sourced from %s.", desc, origName)
292 }
293
294 // Describe returns all descriptions of the collector.
295 func (c *goCollector) Describe(ch chan<- *Desc) {
296 c.base.Describe(ch)
297 for _, i := range c.msMetrics {
298 ch <- i.desc
299 }
300 for _, m := range c.rmExposedMetrics {
301 ch <- m.Desc()
302 }
303 }
304
305 // Collect returns the current state of all metrics of the collector.
306 func (c *goCollector) Collect(ch chan<- Metric) {
307 // Collect base non-memory metrics.
308 c.base.Collect(ch)
309
310 if len(c.sampleBuf) == 0 {
311 return
312 }
313
314 // Collect must be thread-safe, so prevent concurrent use of
315 // sampleBuf elements. Just read into sampleBuf but write all the data
316 // we get into our Metrics or MemStats.
317 //
318 // This lock also ensures that the Metrics we send out are all from
319 // the same updates, ensuring their mutual consistency insofar as
320 // is guaranteed by the runtime/metrics package.
321 //
322 // N.B. This locking is heavy-handed, but Collect is expected to be called
323 // relatively infrequently. Also the core operation here, metrics.Read,
324 // is fast (O(tens of microseconds)) so contention should certainly be
325 // low, though channel operations and any allocations may add to that.
326 c.mu.Lock()
327 defer c.mu.Unlock()
328
329 // Populate runtime/metrics sample buffer.
330 metrics.Read(c.sampleBuf)
331
332 // Collect all our runtime/metrics user chose to expose from sampleBuf (if any).
333 for i, metric := range c.rmExposedMetrics {
334 // We created samples for exposed metrics first in order, so indexes match.
335 sample := c.sampleBuf[i]
336
337 // N.B. switch on concrete type because it's significantly more efficient
338 // than checking for the Counter and Gauge interface implementations. In
339 // this case, we control all the types here.
340 switch m := metric.(type) {
341 case *counter:
342 // Guard against decreases. This should never happen, but a failure
343 // to do so will result in a panic, which is a harsh consequence for
344 // a metrics collection bug.
345 v0, v1 := m.get(), unwrapScalarRMValue(sample.Value)
346 if v1 > v0 {
347 m.Add(unwrapScalarRMValue(sample.Value) - m.get())
348 }
349 m.Collect(ch)
350 case *gauge:
351 m.Set(unwrapScalarRMValue(sample.Value))
352 m.Collect(ch)
353 case *batchHistogram:
354 m.update(sample.Value.Float64Histogram(), c.exactSumFor(sample.Name))
355 m.Collect(ch)
356 default:
357 panic("unexpected metric type")
358 }
359 }
360
361 if c.msMetricsEnabled {
362 // ms is a dummy MemStats that we populate ourselves so that we can
363 // populate the old metrics from it if goMemStatsCollection is enabled.
364 var ms runtime.MemStats
365 memStatsFromRM(&ms, c.sampleMap)
366 for _, i := range c.msMetrics {
367 ch <- MustNewConstMetric(i.desc, i.valType, i.eval(&ms))
368 }
369 }
370 }
371
372 // unwrapScalarRMValue unwraps a runtime/metrics value that is assumed
373 // to be scalar and returns the equivalent float64 value. Panics if the
374 // value is not scalar.
375 func unwrapScalarRMValue(v metrics.Value) float64 {
376 switch v.Kind() {
377 case metrics.KindUint64:
378 return float64(v.Uint64())
379 case metrics.KindFloat64:
380 return v.Float64()
381 case metrics.KindBad:
382 // Unsupported metric.
383 //
384 // This should never happen because we always populate our metric
385 // set from the runtime/metrics package.
386 panic("unexpected bad kind metric")
387 default:
388 // Unsupported metric kind.
389 //
390 // This should never happen because we check for this during initialization
391 // and flag and filter metrics whose kinds we don't understand.
392 panic(fmt.Sprintf("unexpected unsupported metric: %v", v.Kind()))
393 }
394 }
395
396 // exactSumFor takes a runtime/metrics metric name (that is assumed to
397 // be of kind KindFloat64Histogram) and returns its exact sum and whether
398 // its exact sum exists.
399 //
400 // The runtime/metrics API for histograms doesn't currently expose exact
401 // sums, but some of the other metrics are in fact exact sums of histograms.
402 func (c *goCollector) exactSumFor(rmName string) float64 {
403 sumName, ok := c.rmExactSumMapForHist[rmName]
404 if !ok {
405 return 0
406 }
407 s, ok := c.sampleMap[sumName]
408 if !ok {
409 return 0
410 }
411 return unwrapScalarRMValue(s.Value)
412 }
413
414 func memStatsFromRM(ms *runtime.MemStats, rm map[string]*metrics.Sample) {
415 lookupOrZero := func(name string) uint64 {
416 if s, ok := rm[name]; ok {
417 return s.Value.Uint64()
418 }
419 return 0
420 }
421
422 // Currently, MemStats adds tiny alloc count to both Mallocs AND Frees.
423 // The reason for this is because MemStats couldn't be extended at the time
424 // but there was a desire to have Mallocs at least be a little more representative,
425 // while having Mallocs - Frees still represent a live object count.
426 // Unfortunately, MemStats doesn't actually export a large allocation count,
427 // so it's impossible to pull this number out directly.
428 tinyAllocs := lookupOrZero(goGCHeapTinyAllocsObjects)
429 ms.Mallocs = lookupOrZero(goGCHeapAllocsObjects) + tinyAllocs
430 ms.Frees = lookupOrZero(goGCHeapFreesObjects) + tinyAllocs
431
432 ms.TotalAlloc = lookupOrZero(goGCHeapAllocsBytes)
433 ms.Sys = lookupOrZero(goMemoryClassesTotalBytes)
434 ms.Lookups = 0 // Already always zero.
435 ms.HeapAlloc = lookupOrZero(goMemoryClassesHeapObjectsBytes)
436 ms.Alloc = ms.HeapAlloc
437 ms.HeapInuse = ms.HeapAlloc + lookupOrZero(goMemoryClassesHeapUnusedBytes)
438 ms.HeapReleased = lookupOrZero(goMemoryClassesHeapReleasedBytes)
439 ms.HeapIdle = ms.HeapReleased + lookupOrZero(goMemoryClassesHeapFreeBytes)
440 ms.HeapSys = ms.HeapInuse + ms.HeapIdle
441 ms.HeapObjects = lookupOrZero(goGCHeapObjects)
442 ms.StackInuse = lookupOrZero(goMemoryClassesHeapStacksBytes)
443 ms.StackSys = ms.StackInuse + lookupOrZero(goMemoryClassesOSStacksBytes)
444 ms.MSpanInuse = lookupOrZero(goMemoryClassesMetadataMSpanInuseBytes)
445 ms.MSpanSys = ms.MSpanInuse + lookupOrZero(goMemoryClassesMetadataMSPanFreeBytes)
446 ms.MCacheInuse = lookupOrZero(goMemoryClassesMetadataMCacheInuseBytes)
447 ms.MCacheSys = ms.MCacheInuse + lookupOrZero(goMemoryClassesMetadataMCacheFreeBytes)
448 ms.BuckHashSys = lookupOrZero(goMemoryClassesProfilingBucketsBytes)
449 ms.GCSys = lookupOrZero(goMemoryClassesMetadataOtherBytes)
450 ms.OtherSys = lookupOrZero(goMemoryClassesOtherBytes)
451 ms.NextGC = lookupOrZero(goGCHeapGoalBytes)
452
453 // N.B. GCCPUFraction is intentionally omitted. This metric is not useful,
454 // and often misleading due to the fact that it's an average over the lifetime
455 // of the process.
456 // See https://github.com/prometheus/client_golang/issues/842#issuecomment-861812034
457 // for more details.
458 ms.GCCPUFraction = 0
459 }
460
461 // batchHistogram is a mutable histogram that is updated
462 // in batches.
463 type batchHistogram struct {
464 selfCollector
465
466 // Static fields updated only once.
467 desc *Desc
468 hasSum bool
469
470 // Because this histogram operates in batches, it just uses a
471 // single mutex for everything. updates are always serialized
472 // but Write calls may operate concurrently with updates.
473 // Contention between these two sources should be rare.
474 mu sync.Mutex
475 buckets []float64 // Inclusive lower bounds, like runtime/metrics.
476 counts []uint64
477 sum float64 // Used if hasSum is true.
478 }
479
480 // newBatchHistogram creates a new batch histogram value with the given
481 // Desc, buckets, and whether or not it has an exact sum available.
482 //
483 // buckets must always be from the runtime/metrics package, following
484 // the same conventions.
485 func newBatchHistogram(desc *Desc, buckets []float64, hasSum bool) *batchHistogram {
486 // We need to remove -Inf values. runtime/metrics keeps them around.
487 // But -Inf bucket should not be allowed for prometheus histograms.
488 if buckets[0] == math.Inf(-1) {
489 buckets = buckets[1:]
490 }
491 h := &batchHistogram{
492 desc: desc,
493 buckets: buckets,
494 // Because buckets follows runtime/metrics conventions, there's
495 // 1 more value in the buckets list than there are buckets represented,
496 // because in runtime/metrics, the bucket values represent *boundaries*,
497 // and non-Inf boundaries are inclusive lower bounds for that bucket.
498 counts: make([]uint64, len(buckets)-1),
499 hasSum: hasSum,
500 }
501 h.init(h)
502 return h
503 }
504
505 // update updates the batchHistogram from a runtime/metrics histogram.
506 //
507 // sum must be provided if the batchHistogram was created to have an exact sum.
508 // h.buckets must be a strict subset of his.Buckets.
509 func (h *batchHistogram) update(his *metrics.Float64Histogram, sum float64) {
510 counts, buckets := his.Counts, his.Buckets
511
512 h.mu.Lock()
513 defer h.mu.Unlock()
514
515 // Clear buckets.
516 for i := range h.counts {
517 h.counts[i] = 0
518 }
519 // Copy and reduce buckets.
520 var j int
521 for i, count := range counts {
522 h.counts[j] += count
523 if buckets[i+1] == h.buckets[j+1] {
524 j++
525 }
526 }
527 if h.hasSum {
528 h.sum = sum
529 }
530 }
531
532 func (h *batchHistogram) Desc() *Desc {
533 return h.desc
534 }
535
536 func (h *batchHistogram) Write(out *dto.Metric) error {
537 h.mu.Lock()
538 defer h.mu.Unlock()
539
540 sum := float64(0)
541 if h.hasSum {
542 sum = h.sum
543 }
544 dtoBuckets := make([]*dto.Bucket, 0, len(h.counts))
545 totalCount := uint64(0)
546 for i, count := range h.counts {
547 totalCount += count
548 if !h.hasSum {
549 if count != 0 {
550 // N.B. This computed sum is an underestimate.
551 sum += h.buckets[i] * float64(count)
552 }
553 }
554
555 // Skip the +Inf bucket, but only for the bucket list.
556 // It must still count for sum and totalCount.
557 if math.IsInf(h.buckets[i+1], 1) {
558 break
559 }
560 // Float64Histogram's upper bound is exclusive, so make it inclusive
561 // by obtaining the next float64 value down, in order.
562 upperBound := math.Nextafter(h.buckets[i+1], h.buckets[i])
563 dtoBuckets = append(dtoBuckets, &dto.Bucket{
564 CumulativeCount: proto.Uint64(totalCount),
565 UpperBound: proto.Float64(upperBound),
566 })
567 }
568 out.Histogram = &dto.Histogram{
569 Bucket: dtoBuckets,
570 SampleCount: proto.Uint64(totalCount),
571 SampleSum: proto.Float64(sum),
572 }
573 return nil
574 }