Debian Codegraph @

prometheus/summary.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 "fmt"
18 "math"
19 "runtime"
20 "sort"
21 "sync"
22 "sync/atomic"
23 "time"
24
25 dto "github.com/prometheus/client_model/go"
26
27 "github.com/beorn7/perks/quantile"
28 "google.golang.org/protobuf/proto"
29 "google.golang.org/protobuf/types/known/timestamppb"
30 )
31
32 // quantileLabel is used for the label that defines the quantile in a
33 // summary.
34 const quantileLabel = "quantile"
35
36 // A Summary captures individual observations from an event or sample stream and
37 // summarizes them in a manner similar to traditional summary statistics: 1. sum
38 // of observations, 2. observation count, 3. rank estimations.
39 //
40 // A typical use-case is the observation of request latencies. By default, a
41 // Summary provides the median, the 90th and the 99th percentile of the latency
42 // as rank estimations. However, the default behavior will change in the
43 // upcoming v1.0.0 of the library. There will be no rank estimations at all by
44 // default. For a sane transition, it is recommended to set the desired rank
45 // estimations explicitly.
46 //
47 // Note that the rank estimations cannot be aggregated in a meaningful way with
48 // the Prometheus query language (i.e. you cannot average or add them). If you
49 // need aggregatable quantiles (e.g. you want the 99th percentile latency of all
50 // queries served across all instances of a service), consider the Histogram
51 // metric type. See the Prometheus documentation for more details.
52 //
53 // To create Summary instances, use NewSummary.
54 type Summary interface {
55 Metric
56 Collector
57
58 // Observe adds a single observation to the summary. Observations are
59 // usually positive or zero. Negative observations are accepted but
60 // prevent current versions of Prometheus from properly detecting
61 // counter resets in the sum of observations. See
62 // https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations
63 // for details.
64 Observe(float64)
65 }
66
67 var errQuantileLabelNotAllowed = fmt.Errorf(
68 "%q is not allowed as label name in summaries", quantileLabel,
69 )
70
71 // Default values for SummaryOpts.
72 const (
73 // DefMaxAge is the default duration for which observations stay
74 // relevant.
75 DefMaxAge time.Duration = 10 * time.Minute
76 // DefAgeBuckets is the default number of buckets used to calculate the
77 // age of observations.
78 DefAgeBuckets = 5
79 // DefBufCap is the standard buffer size for collecting Summary observations.
80 DefBufCap = 500
81 )
82
83 // SummaryOpts bundles the options for creating a Summary metric. It is
84 // mandatory to set Name to a non-empty string. While all other fields are
85 // optional and can safely be left at their zero value, it is recommended to set
86 // a help string and to explicitly set the Objectives field to the desired value
87 // as the default value will change in the upcoming v1.0.0 of the library.
88 type SummaryOpts struct {
89 // Namespace, Subsystem, and Name are components of the fully-qualified
90 // name of the Summary (created by joining these components with
91 // "_"). Only Name is mandatory, the others merely help structuring the
92 // name. Note that the fully-qualified name of the Summary must be a
93 // valid Prometheus metric name.
94 Namespace string
95 Subsystem string
96 Name string
97
98 // Help provides information about this Summary.
99 //
100 // Metrics with the same fully-qualified name must have the same Help
101 // string.
102 Help string
103
104 // ConstLabels are used to attach fixed labels to this metric. Metrics
105 // with the same fully-qualified name must have the same label names in
106 // their ConstLabels.
107 //
108 // Due to the way a Summary is represented in the Prometheus text format
109 // and how it is handled by the Prometheus server internally, “quantile”
110 // is an illegal label name. Construction of a Summary or SummaryVec
111 // will panic if this label name is used in ConstLabels.
112 //
113 // ConstLabels are only used rarely. In particular, do not use them to
114 // attach the same labels to all your metrics. Those use cases are
115 // better covered by target labels set by the scraping Prometheus
116 // server, or by one specific metric (e.g. a build_info or a
117 // machine_role metric). See also
118 // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
119 ConstLabels Labels
120
121 // Objectives defines the quantile rank estimates with their respective
122 // absolute error. If Objectives[q] = e, then the value reported for q
123 // will be the φ-quantile value for some φ between q-e and q+e. The
124 // default value is an empty map, resulting in a summary without
125 // quantiles.
126 Objectives map[float64]float64
127
128 // MaxAge defines the duration for which an observation stays relevant
129 // for the summary. Only applies to pre-calculated quantiles, does not
130 // apply to _sum and _count. Must be positive. The default value is
131 // DefMaxAge.
132 MaxAge time.Duration
133
134 // AgeBuckets is the number of buckets used to exclude observations that
135 // are older than MaxAge from the summary. A higher number has a
136 // resource penalty, so only increase it if the higher resolution is
137 // really required. For very high observation rates, you might want to
138 // reduce the number of age buckets. With only one age bucket, you will
139 // effectively see a complete reset of the summary each time MaxAge has
140 // passed. The default value is DefAgeBuckets.
141 AgeBuckets uint32
142
143 // BufCap defines the default sample stream buffer size. The default
144 // value of DefBufCap should suffice for most uses. If there is a need
145 // to increase the value, a multiple of 500 is recommended (because that
146 // is the internal buffer size of the underlying package
147 // "github.com/bmizerany/perks/quantile").
148 BufCap uint32
149
150 // now is for testing purposes, by default it's time.Now.
151 now func() time.Time
152 }
153
154 // SummaryVecOpts bundles the options to create a SummaryVec metric.
155 // It is mandatory to set SummaryOpts, see there for mandatory fields. VariableLabels
156 // is optional and can safely be left to its default value.
157 type SummaryVecOpts struct {
158 SummaryOpts
159
160 // VariableLabels are used to partition the metric vector by the given set
161 // of labels. Each label value will be constrained with the optional Constraint
162 // function, if provided.
163 VariableLabels ConstrainableLabels
164 }
165
166 // Problem with the sliding-window decay algorithm... The Merge method of
167 // perk/quantile is actually not working as advertised - and it might be
168 // unfixable, as the underlying algorithm is apparently not capable of merging
169 // summaries in the first place. To avoid using Merge, we are currently adding
170 // observations to _each_ age bucket, i.e. the effort to add a sample is
171 // essentially multiplied by the number of age buckets. When rotating age
172 // buckets, we empty the previous head stream. On scrape time, we simply take
173 // the quantiles from the head stream (no merging required). Result: More effort
174 // on observation time, less effort on scrape time, which is exactly the
175 // opposite of what we try to accomplish, but at least the results are correct.
176 //
177 // The quite elegant previous contraption to merge the age buckets efficiently
178 // on scrape time (see code up commit 6b9530d72ea715f0ba612c0120e6e09fbf1d49d0)
179 // can't be used anymore.
180
181 // NewSummary creates a new Summary based on the provided SummaryOpts.
182 func NewSummary(opts SummaryOpts) Summary {
183 return newSummary(
184 NewDesc(
185 BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
186 opts.Help,
187 nil,
188 opts.ConstLabels,
189 ),
190 opts,
191 )
192 }
193
194 func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
195 if len(desc.variableLabels.names) != len(labelValues) {
196 panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, labelValues))
197 }
198
199 for _, n := range desc.variableLabels.names {
200 if n == quantileLabel {
201 panic(errQuantileLabelNotAllowed)
202 }
203 }
204 for _, lp := range desc.constLabelPairs {
205 if lp.GetName() == quantileLabel {
206 panic(errQuantileLabelNotAllowed)
207 }
208 }
209
210 if opts.Objectives == nil {
211 opts.Objectives = map[float64]float64{}
212 }
213
214 if opts.MaxAge < 0 {
215 panic(fmt.Errorf("illegal max age MaxAge=%v", opts.MaxAge))
216 }
217 if opts.MaxAge == 0 {
218 opts.MaxAge = DefMaxAge
219 }
220
221 if opts.AgeBuckets == 0 {
222 opts.AgeBuckets = DefAgeBuckets
223 }
224
225 if opts.BufCap == 0 {
226 opts.BufCap = DefBufCap
227 }
228
229 if opts.now == nil {
230 opts.now = time.Now
231 }
232 if len(opts.Objectives) == 0 {
233 // Use the lock-free implementation of a Summary without objectives.
234 s := &noObjectivesSummary{
235 desc: desc,
236 labelPairs: MakeLabelPairs(desc, labelValues),
237 counts: [2]*summaryCounts{{}, {}},
238 }
239 s.init(s) // Init self-collection.
240 s.createdTs = timestamppb.New(opts.now())
241 return s
242 }
243
244 s := &summary{
245 desc: desc,
246 now: opts.now,
247
248 objectives: opts.Objectives,
249 sortedObjectives: make([]float64, 0, len(opts.Objectives)),
250
251 labelPairs: MakeLabelPairs(desc, labelValues),
252
253 hotBuf: make([]float64, 0, opts.BufCap),
254 coldBuf: make([]float64, 0, opts.BufCap),
255 streamDuration: opts.MaxAge / time.Duration(opts.AgeBuckets),
256 }
257 s.headStreamExpTime = opts.now().Add(s.streamDuration)
258 s.hotBufExpTime = s.headStreamExpTime
259
260 for i := uint32(0); i < opts.AgeBuckets; i++ {
261 s.streams = append(s.streams, s.newStream())
262 }
263 s.headStream = s.streams[0]
264
265 for qu := range s.objectives {
266 s.sortedObjectives = append(s.sortedObjectives, qu)
267 }
268 sort.Float64s(s.sortedObjectives)
269
270 s.init(s) // Init self-collection.
271 s.createdTs = timestamppb.New(opts.now())
272 return s
273 }
274
275 type summary struct {
276 selfCollector
277
278 bufMtx sync.Mutex // Protects hotBuf and hotBufExpTime.
279 mtx sync.Mutex // Protects every other moving part.
280 // Lock bufMtx before mtx if both are needed.
281
282 desc *Desc
283
284 now func() time.Time
285
286 objectives map[float64]float64
287 sortedObjectives []float64
288
289 labelPairs []*dto.LabelPair
290
291 sum float64
292 cnt uint64
293
294 hotBuf, coldBuf []float64
295
296 streams []*quantile.Stream
297 streamDuration time.Duration
298 headStream *quantile.Stream
299 headStreamIdx int
300 headStreamExpTime, hotBufExpTime time.Time
301
302 createdTs *timestamppb.Timestamp
303 }
304
305 func (s *summary) Desc() *Desc {
306 return s.desc
307 }
308
309 func (s *summary) Observe(v float64) {
310 s.bufMtx.Lock()
311 defer s.bufMtx.Unlock()
312
313 now := s.now()
314 if now.After(s.hotBufExpTime) {
315 s.asyncFlush(now)
316 }
317 s.hotBuf = append(s.hotBuf, v)
318 if len(s.hotBuf) == cap(s.hotBuf) {
319 s.asyncFlush(now)
320 }
321 }
322
323 func (s *summary) Write(out *dto.Metric) error {
324 sum := &dto.Summary{
325 CreatedTimestamp: s.createdTs,
326 }
327 qs := make([]*dto.Quantile, 0, len(s.objectives))
328
329 s.bufMtx.Lock()
330 s.mtx.Lock()
331 // Swap bufs even if hotBuf is empty to set new hotBufExpTime.
332 s.swapBufs(s.now())
333 s.bufMtx.Unlock()
334
335 s.flushColdBuf()
336 sum.SampleCount = proto.Uint64(s.cnt)
337 sum.SampleSum = proto.Float64(s.sum)
338
339 for _, rank := range s.sortedObjectives {
340 var q float64
341 if s.headStream.Count() == 0 {
342 q = math.NaN()
343 } else {
344 q = s.headStream.Query(rank)
345 }
346 qs = append(qs, &dto.Quantile{
347 Quantile: proto.Float64(rank),
348 Value: proto.Float64(q),
349 })
350 }
351
352 s.mtx.Unlock()
353
354 if len(qs) > 0 {
355 sort.Sort(quantSort(qs))
356 }
357 sum.Quantile = qs
358
359 out.Summary = sum
360 out.Label = s.labelPairs
361 return nil
362 }
363
364 func (s *summary) newStream() *quantile.Stream {
365 return quantile.NewTargeted(s.objectives)
366 }
367
368 // asyncFlush needs bufMtx locked.
369 func (s *summary) asyncFlush(now time.Time) {
370 s.mtx.Lock()
371 s.swapBufs(now)
372
373 // Unblock the original goroutine that was responsible for the mutation
374 // that triggered the compaction. But hold onto the global non-buffer
375 // state mutex until the operation finishes.
376 go func() {
377 s.flushColdBuf()
378 s.mtx.Unlock()
379 }()
380 }
381
382 // rotateStreams needs mtx AND bufMtx locked.
383 func (s *summary) maybeRotateStreams() {
384 for !s.hotBufExpTime.Equal(s.headStreamExpTime) {
385 s.headStream.Reset()
386 s.headStreamIdx++
387 if s.headStreamIdx >= len(s.streams) {
388 s.headStreamIdx = 0
389 }
390 s.headStream = s.streams[s.headStreamIdx]
391 s.headStreamExpTime = s.headStreamExpTime.Add(s.streamDuration)
392 }
393 }
394
395 // flushColdBuf needs mtx locked.
396 func (s *summary) flushColdBuf() {
397 for _, v := range s.coldBuf {
398 for _, stream := range s.streams {
399 stream.Insert(v)
400 }
401 s.cnt++
402 s.sum += v
403 }
404 s.coldBuf = s.coldBuf[0:0]
405 s.maybeRotateStreams()
406 }
407
408 // swapBufs needs mtx AND bufMtx locked, coldBuf must be empty.
409 func (s *summary) swapBufs(now time.Time) {
410 if len(s.coldBuf) != 0 {
411 panic("coldBuf is not empty")
412 }
413 s.hotBuf, s.coldBuf = s.coldBuf, s.hotBuf
414 // hotBuf is now empty and gets new expiration set.
415 for now.After(s.hotBufExpTime) {
416 s.hotBufExpTime = s.hotBufExpTime.Add(s.streamDuration)
417 }
418 }
419
420 type summaryCounts struct {
421 // sumBits contains the bits of the float64 representing the sum of all
422 // observations. sumBits and count have to go first in the struct to
423 // guarantee alignment for atomic operations.
424 // http://golang.org/pkg/sync/atomic/#pkg-note-BUG
425 sumBits uint64
426 count uint64
427 }
428
429 type noObjectivesSummary struct {
430 // countAndHotIdx enables lock-free writes with use of atomic updates.
431 // The most significant bit is the hot index [0 or 1] of the count field
432 // below. Observe calls update the hot one. All remaining bits count the
433 // number of Observe calls. Observe starts by incrementing this counter,
434 // and finish by incrementing the count field in the respective
435 // summaryCounts, as a marker for completion.
436 //
437 // Calls of the Write method (which are non-mutating reads from the
438 // perspective of the summary) swap the hot–cold under the writeMtx
439 // lock. A cooldown is awaited (while locked) by comparing the number of
440 // observations with the initiation count. Once they match, then the
441 // last observation on the now cool one has completed. All cool fields must
442 // be merged into the new hot before releasing writeMtx.
443
444 // Fields with atomic access first! See alignment constraint:
445 // http://golang.org/pkg/sync/atomic/#pkg-note-BUG
446 countAndHotIdx uint64
447
448 selfCollector
449 desc *Desc
450 writeMtx sync.Mutex // Only used in the Write method.
451
452 // Two counts, one is "hot" for lock-free observations, the other is
453 // "cold" for writing out a dto.Metric. It has to be an array of
454 // pointers to guarantee 64bit alignment of the histogramCounts, see
455 // http://golang.org/pkg/sync/atomic/#pkg-note-BUG.
456 counts [2]*summaryCounts
457
458 labelPairs []*dto.LabelPair
459
460 createdTs *timestamppb.Timestamp
461 }
462
463 func (s *noObjectivesSummary) Desc() *Desc {
464 return s.desc
465 }
466
467 func (s *noObjectivesSummary) Observe(v float64) {
468 // We increment h.countAndHotIdx so that the counter in the lower
469 // 63 bits gets incremented. At the same time, we get the new value
470 // back, which we can use to find the currently-hot counts.
471 n := atomic.AddUint64(&s.countAndHotIdx, 1)
472 hotCounts := s.counts[n>>63]
473
474 for {
475 oldBits := atomic.LoadUint64(&hotCounts.sumBits)
476 newBits := math.Float64bits(math.Float64frombits(oldBits) + v)
477 if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) {
478 break
479 }
480 }
481 // Increment count last as we take it as a signal that the observation
482 // is complete.
483 atomic.AddUint64(&hotCounts.count, 1)
484 }
485
486 func (s *noObjectivesSummary) Write(out *dto.Metric) error {
487 // For simplicity, we protect this whole method by a mutex. It is not in
488 // the hot path, i.e. Observe is called much more often than Write. The
489 // complication of making Write lock-free isn't worth it, if possible at
490 // all.
491 s.writeMtx.Lock()
492 defer s.writeMtx.Unlock()
493
494 // Adding 1<<63 switches the hot index (from 0 to 1 or from 1 to 0)
495 // without touching the count bits. See the struct comments for a full
496 // description of the algorithm.
497 n := atomic.AddUint64(&s.countAndHotIdx, 1<<63)
498 // count is contained unchanged in the lower 63 bits.
499 count := n & ((1 << 63) - 1)
500 // The most significant bit tells us which counts is hot. The complement
501 // is thus the cold one.
502 hotCounts := s.counts[n>>63]
503 coldCounts := s.counts[(^n)>>63]
504
505 // Await cooldown.
506 for count != atomic.LoadUint64(&coldCounts.count) {
507 runtime.Gosched() // Let observations get work done.
508 }
509
510 sum := &dto.Summary{
511 SampleCount: proto.Uint64(count),
512 SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
513 CreatedTimestamp: s.createdTs,
514 }
515
516 out.Summary = sum
517 out.Label = s.labelPairs
518
519 // Finally add all the cold counts to the new hot counts and reset the cold counts.
520 atomic.AddUint64(&hotCounts.count, count)
521 atomic.StoreUint64(&coldCounts.count, 0)
522 for {
523 oldBits := atomic.LoadUint64(&hotCounts.sumBits)
524 newBits := math.Float64bits(math.Float64frombits(oldBits) + sum.GetSampleSum())
525 if atomic.CompareAndSwapUint64(&hotCounts.sumBits, oldBits, newBits) {
526 atomic.StoreUint64(&coldCounts.sumBits, 0)
527 break
528 }
529 }
530 return nil
531 }
532
533 type quantSort []*dto.Quantile
534
535 func (s quantSort) Len() int {
536 return len(s)
537 }
538
539 func (s quantSort) Swap(i, j int) {
540 s[i], s[j] = s[j], s[i]
541 }
542
543 func (s quantSort) Less(i, j int) bool {
544 return s[i].GetQuantile() < s[j].GetQuantile()
545 }
546
547 // SummaryVec is a Collector that bundles a set of Summaries that all share the
548 // same Desc, but have different values for their variable labels. This is used
549 // if you want to count the same thing partitioned by various dimensions
550 // (e.g. HTTP request latencies, partitioned by status code and method). Create
551 // instances with NewSummaryVec.
552 type SummaryVec struct {
553 *MetricVec
554 }
555
556 // NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and
557 // partitioned by the given label names.
558 //
559 // Due to the way a Summary is represented in the Prometheus text format and how
560 // it is handled by the Prometheus server internally, “quantile” is an illegal
561 // label name. NewSummaryVec will panic if this label name is used.
562 func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
563 return V2.NewSummaryVec(SummaryVecOpts{
564 SummaryOpts: opts,
565 VariableLabels: UnconstrainedLabels(labelNames),
566 })
567 }
568
569 // NewSummaryVec creates a new SummaryVec based on the provided SummaryVecOpts.
570 func (v2) NewSummaryVec(opts SummaryVecOpts) *SummaryVec {
571 for _, ln := range opts.VariableLabels.labelNames() {
572 if ln == quantileLabel {
573 panic(errQuantileLabelNotAllowed)
574 }
575 }
576 desc := V2.NewDesc(
577 BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
578 opts.Help,
579 opts.VariableLabels,
580 opts.ConstLabels,
581 )
582 return &SummaryVec{
583 MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
584 return newSummary(desc, opts.SummaryOpts, lvs...)
585 }),
586 }
587 }
588
589 // GetMetricWithLabelValues returns the Summary for the given slice of label
590 // values (same order as the variable labels in Desc). If that combination of
591 // label values is accessed for the first time, a new Summary is created.
592 //
593 // It is possible to call this method without using the returned Summary to only
594 // create the new Summary but leave it at its starting value, a Summary without
595 // any observations.
596 //
597 // Keeping the Summary for later use is possible (and should be considered if
598 // performance is critical), but keep in mind that Reset, DeleteLabelValues and
599 // Delete can be used to delete the Summary from the SummaryVec. In that case,
600 // the Summary will still exist, but it will not be exported anymore, even if a
601 // Summary with the same label values is created later. See also the CounterVec
602 // example.
603 //
604 // An error is returned if the number of label values is not the same as the
605 // number of variable labels in Desc (minus any curried labels).
606 //
607 // Note that for more than one label value, this method is prone to mistakes
608 // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
609 // an alternative to avoid that type of mistake. For higher label numbers, the
610 // latter has a much more readable (albeit more verbose) syntax, but it comes
611 // with a performance overhead (for creating and processing the Labels map).
612 // See also the GaugeVec example.
613 func (v *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
614 metric, err := v.MetricVec.GetMetricWithLabelValues(lvs...)
615 if metric != nil {
616 return metric.(Observer), err
617 }
618 return nil, err
619 }
620
621 // GetMetricWith returns the Summary for the given Labels map (the label names
622 // must match those of the variable labels in Desc). If that label map is
623 // accessed for the first time, a new Summary is created. Implications of
624 // creating a Summary without using it and keeping the Summary for later use are
625 // the same as for GetMetricWithLabelValues.
626 //
627 // An error is returned if the number and names of the Labels are inconsistent
628 // with those of the variable labels in Desc (minus any curried labels).
629 //
630 // This method is used for the same purpose as
631 // GetMetricWithLabelValues(...string). See there for pros and cons of the two
632 // methods.
633 func (v *SummaryVec) GetMetricWith(labels Labels) (Observer, error) {
634 metric, err := v.MetricVec.GetMetricWith(labels)
635 if metric != nil {
636 return metric.(Observer), err
637 }
638 return nil, err
639 }
640
641 // WithLabelValues works as GetMetricWithLabelValues, but panics where
642 // GetMetricWithLabelValues would have returned an error. Not returning an
643 // error allows shortcuts like
644 //
645 // myVec.WithLabelValues("404", "GET").Observe(42.21)
646 func (v *SummaryVec) WithLabelValues(lvs ...string) Observer {
647 s, err := v.GetMetricWithLabelValues(lvs...)
648 if err != nil {
649 panic(err)
650 }
651 return s
652 }
653
654 // With works as GetMetricWith, but panics where GetMetricWithLabels would have
655 // returned an error. Not returning an error allows shortcuts like
656 //
657 // myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
658 func (v *SummaryVec) With(labels Labels) Observer {
659 s, err := v.GetMetricWith(labels)
660 if err != nil {
661 panic(err)
662 }
663 return s
664 }
665
666 // CurryWith returns a vector curried with the provided labels, i.e. the
667 // returned vector has those labels pre-set for all labeled operations performed
668 // on it. The cardinality of the curried vector is reduced accordingly. The
669 // order of the remaining labels stays the same (just with the curried labels
670 // taken out of the sequence – which is relevant for the
671 // (GetMetric)WithLabelValues methods). It is possible to curry a curried
672 // vector, but only with labels not yet used for currying before.
673 //
674 // The metrics contained in the SummaryVec are shared between the curried and
675 // uncurried vectors. They are just accessed differently. Curried and uncurried
676 // vectors behave identically in terms of collection. Only one must be
677 // registered with a given registry (usually the uncurried version). The Reset
678 // method deletes all metrics, even if called on a curried vector.
679 func (v *SummaryVec) CurryWith(labels Labels) (ObserverVec, error) {
680 vec, err := v.MetricVec.CurryWith(labels)
681 if vec != nil {
682 return &SummaryVec{vec}, err
683 }
684 return nil, err
685 }
686
687 // MustCurryWith works as CurryWith but panics where CurryWith would have
688 // returned an error.
689 func (v *SummaryVec) MustCurryWith(labels Labels) ObserverVec {
690 vec, err := v.CurryWith(labels)
691 if err != nil {
692 panic(err)
693 }
694 return vec
695 }
696
697 type constSummary struct {
698 desc *Desc
699 count uint64
700 sum float64
701 quantiles map[float64]float64
702 labelPairs []*dto.LabelPair
703 createdTs *timestamppb.Timestamp
704 }
705
706 func (s *constSummary) Desc() *Desc {
707 return s.desc
708 }
709
710 func (s *constSummary) Write(out *dto.Metric) error {
711 sum := &dto.Summary{
712 CreatedTimestamp: s.createdTs,
713 }
714 qs := make([]*dto.Quantile, 0, len(s.quantiles))
715
716 sum.SampleCount = proto.Uint64(s.count)
717 sum.SampleSum = proto.Float64(s.sum)
718
719 for rank, q := range s.quantiles {
720 qs = append(qs, &dto.Quantile{
721 Quantile: proto.Float64(rank),
722 Value: proto.Float64(q),
723 })
724 }
725
726 if len(qs) > 0 {
727 sort.Sort(quantSort(qs))
728 }
729 sum.Quantile = qs
730
731 out.Summary = sum
732 out.Label = s.labelPairs
733
734 return nil
735 }
736
737 // NewConstSummary returns a metric representing a Prometheus summary with fixed
738 // values for the count, sum, and quantiles. As those parameters cannot be
739 // changed, the returned value does not implement the Summary interface (but
740 // only the Metric interface). Users of this package will not have much use for
741 // it in regular operations. However, when implementing custom Collectors, it is
742 // useful as a throw-away metric that is generated on the fly to send it to
743 // Prometheus in the Collect method.
744 //
745 // quantiles maps ranks to quantile values. For example, a median latency of
746 // 0.23s and a 99th percentile latency of 0.56s would be expressed as:
747 //
748 // map[float64]float64{0.5: 0.23, 0.99: 0.56}
749 //
750 // NewConstSummary returns an error if the length of labelValues is not
751 // consistent with the variable labels in Desc or if Desc is invalid.
752 func NewConstSummary(
753 desc *Desc,
754 count uint64,
755 sum float64,
756 quantiles map[float64]float64,
757 labelValues ...string,
758 ) (Metric, error) {
759 if desc.err != nil {
760 return nil, desc.err
761 }
762 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
763 return nil, err
764 }
765 return &constSummary{
766 desc: desc,
767 count: count,
768 sum: sum,
769 quantiles: quantiles,
770 labelPairs: MakeLabelPairs(desc, labelValues),
771 }, nil
772 }
773
774 // MustNewConstSummary is a version of NewConstSummary that panics where
775 // NewConstMetric would have returned an error.
776 func MustNewConstSummary(
777 desc *Desc,
778 count uint64,
779 sum float64,
780 quantiles map[float64]float64,
781 labelValues ...string,
782 ) Metric {
783 m, err := NewConstSummary(desc, count, sum, quantiles, labelValues...)
784 if err != nil {
785 panic(err)
786 }
787 return m
788 }
789
790 // NewConstSummaryWithCreatedTimestamp does the same thing as NewConstSummary but sets the created timestamp.
791 func NewConstSummaryWithCreatedTimestamp(
792 desc *Desc,
793 count uint64,
794 sum float64,
795 quantiles map[float64]float64,
796 ct time.Time,
797 labelValues ...string,
798 ) (Metric, error) {
799 if desc.err != nil {
800 return nil, desc.err
801 }
802 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
803 return nil, err
804 }
805 return &constSummary{
806 desc: desc,
807 count: count,
808 sum: sum,
809 quantiles: quantiles,
810 labelPairs: MakeLabelPairs(desc, labelValues),
811 createdTs: timestamppb.New(ct),
812 }, nil
813 }
814
815 // MustNewConstSummaryWithCreatedTimestamp is a version of NewConstSummaryWithCreatedTimestamp that panics where
816 // NewConstSummaryWithCreatedTimestamp would have returned an error.
817 func MustNewConstSummaryWithCreatedTimestamp(
818 desc *Desc,
819 count uint64,
820 sum float64,
821 quantiles map[float64]float64,
822 ct time.Time,
823 labelValues ...string,
824 ) Metric {
825 m, err := NewConstSummaryWithCreatedTimestamp(desc, count, sum, quantiles, ct, labelValues...)
826 if err != nil {
827 panic(err)
828 }
829 return m
830 }