Debian Codegraph @

prometheus/histogram.go

raw
1 // Copyright 2015 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 "errors"
18 "fmt"
19 "math"
20 "runtime"
21 "sort"
22 "sync"
23 "sync/atomic"
24 "time"
25
26 dto "github.com/prometheus/client_model/go"
27
28 "google.golang.org/protobuf/proto"
29 "google.golang.org/protobuf/types/known/timestamppb"
30 )
31
32 const (
33 nativeHistogramSchemaMaximum = 8
34 nativeHistogramSchemaMinimum = -4
35 )
36
37 // nativeHistogramBounds for the frac of observed values. Only relevant for
38 // schema > 0. The position in the slice is the schema. (0 is never used, just
39 // here for convenience of using the schema directly as the index.)
40 //
41 // TODO(beorn7): Currently, we do a binary search into these slices. There are
42 // ways to turn it into a small number of simple array lookups. It probably only
43 // matters for schema 5 and beyond, but should be investigated. See this comment
44 // as a starting point:
45 // https://github.com/open-telemetry/opentelemetry-specification/issues/1776#issuecomment-870164310
46 var nativeHistogramBounds = [][]float64{
47 // Schema "0":
48 {0.5},
49 // Schema 1:
50 {0.5, 0.7071067811865475},
51 // Schema 2:
52 {0.5, 0.5946035575013605, 0.7071067811865475, 0.8408964152537144},
53 // Schema 3:
54 {
55 0.5, 0.5452538663326288, 0.5946035575013605, 0.6484197773255048,
56 0.7071067811865475, 0.7711054127039704, 0.8408964152537144, 0.9170040432046711,
57 },
58 // Schema 4:
59 {
60 0.5, 0.5221368912137069, 0.5452538663326288, 0.5693943173783458,
61 0.5946035575013605, 0.620928906036742, 0.6484197773255048, 0.6771277734684463,
62 0.7071067811865475, 0.7384130729697496, 0.7711054127039704, 0.805245165974627,
63 0.8408964152537144, 0.8781260801866495, 0.9170040432046711, 0.9576032806985735,
64 },
65 // Schema 5:
66 {
67 0.5, 0.5109485743270583, 0.5221368912137069, 0.5335702003384117,
68 0.5452538663326288, 0.5571933712979462, 0.5693943173783458, 0.5818624293887887,
69 0.5946035575013605, 0.6076236799902344, 0.620928906036742, 0.6345254785958666,
70 0.6484197773255048, 0.6626183215798706, 0.6771277734684463, 0.6919549409819159,
71 0.7071067811865475, 0.7225904034885232, 0.7384130729697496, 0.7545822137967112,
72 0.7711054127039704, 0.7879904225539431, 0.805245165974627, 0.8228777390769823,
73 0.8408964152537144, 0.8593096490612387, 0.8781260801866495, 0.8973545375015533,
74 0.9170040432046711, 0.9370838170551498, 0.9576032806985735, 0.9785720620876999,
75 },
76 // Schema 6:
77 {
78 0.5, 0.5054446430258502, 0.5109485743270583, 0.5165124395106142,
79 0.5221368912137069, 0.5278225891802786, 0.5335702003384117, 0.5393803988785598,
80 0.5452538663326288, 0.5511912916539204, 0.5571933712979462, 0.5632608093041209,
81 0.5693943173783458, 0.5755946149764913, 0.5818624293887887, 0.5881984958251406,
82 0.5946035575013605, 0.6010783657263515, 0.6076236799902344, 0.6142402680534349,
83 0.620928906036742, 0.6276903785123455, 0.6345254785958666, 0.6414350080393891,
84 0.6484197773255048, 0.6554806057623822, 0.6626183215798706, 0.6698337620266515,
85 0.6771277734684463, 0.6845012114872953, 0.6919549409819159, 0.6994898362691555,
86 0.7071067811865475, 0.7148066691959849, 0.7225904034885232, 0.7304588970903234,
87 0.7384130729697496, 0.7464538641456323, 0.7545822137967112, 0.762799075372269,
88 0.7711054127039704, 0.7795022001189185, 0.7879904225539431, 0.7965710756711334,
89 0.805245165974627, 0.8140137109286738, 0.8228777390769823, 0.8318382901633681,
90 0.8408964152537144, 0.8500531768592616, 0.8593096490612387, 0.8686669176368529,
91 0.8781260801866495, 0.8876882462632604, 0.8973545375015533, 0.9071260877501991,
92 0.9170040432046711, 0.9269895625416926, 0.9370838170551498, 0.9472879907934827,
93 0.9576032806985735, 0.9680308967461471, 0.9785720620876999, 0.9892280131939752,
94 },
95 // Schema 7:
96 {
97 0.5, 0.5027149505564014, 0.5054446430258502, 0.5081891574554764,
98 0.5109485743270583, 0.5137229745593818, 0.5165124395106142, 0.5193170509806894,
99 0.5221368912137069, 0.5249720429003435, 0.5278225891802786, 0.5306886136446309,
100 0.5335702003384117, 0.5364674337629877, 0.5393803988785598, 0.5423091811066545,
101 0.5452538663326288, 0.5482145409081883, 0.5511912916539204, 0.5541842058618393,
102 0.5571933712979462, 0.5602188762048033, 0.5632608093041209, 0.5663192597993595,
103 0.5693943173783458, 0.572486072215902, 0.5755946149764913, 0.5787200368168754,
104 0.5818624293887887, 0.585021884841625, 0.5881984958251406, 0.5913923554921704,
105 0.5946035575013605, 0.5978321960199137, 0.6010783657263515, 0.6043421618132907,
106 0.6076236799902344, 0.6109230164863786, 0.6142402680534349, 0.6175755319684665,
107 0.620928906036742, 0.6243004885946023, 0.6276903785123455, 0.6310986751971253,
108 0.6345254785958666, 0.637970889198196, 0.6414350080393891, 0.6449179367033329,
109 0.6484197773255048, 0.6519406325959679, 0.6554806057623822, 0.659039800633032,
110 0.6626183215798706, 0.6662162735415805, 0.6698337620266515, 0.6734708931164728,
111 0.6771277734684463, 0.6808045103191123, 0.6845012114872953, 0.688217985377265,
112 0.6919549409819159, 0.6957121878859629, 0.6994898362691555, 0.7032879969095076,
113 0.7071067811865475, 0.7109463010845827, 0.7148066691959849, 0.718687998724491,
114 0.7225904034885232, 0.7265139979245261, 0.7304588970903234, 0.7344252166684908,
115 0.7384130729697496, 0.7424225829363761, 0.7464538641456323, 0.7505070348132126,
116 0.7545822137967112, 0.7586795205991071, 0.762799075372269, 0.7669409989204777,
117 0.7711054127039704, 0.7752924388424999, 0.7795022001189185, 0.7837348199827764,
118 0.7879904225539431, 0.7922691326262467, 0.7965710756711334, 0.8008963778413465,
119 0.805245165974627, 0.8096175675974316, 0.8140137109286738, 0.8184337248834821,
120 0.8228777390769823, 0.8273458838280969, 0.8318382901633681, 0.8363550898207981,
121 0.8408964152537144, 0.8454623996346523, 0.8500531768592616, 0.8546688815502312,
122 0.8593096490612387, 0.8639756154809185, 0.8686669176368529, 0.8733836930995842,
123 0.8781260801866495, 0.8828942179666361, 0.8876882462632604, 0.8925083056594671,
124 0.8973545375015533, 0.9022270839033115, 0.9071260877501991, 0.9120516927035263,
125 0.9170040432046711, 0.9219832844793128, 0.9269895625416926, 0.9320230241988943,
126 0.9370838170551498, 0.9421720895161669, 0.9472879907934827, 0.9524316709088368,
127 0.9576032806985735, 0.9628029718180622, 0.9680308967461471, 0.9732872087896164,
128 0.9785720620876999, 0.9838856116165875, 0.9892280131939752, 0.9945994234836328,
129 },
130 // Schema 8:
131 {
132 0.5, 0.5013556375251013, 0.5027149505564014, 0.5040779490592088,
133 0.5054446430258502, 0.5068150424757447, 0.5081891574554764, 0.509566998038869,
134 0.5109485743270583, 0.5123338964485679, 0.5137229745593818, 0.5151158188430205,
135 0.5165124395106142, 0.5179128468009786, 0.5193170509806894, 0.520725062344158,
136 0.5221368912137069, 0.5235525479396449, 0.5249720429003435, 0.526395386502313,
137 0.5278225891802786, 0.5292536613972564, 0.5306886136446309, 0.5321274564422321,
138 0.5335702003384117, 0.5350168559101208, 0.5364674337629877, 0.5379219445313954,
139 0.5393803988785598, 0.5408428074966075, 0.5423091811066545, 0.5437795304588847,
140 0.5452538663326288, 0.5467321995364429, 0.5482145409081883, 0.549700901315111,
141 0.5511912916539204, 0.5526857228508706, 0.5541842058618393, 0.5556867516724088,
142 0.5571933712979462, 0.5587040757836845, 0.5602188762048033, 0.5617377836665098,
143 0.5632608093041209, 0.564787964283144, 0.5663192597993595, 0.5678547070789026,
144 0.5693943173783458, 0.5709381019847808, 0.572486072215902, 0.5740382394200894,
145 0.5755946149764913, 0.5771552102951081, 0.5787200368168754, 0.5802891060137493,
146 0.5818624293887887, 0.5834400184762408, 0.585021884841625, 0.5866080400818185,
147 0.5881984958251406, 0.5897932637314379, 0.5913923554921704, 0.5929957828304968,
148 0.5946035575013605, 0.5962156912915756, 0.5978321960199137, 0.5994530835371903,
149 0.6010783657263515, 0.6027080545025619, 0.6043421618132907, 0.6059806996384005,
150 0.6076236799902344, 0.6092711149137041, 0.6109230164863786, 0.6125793968185725,
151 0.6142402680534349, 0.6159056423670379, 0.6175755319684665, 0.6192499490999082,
152 0.620928906036742, 0.622612415087629, 0.6243004885946023, 0.6259931389331581,
153 0.6276903785123455, 0.6293922197748583, 0.6310986751971253, 0.6328097572894031,
154 0.6345254785958666, 0.6362458516947014, 0.637970889198196, 0.6397006037528346,
155 0.6414350080393891, 0.6431741147730128, 0.6449179367033329, 0.6466664866145447,
156 0.6484197773255048, 0.6501778216898253, 0.6519406325959679, 0.6537082229673385,
157 0.6554806057623822, 0.6572577939746774, 0.659039800633032, 0.6608266388015788,
158 0.6626183215798706, 0.6644148621029772, 0.6662162735415805, 0.6680225691020727,
159 0.6698337620266515, 0.6716498655934177, 0.6734708931164728, 0.6752968579460171,
160 0.6771277734684463, 0.6789636531064505, 0.6808045103191123, 0.6826503586020058,
161 0.6845012114872953, 0.6863570825438342, 0.688217985377265, 0.690083933630119,
162 0.6919549409819159, 0.6938310211492645, 0.6957121878859629, 0.6975984549830999,
163 0.6994898362691555, 0.7013863456101023, 0.7032879969095076, 0.7051948041086352,
164 0.7071067811865475, 0.7090239421602076, 0.7109463010845827, 0.7128738720527471,
165 0.7148066691959849, 0.7167447066838943, 0.718687998724491, 0.7206365595643126,
166 0.7225904034885232, 0.7245495448210174, 0.7265139979245261, 0.7284837772007218,
167 0.7304588970903234, 0.7324393720732029, 0.7344252166684908, 0.7364164454346837,
168 0.7384130729697496, 0.7404151139112358, 0.7424225829363761, 0.7444354947621984,
169 0.7464538641456323, 0.7484777058836176, 0.7505070348132126, 0.7525418658117031,
170 0.7545822137967112, 0.7566280937263048, 0.7586795205991071, 0.7607365094544071,
171 0.762799075372269, 0.7648672334736434, 0.7669409989204777, 0.7690203869158282,
172 0.7711054127039704, 0.7731960915705107, 0.7752924388424999, 0.7773944698885442,
173 0.7795022001189185, 0.7816156449856788, 0.7837348199827764, 0.7858597406461707,
174 0.7879904225539431, 0.7901268813264122, 0.7922691326262467, 0.7944171921585818,
175 0.7965710756711334, 0.7987307989543135, 0.8008963778413465, 0.8030678282083853,
176 0.805245165974627, 0.8074284071024302, 0.8096175675974316, 0.8118126635086642,
177 0.8140137109286738, 0.8162207259936375, 0.8184337248834821, 0.820652723822003,
178 0.8228777390769823, 0.8251087869603088, 0.8273458838280969, 0.8295890460808079,
179 0.8318382901633681, 0.8340936325652911, 0.8363550898207981, 0.8386226785089391,
180 0.8408964152537144, 0.8431763167241966, 0.8454623996346523, 0.8477546807446661,
181 0.8500531768592616, 0.8523579048290255, 0.8546688815502312, 0.8569861239649629,
182 0.8593096490612387, 0.8616394738731368, 0.8639756154809185, 0.8663180910111553,
183 0.8686669176368529, 0.871022112577578, 0.8733836930995842, 0.8757516765159389,
184 0.8781260801866495, 0.8805069215187917, 0.8828942179666361, 0.8852879870317771,
185 0.8876882462632604, 0.890095013257712, 0.8925083056594671, 0.8949281411607002,
186 0.8973545375015533, 0.8997875124702672, 0.9022270839033115, 0.9046732696855155,
187 0.9071260877501991, 0.909585556079304, 0.9120516927035263, 0.9145245157024483,
188 0.9170040432046711, 0.9194902933879467, 0.9219832844793128, 0.9244830347552253,
189 0.9269895625416926, 0.92950288621441, 0.9320230241988943, 0.9345499949706191,
190 0.9370838170551498, 0.93962450902828, 0.9421720895161669, 0.9447265771954693,
191 0.9472879907934827, 0.9498563490882775, 0.9524316709088368, 0.9550139751351947,
192 0.9576032806985735, 0.9601996065815236, 0.9628029718180622, 0.9654133954938133,
193 0.9680308967461471, 0.9706554947643201, 0.9732872087896164, 0.9759260581154889,
194 0.9785720620876999, 0.9812252401044634, 0.9838856116165875, 0.9865531961276168,
195 0.9892280131939752, 0.9919100824251095, 0.9945994234836328, 0.9972960560854698,
196 },
197 }
198
199 // The nativeHistogramBounds above can be generated with the code below.
200 //
201 // TODO(beorn7): It's tempting to actually use `go generate` to generate the
202 // code above. However, this could lead to slightly different numbers on
203 // different architectures. We still need to come to terms if we are fine with
204 // that, or if we might prefer to specify precise numbers in the standard.
205 //
206 // var nativeHistogramBounds [][]float64 = make([][]float64, 9)
207 //
208 // func init() {
209 // // Populate nativeHistogramBounds.
210 // numBuckets := 1
211 // for i := range nativeHistogramBounds {
212 // bounds := []float64{0.5}
213 // factor := math.Exp2(math.Exp2(float64(-i)))
214 // for j := 0; j < numBuckets-1; j++ {
215 // var bound float64
216 // if (j+1)%2 == 0 {
217 // // Use previously calculated value for increased precision.
218 // bound = nativeHistogramBounds[i-1][j/2+1]
219 // } else {
220 // bound = bounds[j] * factor
221 // }
222 // bounds = append(bounds, bound)
223 // }
224 // numBuckets *= 2
225 // nativeHistogramBounds[i] = bounds
226 // }
227 // }
228
229 // A Histogram counts individual observations from an event or sample stream in
230 // configurable static buckets (or in dynamic sparse buckets as part of the
231 // experimental Native Histograms, see below for more details). Similar to a
232 // Summary, it also provides a sum of observations and an observation count.
233 //
234 // On the Prometheus server, quantiles can be calculated from a Histogram using
235 // the histogram_quantile PromQL function.
236 //
237 // Note that Histograms, in contrast to Summaries, can be aggregated in PromQL
238 // (see the documentation for detailed procedures). However, Histograms require
239 // the user to pre-define suitable buckets, and they are in general less
240 // accurate. (Both problems are addressed by the experimental Native
241 // Histograms. To use them, configure a NativeHistogramBucketFactor in the
242 // HistogramOpts. They also require a Prometheus server v2.40+ with the
243 // corresponding feature flag enabled.)
244 //
245 // The Observe method of a Histogram has a very low performance overhead in
246 // comparison with the Observe method of a Summary.
247 //
248 // To create Histogram instances, use NewHistogram.
249 type Histogram interface {
250 Metric
251 Collector
252
253 // Observe adds a single observation to the histogram. Observations are
254 // usually positive or zero. Negative observations are accepted but
255 // prevent current versions of Prometheus from properly detecting
256 // counter resets in the sum of observations. (The experimental Native
257 // Histograms handle negative observations properly.) See
258 // https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations
259 // for details.
260 Observe(float64)
261 }
262
263 // bucketLabel is used for the label that defines the upper bound of a
264 // bucket of a histogram ("le" -> "less or equal").
265 const bucketLabel = "le"
266
267 // DefBuckets are the default Histogram buckets. The default buckets are
268 // tailored to broadly measure the response time (in seconds) of a network
269 // service. Most likely, however, you will be required to define buckets
270 // customized to your use case.
271 var DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
272
273 // DefNativeHistogramZeroThreshold is the default value for
274 // NativeHistogramZeroThreshold in the HistogramOpts.
275 //
276 // The value is 2^-128 (or 0.5*2^-127 in the actual IEEE 754 representation),
277 // which is a bucket boundary at all possible resolutions.
278 const DefNativeHistogramZeroThreshold = 2.938735877055719e-39
279
280 // NativeHistogramZeroThresholdZero can be used as NativeHistogramZeroThreshold
281 // in the HistogramOpts to create a zero bucket of width zero, i.e. a zero
282 // bucket that only receives observations of precisely zero.
283 const NativeHistogramZeroThresholdZero = -1
284
285 var errBucketLabelNotAllowed = fmt.Errorf(
286 "%q is not allowed as label name in histograms", bucketLabel,
287 )
288
289 // LinearBuckets creates 'count' regular buckets, each 'width' wide, where the
290 // lowest bucket has an upper bound of 'start'. The final +Inf bucket is not
291 // counted and not included in the returned slice. The returned slice is meant
292 // to be used for the Buckets field of HistogramOpts.
293 //
294 // The function panics if 'count' is zero or negative.
295 func LinearBuckets(start, width float64, count int) []float64 {
296 if count < 1 {
297 panic("LinearBuckets needs a positive count")
298 }
299 buckets := make([]float64, count)
300 for i := range buckets {
301 buckets[i] = start
302 start += width
303 }
304 return buckets
305 }
306
307 // ExponentialBuckets creates 'count' regular buckets, where the lowest bucket
308 // has an upper bound of 'start' and each following bucket's upper bound is
309 // 'factor' times the previous bucket's upper bound. The final +Inf bucket is
310 // not counted and not included in the returned slice. The returned slice is
311 // meant to be used for the Buckets field of HistogramOpts.
312 //
313 // The function panics if 'count' is 0 or negative, if 'start' is 0 or negative,
314 // or if 'factor' is less than or equal 1.
315 func ExponentialBuckets(start, factor float64, count int) []float64 {
316 if count < 1 {
317 panic("ExponentialBuckets needs a positive count")
318 }
319 if start <= 0 {
320 panic("ExponentialBuckets needs a positive start value")
321 }
322 if factor <= 1 {
323 panic("ExponentialBuckets needs a factor greater than 1")
324 }
325 buckets := make([]float64, count)
326 for i := range buckets {
327 buckets[i] = start
328 start *= factor
329 }
330 return buckets
331 }
332
333 // ExponentialBucketsRange creates 'count' buckets, where the lowest bucket is
334 // 'min' and the highest bucket is 'max'. The final +Inf bucket is not counted
335 // and not included in the returned slice. The returned slice is meant to be
336 // used for the Buckets field of HistogramOpts.
337 //
338 // The function panics if 'count' is 0 or negative, if 'min' is 0 or negative.
339 func ExponentialBucketsRange(minBucket, maxBucket float64, count int) []float64 {
340 if count < 1 {
341 panic("ExponentialBucketsRange count needs a positive count")
342 }
343 if minBucket <= 0 {
344 panic("ExponentialBucketsRange min needs to be greater than 0")
345 }
346
347 // Formula for exponential buckets.
348 // max = min*growthFactor^(bucketCount-1)
349
350 // We know max/min and highest bucket. Solve for growthFactor.
351 growthFactor := math.Pow(maxBucket/minBucket, 1.0/float64(count-1))
352
353 // Now that we know growthFactor, solve for each bucket.
354 buckets := make([]float64, count)
355 for i := 1; i <= count; i++ {
356 buckets[i-1] = minBucket * math.Pow(growthFactor, float64(i-1))
357 }
358 return buckets
359 }
360
361 // HistogramOpts bundles the options for creating a Histogram metric. It is
362 // mandatory to set Name to a non-empty string. All other fields are optional
363 // and can safely be left at their zero value, although it is strongly
364 // encouraged to set a Help string.
365 type HistogramOpts struct {
366 // Namespace, Subsystem, and Name are components of the fully-qualified
367 // name of the Histogram (created by joining these components with
368 // "_"). Only Name is mandatory, the others merely help structuring the
369 // name. Note that the fully-qualified name of the Histogram must be a
370 // valid Prometheus metric name.
371 Namespace string
372 Subsystem string
373 Name string
374
375 // Help provides information about this Histogram.
376 //
377 // Metrics with the same fully-qualified name must have the same Help
378 // string.
379 Help string
380
381 // ConstLabels are used to attach fixed labels to this metric. Metrics
382 // with the same fully-qualified name must have the same label names in
383 // their ConstLabels.
384 //
385 // ConstLabels are only used rarely. In particular, do not use them to
386 // attach the same labels to all your metrics. Those use cases are
387 // better covered by target labels set by the scraping Prometheus
388 // server, or by one specific metric (e.g. a build_info or a
389 // machine_role metric). See also
390 // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
391 ConstLabels Labels
392
393 // Buckets defines the buckets into which observations are counted. Each
394 // element in the slice is the upper inclusive bound of a bucket. The
395 // values must be sorted in strictly increasing order. There is no need
396 // to add a highest bucket with +Inf bound, it will be added
397 // implicitly. If Buckets is left as nil or set to a slice of length
398 // zero, it is replaced by default buckets. The default buckets are
399 // DefBuckets if no buckets for a native histogram (see below) are used,
400 // otherwise the default is no buckets. (In other words, if you want to
401 // use both regular buckets and buckets for a native histogram, you have
402 // to define the regular buckets here explicitly.)
403 Buckets []float64
404
405 // If NativeHistogramBucketFactor is greater than one, so-called sparse
406 // buckets are used (in addition to the regular buckets, if defined
407 // above). A Histogram with sparse buckets will be ingested as a Native
408 // Histogram by a Prometheus server with that feature enabled (requires
409 // Prometheus v2.40+). Sparse buckets are exponential buckets covering
410 // the whole float64 range (with the exception of the “zero” bucket, see
411 // NativeHistogramZeroThreshold below). From any one bucket to the next,
412 // the width of the bucket grows by a constant
413 // factor. NativeHistogramBucketFactor provides an upper bound for this
414 // factor (exception see below). The smaller
415 // NativeHistogramBucketFactor, the more buckets will be used and thus
416 // the more costly the histogram will become. A generally good trade-off
417 // between cost and accuracy is a value of 1.1 (each bucket is at most
418 // 10% wider than the previous one), which will result in each power of
419 // two divided into 8 buckets (e.g. there will be 8 buckets between 1
420 // and 2, same as between 2 and 4, and 4 and 8, etc.).
421 //
422 // Details about the actually used factor: The factor is calculated as
423 // 2^(2^-n), where n is an integer number between (and including) -4 and
424 // 8. n is chosen so that the resulting factor is the largest that is
425 // still smaller or equal to NativeHistogramBucketFactor. Note that the
426 // smallest possible factor is therefore approx. 1.00271 (i.e. 2^(2^-8)
427 // ). If NativeHistogramBucketFactor is greater than 1 but smaller than
428 // 2^(2^-8), then the actually used factor is still 2^(2^-8) even though
429 // it is larger than the provided NativeHistogramBucketFactor.
430 //
431 // NOTE: Native Histograms are still an experimental feature. Their
432 // behavior might still change without a major version
433 // bump. Subsequently, all NativeHistogram... options here might still
434 // change their behavior or name (or might completely disappear) without
435 // a major version bump.
436 NativeHistogramBucketFactor float64
437 // All observations with an absolute value of less or equal
438 // NativeHistogramZeroThreshold are accumulated into a “zero” bucket.
439 // For best results, this should be close to a bucket boundary. This is
440 // usually the case if picking a power of two. If
441 // NativeHistogramZeroThreshold is left at zero,
442 // DefNativeHistogramZeroThreshold is used as the threshold. To
443 // configure a zero bucket with an actual threshold of zero (i.e. only
444 // observations of precisely zero will go into the zero bucket), set
445 // NativeHistogramZeroThreshold to the NativeHistogramZeroThresholdZero
446 // constant (or any negative float value).
447 NativeHistogramZeroThreshold float64
448
449 // The next three fields define a strategy to limit the number of
450 // populated sparse buckets. If NativeHistogramMaxBucketNumber is left
451 // at zero, the number of buckets is not limited. (Note that this might
452 // lead to unbounded memory consumption if the values observed by the
453 // Histogram are sufficiently wide-spread. In particular, this could be
454 // used as a DoS attack vector. Where the observed values depend on
455 // external inputs, it is highly recommended to set a
456 // NativeHistogramMaxBucketNumber.) Once the set
457 // NativeHistogramMaxBucketNumber is exceeded, the following strategy is
458 // enacted:
459 // - First, if the last reset (or the creation) of the histogram is at
460 // least NativeHistogramMinResetDuration ago, then the whole
461 // histogram is reset to its initial state (including regular
462 // buckets).
463 // - If less time has passed, or if NativeHistogramMinResetDuration is
464 // zero, no reset is performed. Instead, the zero threshold is
465 // increased sufficiently to reduce the number of buckets to or below
466 // NativeHistogramMaxBucketNumber, but not to more than
467 // NativeHistogramMaxZeroThreshold. Thus, if
468 // NativeHistogramMaxZeroThreshold is already at or below the current
469 // zero threshold, nothing happens at this step.
470 // - After that, if the number of buckets still exceeds
471 // NativeHistogramMaxBucketNumber, the resolution of the histogram is
472 // reduced by doubling the width of the sparse buckets (up to a
473 // growth factor between one bucket to the next of 2^(2^4) = 65536,
474 // see above).
475 // - Any increased zero threshold or reduced resolution is reset back
476 // to their original values once NativeHistogramMinResetDuration has
477 // passed (since the last reset or the creation of the histogram).
478 NativeHistogramMaxBucketNumber uint32
479 NativeHistogramMinResetDuration time.Duration
480 NativeHistogramMaxZeroThreshold float64
481
482 // NativeHistogramMaxExemplars limits the number of exemplars
483 // that are kept in memory for each native histogram. If you leave it at
484 // zero, a default value of 10 is used. If no exemplars should be kept specifically
485 // for native histograms, set it to a negative value. (Scrapers can
486 // still use the exemplars exposed for classic buckets, which are managed
487 // independently.)
488 NativeHistogramMaxExemplars int
489 // NativeHistogramExemplarTTL is only checked once
490 // NativeHistogramMaxExemplars is exceeded. In that case, the
491 // oldest exemplar is removed if it is older than NativeHistogramExemplarTTL.
492 // Otherwise, the older exemplar in the pair of exemplars that are closest
493 // together (on an exponential scale) is removed.
494 // If NativeHistogramExemplarTTL is left at its zero value, a default value of
495 // 5m is used. To always delete the oldest exemplar, set it to a negative value.
496 NativeHistogramExemplarTTL time.Duration
497
498 // now is for testing purposes, by default it's time.Now.
499 now func() time.Time
500
501 // afterFunc is for testing purposes, by default it's time.AfterFunc.
502 afterFunc func(time.Duration, func()) *time.Timer
503 }
504
505 // HistogramVecOpts bundles the options to create a HistogramVec metric.
506 // It is mandatory to set HistogramOpts, see there for mandatory fields. VariableLabels
507 // is optional and can safely be left to its default value.
508 type HistogramVecOpts struct {
509 HistogramOpts
510
511 // VariableLabels are used to partition the metric vector by the given set
512 // of labels. Each label value will be constrained with the optional Constraint
513 // function, if provided.
514 VariableLabels ConstrainableLabels
515 }
516
517 // NewHistogram creates a new Histogram based on the provided HistogramOpts. It
518 // panics if the buckets in HistogramOpts are not in strictly increasing order.
519 //
520 // The returned implementation also implements ExemplarObserver. It is safe to
521 // perform the corresponding type assertion. Exemplars are tracked separately
522 // for each bucket.
523 func NewHistogram(opts HistogramOpts) Histogram {
524 return newHistogram(
525 NewDesc(
526 BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
527 opts.Help,
528 nil,
529 opts.ConstLabels,
530 ),
531 opts,
532 )
533 }
534
535 func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogram {
536 if len(desc.variableLabels.names) != len(labelValues) {
537 panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, labelValues))
538 }
539
540 for _, n := range desc.variableLabels.names {
541 if n == bucketLabel {
542 panic(errBucketLabelNotAllowed)
543 }
544 }
545 for _, lp := range desc.constLabelPairs {
546 if lp.GetName() == bucketLabel {
547 panic(errBucketLabelNotAllowed)
548 }
549 }
550
551 if opts.now == nil {
552 opts.now = time.Now
553 }
554 if opts.afterFunc == nil {
555 opts.afterFunc = time.AfterFunc
556 }
557
558 h := &histogram{
559 desc: desc,
560 upperBounds: opts.Buckets,
561 labelPairs: MakeLabelPairs(desc, labelValues),
562 nativeHistogramMaxBuckets: opts.NativeHistogramMaxBucketNumber,
563 nativeHistogramMaxZeroThreshold: opts.NativeHistogramMaxZeroThreshold,
564 nativeHistogramMinResetDuration: opts.NativeHistogramMinResetDuration,
565 lastResetTime: opts.now(),
566 now: opts.now,
567 afterFunc: opts.afterFunc,
568 }
569 if len(h.upperBounds) == 0 && opts.NativeHistogramBucketFactor <= 1 {
570 h.upperBounds = DefBuckets
571 }
572 if opts.NativeHistogramBucketFactor <= 1 {
573 h.nativeHistogramSchema = math.MinInt32 // To mark that there are no sparse buckets.
574 } else {
575 switch {
576 case opts.NativeHistogramZeroThreshold > 0:
577 h.nativeHistogramZeroThreshold = opts.NativeHistogramZeroThreshold
578 case opts.NativeHistogramZeroThreshold == 0:
579 h.nativeHistogramZeroThreshold = DefNativeHistogramZeroThreshold
580 } // Leave h.nativeHistogramZeroThreshold at 0 otherwise.
581 h.nativeHistogramSchema = pickSchema(opts.NativeHistogramBucketFactor)
582 h.nativeExemplars = makeNativeExemplars(opts.NativeHistogramExemplarTTL, opts.NativeHistogramMaxExemplars)
583 }
584 for i, upperBound := range h.upperBounds {
585 if i < len(h.upperBounds)-1 {
586 if upperBound >= h.upperBounds[i+1] {
587 panic(fmt.Errorf(
588 "histogram buckets must be in increasing order: %f >= %f",
589 upperBound, h.upperBounds[i+1],
590 ))
591 }
592 } else {
593 if math.IsInf(upperBound, +1) {
594 // The +Inf bucket is implicit. Remove it here.
595 h.upperBounds = h.upperBounds[:i]
596 }
597 }
598 }
599 // Finally we know the final length of h.upperBounds and can make buckets
600 // for both counts as well as exemplars:
601 h.counts[0] = &histogramCounts{buckets: make([]uint64, len(h.upperBounds))}
602 atomic.StoreUint64(&h.counts[0].nativeHistogramZeroThresholdBits, math.Float64bits(h.nativeHistogramZeroThreshold))
603 atomic.StoreInt32(&h.counts[0].nativeHistogramSchema, h.nativeHistogramSchema)
604 h.counts[1] = &histogramCounts{buckets: make([]uint64, len(h.upperBounds))}
605 atomic.StoreUint64(&h.counts[1].nativeHistogramZeroThresholdBits, math.Float64bits(h.nativeHistogramZeroThreshold))
606 atomic.StoreInt32(&h.counts[1].nativeHistogramSchema, h.nativeHistogramSchema)
607 h.exemplars = make([]atomic.Value, len(h.upperBounds)+1)
608
609 h.init(h) // Init self-collection.
610 return h
611 }
612
613 type histogramCounts struct {
614 // Order in this struct matters for the alignment required by atomic
615 // operations, see http://golang.org/pkg/sync/atomic/#pkg-note-BUG
616
617 // sumBits contains the bits of the float64 representing the sum of all
618 // observations.
619 sumBits uint64
620 count uint64
621
622 // nativeHistogramZeroBucket counts all (positive and negative)
623 // observations in the zero bucket (with an absolute value less or equal
624 // the current threshold, see next field.
625 nativeHistogramZeroBucket uint64
626 // nativeHistogramZeroThresholdBits is the bit pattern of the current
627 // threshold for the zero bucket. It's initially equal to
628 // nativeHistogramZeroThreshold but may change according to the bucket
629 // count limitation strategy.
630 nativeHistogramZeroThresholdBits uint64
631 // nativeHistogramSchema may change over time according to the bucket
632 // count limitation strategy and therefore has to be saved here.
633 nativeHistogramSchema int32
634 // Number of (positive and negative) sparse buckets.
635 nativeHistogramBucketsNumber uint32
636
637 // Regular buckets.
638 buckets []uint64
639
640 // The sparse buckets for native histograms are implemented with a
641 // sync.Map for now. A dedicated data structure will likely be more
642 // efficient. There are separate maps for negative and positive
643 // observations. The map's value is an *int64, counting observations in
644 // that bucket. (Note that we don't use uint64 as an int64 won't
645 // overflow in practice, and working with signed numbers from the
646 // beginning simplifies the handling of deltas.) The map's key is the
647 // index of the bucket according to the used
648 // nativeHistogramSchema. Index 0 is for an upper bound of 1.
649 nativeHistogramBucketsPositive, nativeHistogramBucketsNegative sync.Map
650 }
651
652 // observe manages the parts of observe that only affects
653 // histogramCounts. doSparse is true if sparse buckets should be done,
654 // too.
655 func (hc *histogramCounts) observe(v float64, bucket int, doSparse bool) {
656 if bucket < len(hc.buckets) {
657 atomic.AddUint64(&hc.buckets[bucket], 1)
658 }
659 atomicAddFloat(&hc.sumBits, v)
660 if doSparse && !math.IsNaN(v) {
661 var (
662 key int
663 schema = atomic.LoadInt32(&hc.nativeHistogramSchema)
664 zeroThreshold = math.Float64frombits(atomic.LoadUint64(&hc.nativeHistogramZeroThresholdBits))
665 bucketCreated, isInf bool
666 )
667 if math.IsInf(v, 0) {
668 // Pretend v is MaxFloat64 but later increment key by one.
669 if math.IsInf(v, +1) {
670 v = math.MaxFloat64
671 } else {
672 v = -math.MaxFloat64
673 }
674 isInf = true
675 }
676 frac, exp := math.Frexp(math.Abs(v))
677 if schema > 0 {
678 bounds := nativeHistogramBounds[schema]
679 key = sort.SearchFloat64s(bounds, frac) + (exp-1)*len(bounds)
680 } else {
681 key = exp
682 if frac == 0.5 {
683 key--
684 }
685 offset := (1 << -schema) - 1
686 key = (key + offset) >> -schema
687 }
688 if isInf {
689 key++
690 }
691 switch {
692 case v > zeroThreshold:
693 bucketCreated = addToBucket(&hc.nativeHistogramBucketsPositive, key, 1)
694 case v < -zeroThreshold:
695 bucketCreated = addToBucket(&hc.nativeHistogramBucketsNegative, key, 1)
696 default:
697 atomic.AddUint64(&hc.nativeHistogramZeroBucket, 1)
698 }
699 if bucketCreated {
700 atomic.AddUint32(&hc.nativeHistogramBucketsNumber, 1)
701 }
702 }
703 // Increment count last as we take it as a signal that the observation
704 // is complete.
705 atomic.AddUint64(&hc.count, 1)
706 }
707
708 type histogram struct {
709 // countAndHotIdx enables lock-free writes with use of atomic updates.
710 // The most significant bit is the hot index [0 or 1] of the count field
711 // below. Observe calls update the hot one. All remaining bits count the
712 // number of Observe calls. Observe starts by incrementing this counter,
713 // and finish by incrementing the count field in the respective
714 // histogramCounts, as a marker for completion.
715 //
716 // Calls of the Write method (which are non-mutating reads from the
717 // perspective of the histogram) swap the hot–cold under the writeMtx
718 // lock. A cooldown is awaited (while locked) by comparing the number of
719 // observations with the initiation count. Once they match, then the
720 // last observation on the now cool one has completed. All cold fields must
721 // be merged into the new hot before releasing writeMtx.
722 //
723 // Fields with atomic access first! See alignment constraint:
724 // http://golang.org/pkg/sync/atomic/#pkg-note-BUG
725 countAndHotIdx uint64
726
727 selfCollector
728 desc *Desc
729
730 // Only used in the Write method and for sparse bucket management.
731 mtx sync.Mutex
732
733 // Two counts, one is "hot" for lock-free observations, the other is
734 // "cold" for writing out a dto.Metric. It has to be an array of
735 // pointers to guarantee 64bit alignment of the histogramCounts, see
736 // http://golang.org/pkg/sync/atomic/#pkg-note-BUG.
737 counts [2]*histogramCounts
738
739 upperBounds []float64
740 labelPairs []*dto.LabelPair
741 exemplars []atomic.Value // One more than buckets (to include +Inf), each a *dto.Exemplar.
742 nativeHistogramSchema int32 // The initial schema. Set to math.MinInt32 if no sparse buckets are used.
743 nativeHistogramZeroThreshold float64 // The initial zero threshold.
744 nativeHistogramMaxZeroThreshold float64
745 nativeHistogramMaxBuckets uint32
746 nativeHistogramMinResetDuration time.Duration
747 // lastResetTime is protected by mtx. It is also used as created timestamp.
748 lastResetTime time.Time
749 // resetScheduled is protected by mtx. It is true if a reset is
750 // scheduled for a later time (when nativeHistogramMinResetDuration has
751 // passed).
752 resetScheduled bool
753 nativeExemplars nativeExemplars
754
755 // now is for testing purposes, by default it's time.Now.
756 now func() time.Time
757
758 // afterFunc is for testing purposes, by default it's time.AfterFunc.
759 afterFunc func(time.Duration, func()) *time.Timer
760 }
761
762 func (h *histogram) Desc() *Desc {
763 return h.desc
764 }
765
766 func (h *histogram) Observe(v float64) {
767 h.observe(v, h.findBucket(v))
768 }
769
770 // ObserveWithExemplar should not be called in a high-frequency setting
771 // for a native histogram with configured exemplars. For this case,
772 // the implementation isn't lock-free and might suffer from lock contention.
773 func (h *histogram) ObserveWithExemplar(v float64, e Labels) {
774 i := h.findBucket(v)
775 h.observe(v, i)
776 h.updateExemplar(v, i, e)
777 }
778
779 func (h *histogram) Write(out *dto.Metric) error {
780 // For simplicity, we protect this whole method by a mutex. It is not in
781 // the hot path, i.e. Observe is called much more often than Write. The
782 // complication of making Write lock-free isn't worth it, if possible at
783 // all.
784 h.mtx.Lock()
785 defer h.mtx.Unlock()
786
787 // Adding 1<<63 switches the hot index (from 0 to 1 or from 1 to 0)
788 // without touching the count bits. See the struct comments for a full
789 // description of the algorithm.
790 n := atomic.AddUint64(&h.countAndHotIdx, 1<<63)
791 // count is contained unchanged in the lower 63 bits.
792 count := n & ((1 << 63) - 1)
793 // The most significant bit tells us which counts is hot. The complement
794 // is thus the cold one.
795 hotCounts := h.counts[n>>63]
796 coldCounts := h.counts[(^n)>>63]
797
798 waitForCooldown(count, coldCounts)
799
800 his := &dto.Histogram{
801 Bucket: make([]*dto.Bucket, len(h.upperBounds)),
802 SampleCount: proto.Uint64(count),
803 SampleSum: proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.sumBits))),
804 CreatedTimestamp: timestamppb.New(h.lastResetTime),
805 }
806 out.Histogram = his
807 out.Label = h.labelPairs
808
809 var cumCount uint64
810 for i, upperBound := range h.upperBounds {
811 cumCount += atomic.LoadUint64(&coldCounts.buckets[i])
812 his.Bucket[i] = &dto.Bucket{
813 CumulativeCount: proto.Uint64(cumCount),
814 UpperBound: proto.Float64(upperBound),
815 }
816 if e := h.exemplars[i].Load(); e != nil {
817 his.Bucket[i].Exemplar = e.(*dto.Exemplar)
818 }
819 }
820 // If there is an exemplar for the +Inf bucket, we have to add that bucket explicitly.
821 if e := h.exemplars[len(h.upperBounds)].Load(); e != nil {
822 b := &dto.Bucket{
823 CumulativeCount: proto.Uint64(count),
824 UpperBound: proto.Float64(math.Inf(1)),
825 Exemplar: e.(*dto.Exemplar),
826 }
827 his.Bucket = append(his.Bucket, b)
828 }
829 if h.nativeHistogramSchema > math.MinInt32 {
830 his.ZeroThreshold = proto.Float64(math.Float64frombits(atomic.LoadUint64(&coldCounts.nativeHistogramZeroThresholdBits)))
831 his.Schema = proto.Int32(atomic.LoadInt32(&coldCounts.nativeHistogramSchema))
832 zeroBucket := atomic.LoadUint64(&coldCounts.nativeHistogramZeroBucket)
833
834 defer func() {
835 coldCounts.nativeHistogramBucketsPositive.Range(addAndReset(&hotCounts.nativeHistogramBucketsPositive, &hotCounts.nativeHistogramBucketsNumber))
836 coldCounts.nativeHistogramBucketsNegative.Range(addAndReset(&hotCounts.nativeHistogramBucketsNegative, &hotCounts.nativeHistogramBucketsNumber))
837 }()
838
839 his.ZeroCount = proto.Uint64(zeroBucket)
840 his.NegativeSpan, his.NegativeDelta = makeBuckets(&coldCounts.nativeHistogramBucketsNegative)
841 his.PositiveSpan, his.PositiveDelta = makeBuckets(&coldCounts.nativeHistogramBucketsPositive)
842
843 // Add a no-op span to a histogram without observations and with
844 // a zero threshold of zero. Otherwise, a native histogram would
845 // look like a classic histogram to scrapers.
846 if *his.ZeroThreshold == 0 && *his.ZeroCount == 0 && len(his.PositiveSpan) == 0 && len(his.NegativeSpan) == 0 {
847 his.PositiveSpan = []*dto.BucketSpan{{
848 Offset: proto.Int32(0),
849 Length: proto.Uint32(0),
850 }}
851 }
852
853 if h.nativeExemplars.isEnabled() {
854 h.nativeExemplars.Lock()
855 his.Exemplars = append(his.Exemplars, h.nativeExemplars.exemplars...)
856 h.nativeExemplars.Unlock()
857 }
858
859 }
860 addAndResetCounts(hotCounts, coldCounts)
861 return nil
862 }
863
864 // findBucket returns the index of the bucket for the provided value, or
865 // len(h.upperBounds) for the +Inf bucket.
866 func (h *histogram) findBucket(v float64) int {
867 n := len(h.upperBounds)
868 if n == 0 {
869 return 0
870 }
871
872 // Early exit: if v is less than or equal to the first upper bound, return 0
873 if v <= h.upperBounds[0] {
874 return 0
875 }
876
877 // Early exit: if v is greater than the last upper bound, return len(h.upperBounds)
878 if v > h.upperBounds[n-1] {
879 return n
880 }
881
882 // For small arrays, use simple linear search
883 // "magic number" 35 is result of tests on couple different (AWS and baremetal) servers
884 // see more details here: https://github.com/prometheus/client_golang/pull/1662
885 if n < 35 {
886 for i, bound := range h.upperBounds {
887 if v <= bound {
888 return i
889 }
890 }
891 // If v is greater than all upper bounds, return len(h.upperBounds)
892 return n
893 }
894
895 // For larger arrays, use stdlib's binary search
896 return sort.SearchFloat64s(h.upperBounds, v)
897 }
898
899 // observe is the implementation for Observe without the findBucket part.
900 func (h *histogram) observe(v float64, bucket int) {
901 // Do not add to sparse buckets for NaN observations.
902 doSparse := h.nativeHistogramSchema > math.MinInt32 && !math.IsNaN(v)
903 // We increment h.countAndHotIdx so that the counter in the lower
904 // 63 bits gets incremented. At the same time, we get the new value
905 // back, which we can use to find the currently-hot counts.
906 n := atomic.AddUint64(&h.countAndHotIdx, 1)
907 hotCounts := h.counts[n>>63]
908 hotCounts.observe(v, bucket, doSparse)
909 if doSparse {
910 h.limitBuckets(hotCounts, v, bucket)
911 }
912 }
913
914 // limitBuckets applies a strategy to limit the number of populated sparse
915 // buckets. It's generally best effort, and there are situations where the
916 // number can go higher (if even the lowest resolution isn't enough to reduce
917 // the number sufficiently, or if the provided counts aren't fully updated yet
918 // by a concurrently happening Write call).
919 func (h *histogram) limitBuckets(counts *histogramCounts, value float64, bucket int) {
920 if h.nativeHistogramMaxBuckets == 0 {
921 return // No limit configured.
922 }
923 if h.nativeHistogramMaxBuckets >= atomic.LoadUint32(&counts.nativeHistogramBucketsNumber) {
924 return // Bucket limit not exceeded yet.
925 }
926
927 h.mtx.Lock()
928 defer h.mtx.Unlock()
929
930 // The hot counts might have been swapped just before we acquired the
931 // lock. Re-fetch the hot counts first...
932 n := atomic.LoadUint64(&h.countAndHotIdx)
933 hotIdx := n >> 63
934 coldIdx := (^n) >> 63
935 hotCounts := h.counts[hotIdx]
936 coldCounts := h.counts[coldIdx]
937 // ...and then check again if we really have to reduce the bucket count.
938 if h.nativeHistogramMaxBuckets >= atomic.LoadUint32(&hotCounts.nativeHistogramBucketsNumber) {
939 return // Bucket limit not exceeded after all.
940 }
941 // Try the various strategies in order.
942 if h.maybeReset(hotCounts, coldCounts, coldIdx, value, bucket) {
943 return
944 }
945 // One of the other strategies will happen. To undo what they will do as
946 // soon as enough time has passed to satisfy
947 // h.nativeHistogramMinResetDuration, schedule a reset at the right time
948 // if we haven't done so already.
949 if h.nativeHistogramMinResetDuration > 0 && !h.resetScheduled {
950 h.resetScheduled = true
951 h.afterFunc(h.nativeHistogramMinResetDuration-h.now().Sub(h.lastResetTime), h.reset)
952 }
953
954 if h.maybeWidenZeroBucket(hotCounts, coldCounts) {
955 return
956 }
957 h.doubleBucketWidth(hotCounts, coldCounts)
958 }
959
960 // maybeReset resets the whole histogram if at least
961 // h.nativeHistogramMinResetDuration has been passed. It returns true if the
962 // histogram has been reset. The caller must have locked h.mtx.
963 func (h *histogram) maybeReset(
964 hot, cold *histogramCounts, coldIdx uint64, value float64, bucket int,
965 ) bool {
966 // We are using the possibly mocked h.now() rather than
967 // time.Since(h.lastResetTime) to enable testing.
968 if h.nativeHistogramMinResetDuration == 0 || // No reset configured.
969 h.resetScheduled || // Do not interefere if a reset is already scheduled.
970 h.now().Sub(h.lastResetTime) < h.nativeHistogramMinResetDuration {
971 return false
972 }
973 // Completely reset coldCounts.
974 h.resetCounts(cold)
975 // Repeat the latest observation to not lose it completely.
976 cold.observe(value, bucket, true)
977 // Make coldCounts the new hot counts while resetting countAndHotIdx.
978 n := atomic.SwapUint64(&h.countAndHotIdx, (coldIdx<<63)+1)
979 count := n & ((1 << 63) - 1)
980 waitForCooldown(count, hot)
981 // Finally, reset the formerly hot counts, too.
982 h.resetCounts(hot)
983 h.lastResetTime = h.now()
984 return true
985 }
986
987 // reset resets the whole histogram. It locks h.mtx itself, i.e. it has to be
988 // called without having locked h.mtx.
989 func (h *histogram) reset() {
990 h.mtx.Lock()
991 defer h.mtx.Unlock()
992
993 n := atomic.LoadUint64(&h.countAndHotIdx)
994 hotIdx := n >> 63
995 coldIdx := (^n) >> 63
996 hot := h.counts[hotIdx]
997 cold := h.counts[coldIdx]
998 // Completely reset coldCounts.
999 h.resetCounts(cold)
1000 // Make coldCounts the new hot counts while resetting countAndHotIdx.
1001 n = atomic.SwapUint64(&h.countAndHotIdx, coldIdx<<63)
1002 count := n & ((1 << 63) - 1)
1003 waitForCooldown(count, hot)
1004 // Finally, reset the formerly hot counts, too.
1005 h.resetCounts(hot)
1006 h.lastResetTime = h.now()
1007 h.resetScheduled = false
1008 }
1009
1010 // maybeWidenZeroBucket widens the zero bucket until it includes the existing
1011 // buckets closest to the zero bucket (which could be two, if an equidistant
1012 // negative and a positive bucket exists, but usually it's only one bucket to be
1013 // merged into the new wider zero bucket). h.nativeHistogramMaxZeroThreshold
1014 // limits how far the zero bucket can be extended, and if that's not enough to
1015 // include an existing bucket, the method returns false. The caller must have
1016 // locked h.mtx.
1017 func (h *histogram) maybeWidenZeroBucket(hot, cold *histogramCounts) bool {
1018 currentZeroThreshold := math.Float64frombits(atomic.LoadUint64(&hot.nativeHistogramZeroThresholdBits))
1019 if currentZeroThreshold >= h.nativeHistogramMaxZeroThreshold {
1020 return false
1021 }
1022 // Find the key of the bucket closest to zero.
1023 smallestKey := findSmallestKey(&hot.nativeHistogramBucketsPositive)
1024 smallestNegativeKey := findSmallestKey(&hot.nativeHistogramBucketsNegative)
1025 if smallestNegativeKey < smallestKey {
1026 smallestKey = smallestNegativeKey
1027 }
1028 if smallestKey == math.MaxInt32 {
1029 return false
1030 }
1031 newZeroThreshold := getLe(smallestKey, atomic.LoadInt32(&hot.nativeHistogramSchema))
1032 if newZeroThreshold > h.nativeHistogramMaxZeroThreshold {
1033 return false // New threshold would exceed the max threshold.
1034 }
1035 atomic.StoreUint64(&cold.nativeHistogramZeroThresholdBits, math.Float64bits(newZeroThreshold))
1036 // Remove applicable buckets.
1037 if _, loaded := cold.nativeHistogramBucketsNegative.LoadAndDelete(smallestKey); loaded {
1038 atomicDecUint32(&cold.nativeHistogramBucketsNumber)
1039 }
1040 if _, loaded := cold.nativeHistogramBucketsPositive.LoadAndDelete(smallestKey); loaded {
1041 atomicDecUint32(&cold.nativeHistogramBucketsNumber)
1042 }
1043 // Make cold counts the new hot counts.
1044 n := atomic.AddUint64(&h.countAndHotIdx, 1<<63)
1045 count := n & ((1 << 63) - 1)
1046 // Swap the pointer names to represent the new roles and make
1047 // the rest less confusing.
1048 hot, cold = cold, hot
1049 waitForCooldown(count, cold)
1050 // Add all the now cold counts to the new hot counts...
1051 addAndResetCounts(hot, cold)
1052 // ...adjust the new zero threshold in the cold counts, too...
1053 atomic.StoreUint64(&cold.nativeHistogramZeroThresholdBits, math.Float64bits(newZeroThreshold))
1054 // ...and then merge the newly deleted buckets into the wider zero
1055 // bucket.
1056 mergeAndDeleteOrAddAndReset := func(hotBuckets, coldBuckets *sync.Map) func(k, v interface{}) bool {
1057 return func(k, v interface{}) bool {
1058 key := k.(int)
1059 bucket := v.(*int64)
1060 if key == smallestKey {
1061 // Merge into hot zero bucket...
1062 atomic.AddUint64(&hot.nativeHistogramZeroBucket, uint64(atomic.LoadInt64(bucket)))
1063 // ...and delete from cold counts.
1064 coldBuckets.Delete(key)
1065 atomicDecUint32(&cold.nativeHistogramBucketsNumber)
1066 } else {
1067 // Add to corresponding hot bucket...
1068 if addToBucket(hotBuckets, key, atomic.LoadInt64(bucket)) {
1069 atomic.AddUint32(&hot.nativeHistogramBucketsNumber, 1)
1070 }
1071 // ...and reset cold bucket.
1072 atomic.StoreInt64(bucket, 0)
1073 }
1074 return true
1075 }
1076 }
1077
1078 cold.nativeHistogramBucketsPositive.Range(mergeAndDeleteOrAddAndReset(&hot.nativeHistogramBucketsPositive, &cold.nativeHistogramBucketsPositive))
1079 cold.nativeHistogramBucketsNegative.Range(mergeAndDeleteOrAddAndReset(&hot.nativeHistogramBucketsNegative, &cold.nativeHistogramBucketsNegative))
1080 return true
1081 }
1082
1083 // doubleBucketWidth doubles the bucket width (by decrementing the schema
1084 // number). Note that very sparse buckets could lead to a low reduction of the
1085 // bucket count (or even no reduction at all). The method does nothing if the
1086 // schema is already -4.
1087 func (h *histogram) doubleBucketWidth(hot, cold *histogramCounts) {
1088 coldSchema := atomic.LoadInt32(&cold.nativeHistogramSchema)
1089 if coldSchema == -4 {
1090 return // Already at lowest resolution.
1091 }
1092 coldSchema--
1093 atomic.StoreInt32(&cold.nativeHistogramSchema, coldSchema)
1094 // Play it simple and just delete all cold buckets.
1095 atomic.StoreUint32(&cold.nativeHistogramBucketsNumber, 0)
1096 deleteSyncMap(&cold.nativeHistogramBucketsNegative)
1097 deleteSyncMap(&cold.nativeHistogramBucketsPositive)
1098 // Make coldCounts the new hot counts.
1099 n := atomic.AddUint64(&h.countAndHotIdx, 1<<63)
1100 count := n & ((1 << 63) - 1)
1101 // Swap the pointer names to represent the new roles and make
1102 // the rest less confusing.
1103 hot, cold = cold, hot
1104 waitForCooldown(count, cold)
1105 // Add all the now cold counts to the new hot counts...
1106 addAndResetCounts(hot, cold)
1107 // ...adjust the schema in the cold counts, too...
1108 atomic.StoreInt32(&cold.nativeHistogramSchema, coldSchema)
1109 // ...and then merge the cold buckets into the wider hot buckets.
1110 merge := func(hotBuckets *sync.Map) func(k, v interface{}) bool {
1111 return func(k, v interface{}) bool {
1112 key := k.(int)
1113 bucket := v.(*int64)
1114 // Adjust key to match the bucket to merge into.
1115 if key > 0 {
1116 key++
1117 }
1118 key /= 2
1119 // Add to corresponding hot bucket.
1120 if addToBucket(hotBuckets, key, atomic.LoadInt64(bucket)) {
1121 atomic.AddUint32(&hot.nativeHistogramBucketsNumber, 1)
1122 }
1123 return true
1124 }
1125 }
1126
1127 cold.nativeHistogramBucketsPositive.Range(merge(&hot.nativeHistogramBucketsPositive))
1128 cold.nativeHistogramBucketsNegative.Range(merge(&hot.nativeHistogramBucketsNegative))
1129 // Play it simple again and just delete all cold buckets.
1130 atomic.StoreUint32(&cold.nativeHistogramBucketsNumber, 0)
1131 deleteSyncMap(&cold.nativeHistogramBucketsNegative)
1132 deleteSyncMap(&cold.nativeHistogramBucketsPositive)
1133 }
1134
1135 func (h *histogram) resetCounts(counts *histogramCounts) {
1136 atomic.StoreUint64(&counts.sumBits, 0)
1137 atomic.StoreUint64(&counts.count, 0)
1138 atomic.StoreUint64(&counts.nativeHistogramZeroBucket, 0)
1139 atomic.StoreUint64(&counts.nativeHistogramZeroThresholdBits, math.Float64bits(h.nativeHistogramZeroThreshold))
1140 atomic.StoreInt32(&counts.nativeHistogramSchema, h.nativeHistogramSchema)
1141 atomic.StoreUint32(&counts.nativeHistogramBucketsNumber, 0)
1142 for i := range h.upperBounds {
1143 atomic.StoreUint64(&counts.buckets[i], 0)
1144 }
1145 deleteSyncMap(&counts.nativeHistogramBucketsNegative)
1146 deleteSyncMap(&counts.nativeHistogramBucketsPositive)
1147 }
1148
1149 // updateExemplar replaces the exemplar for the provided classic bucket.
1150 // With empty labels, it's a no-op. It panics if any of the labels is invalid.
1151 // If histogram is native, the exemplar will be cached into nativeExemplars,
1152 // which has a limit, and will remove one exemplar when limit is reached.
1153 func (h *histogram) updateExemplar(v float64, bucket int, l Labels) {
1154 if l == nil {
1155 return
1156 }
1157 e, err := newExemplar(v, h.now(), l)
1158 if err != nil {
1159 panic(err)
1160 }
1161 h.exemplars[bucket].Store(e)
1162 doSparse := h.nativeHistogramSchema > math.MinInt32 && !math.IsNaN(v)
1163 if doSparse {
1164 h.nativeExemplars.addExemplar(e)
1165 }
1166 }
1167
1168 // HistogramVec is a Collector that bundles a set of Histograms that all share the
1169 // same Desc, but have different values for their variable labels. This is used
1170 // if you want to count the same thing partitioned by various dimensions
1171 // (e.g. HTTP request latencies, partitioned by status code and method). Create
1172 // instances with NewHistogramVec.
1173 type HistogramVec struct {
1174 *MetricVec
1175 }
1176
1177 // NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and
1178 // partitioned by the given label names.
1179 func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
1180 return V2.NewHistogramVec(HistogramVecOpts{
1181 HistogramOpts: opts,
1182 VariableLabels: UnconstrainedLabels(labelNames),
1183 })
1184 }
1185
1186 // NewHistogramVec creates a new HistogramVec based on the provided HistogramVecOpts.
1187 func (v2) NewHistogramVec(opts HistogramVecOpts) *HistogramVec {
1188 desc := V2.NewDesc(
1189 BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
1190 opts.Help,
1191 opts.VariableLabels,
1192 opts.ConstLabels,
1193 )
1194 return &HistogramVec{
1195 MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
1196 return newHistogram(desc, opts.HistogramOpts, lvs...)
1197 }),
1198 }
1199 }
1200
1201 // GetMetricWithLabelValues returns the Histogram for the given slice of label
1202 // values (same order as the variable labels in Desc). If that combination of
1203 // label values is accessed for the first time, a new Histogram is created.
1204 //
1205 // It is possible to call this method without using the returned Histogram to only
1206 // create the new Histogram but leave it at its starting value, a Histogram without
1207 // any observations.
1208 //
1209 // Keeping the Histogram for later use is possible (and should be considered if
1210 // performance is critical), but keep in mind that Reset, DeleteLabelValues and
1211 // Delete can be used to delete the Histogram from the HistogramVec. In that case, the
1212 // Histogram will still exist, but it will not be exported anymore, even if a
1213 // Histogram with the same label values is created later. See also the CounterVec
1214 // example.
1215 //
1216 // An error is returned if the number of label values is not the same as the
1217 // number of variable labels in Desc (minus any curried labels).
1218 //
1219 // Note that for more than one label value, this method is prone to mistakes
1220 // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
1221 // an alternative to avoid that type of mistake. For higher label numbers, the
1222 // latter has a much more readable (albeit more verbose) syntax, but it comes
1223 // with a performance overhead (for creating and processing the Labels map).
1224 // See also the GaugeVec example.
1225 func (v *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Observer, error) {
1226 metric, err := v.MetricVec.GetMetricWithLabelValues(lvs...)
1227 if metric != nil {
1228 return metric.(Observer), err
1229 }
1230 return nil, err
1231 }
1232
1233 // GetMetricWith returns the Histogram for the given Labels map (the label names
1234 // must match those of the variable labels in Desc). If that label map is
1235 // accessed for the first time, a new Histogram is created. Implications of
1236 // creating a Histogram without using it and keeping the Histogram for later use
1237 // are the same as for GetMetricWithLabelValues.
1238 //
1239 // An error is returned if the number and names of the Labels are inconsistent
1240 // with those of the variable labels in Desc (minus any curried labels).
1241 //
1242 // This method is used for the same purpose as
1243 // GetMetricWithLabelValues(...string). See there for pros and cons of the two
1244 // methods.
1245 func (v *HistogramVec) GetMetricWith(labels Labels) (Observer, error) {
1246 metric, err := v.MetricVec.GetMetricWith(labels)
1247 if metric != nil {
1248 return metric.(Observer), err
1249 }
1250 return nil, err
1251 }
1252
1253 // WithLabelValues works as GetMetricWithLabelValues, but panics where
1254 // GetMetricWithLabelValues would have returned an error. Not returning an
1255 // error allows shortcuts like
1256 //
1257 // myVec.WithLabelValues("404", "GET").Observe(42.21)
1258 func (v *HistogramVec) WithLabelValues(lvs ...string) Observer {
1259 h, err := v.GetMetricWithLabelValues(lvs...)
1260 if err != nil {
1261 panic(err)
1262 }
1263 return h
1264 }
1265
1266 // With works as GetMetricWith but panics where GetMetricWithLabels would have
1267 // returned an error. Not returning an error allows shortcuts like
1268 //
1269 // myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Observe(42.21)
1270 func (v *HistogramVec) With(labels Labels) Observer {
1271 h, err := v.GetMetricWith(labels)
1272 if err != nil {
1273 panic(err)
1274 }
1275 return h
1276 }
1277
1278 // CurryWith returns a vector curried with the provided labels, i.e. the
1279 // returned vector has those labels pre-set for all labeled operations performed
1280 // on it. The cardinality of the curried vector is reduced accordingly. The
1281 // order of the remaining labels stays the same (just with the curried labels
1282 // taken out of the sequence – which is relevant for the
1283 // (GetMetric)WithLabelValues methods). It is possible to curry a curried
1284 // vector, but only with labels not yet used for currying before.
1285 //
1286 // The metrics contained in the HistogramVec are shared between the curried and
1287 // uncurried vectors. They are just accessed differently. Curried and uncurried
1288 // vectors behave identically in terms of collection. Only one must be
1289 // registered with a given registry (usually the uncurried version). The Reset
1290 // method deletes all metrics, even if called on a curried vector.
1291 func (v *HistogramVec) CurryWith(labels Labels) (ObserverVec, error) {
1292 vec, err := v.MetricVec.CurryWith(labels)
1293 if vec != nil {
1294 return &HistogramVec{vec}, err
1295 }
1296 return nil, err
1297 }
1298
1299 // MustCurryWith works as CurryWith but panics where CurryWith would have
1300 // returned an error.
1301 func (v *HistogramVec) MustCurryWith(labels Labels) ObserverVec {
1302 vec, err := v.CurryWith(labels)
1303 if err != nil {
1304 panic(err)
1305 }
1306 return vec
1307 }
1308
1309 type constHistogram struct {
1310 desc *Desc
1311 count uint64
1312 sum float64
1313 buckets map[float64]uint64
1314 labelPairs []*dto.LabelPair
1315 createdTs *timestamppb.Timestamp
1316 }
1317
1318 func (h *constHistogram) Desc() *Desc {
1319 return h.desc
1320 }
1321
1322 func (h *constHistogram) Write(out *dto.Metric) error {
1323 his := &dto.Histogram{
1324 CreatedTimestamp: h.createdTs,
1325 }
1326
1327 buckets := make([]*dto.Bucket, 0, len(h.buckets))
1328
1329 his.SampleCount = proto.Uint64(h.count)
1330 his.SampleSum = proto.Float64(h.sum)
1331 for upperBound, count := range h.buckets {
1332 buckets = append(buckets, &dto.Bucket{
1333 CumulativeCount: proto.Uint64(count),
1334 UpperBound: proto.Float64(upperBound),
1335 })
1336 }
1337
1338 if len(buckets) > 0 {
1339 sort.Sort(buckSort(buckets))
1340 }
1341 his.Bucket = buckets
1342
1343 out.Histogram = his
1344 out.Label = h.labelPairs
1345
1346 return nil
1347 }
1348
1349 // NewConstHistogram returns a metric representing a Prometheus histogram with
1350 // fixed values for the count, sum, and bucket counts. As those parameters
1351 // cannot be changed, the returned value does not implement the Histogram
1352 // interface (but only the Metric interface). Users of this package will not
1353 // have much use for it in regular operations. However, when implementing custom
1354 // Collectors, it is useful as a throw-away metric that is generated on the fly
1355 // to send it to Prometheus in the Collect method.
1356 //
1357 // buckets is a map of upper bounds to cumulative counts, excluding the +Inf
1358 // bucket. The +Inf bucket is implicit, and its value is equal to the provided count.
1359 //
1360 // NewConstHistogram returns an error if the length of labelValues is not
1361 // consistent with the variable labels in Desc or if Desc is invalid.
1362 func NewConstHistogram(
1363 desc *Desc,
1364 count uint64,
1365 sum float64,
1366 buckets map[float64]uint64,
1367 labelValues ...string,
1368 ) (Metric, error) {
1369 if desc.err != nil {
1370 return nil, desc.err
1371 }
1372 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
1373 return nil, err
1374 }
1375 return &constHistogram{
1376 desc: desc,
1377 count: count,
1378 sum: sum,
1379 buckets: buckets,
1380 labelPairs: MakeLabelPairs(desc, labelValues),
1381 }, nil
1382 }
1383
1384 // MustNewConstHistogram is a version of NewConstHistogram that panics where
1385 // NewConstHistogram would have returned an error.
1386 func MustNewConstHistogram(
1387 desc *Desc,
1388 count uint64,
1389 sum float64,
1390 buckets map[float64]uint64,
1391 labelValues ...string,
1392 ) Metric {
1393 m, err := NewConstHistogram(desc, count, sum, buckets, labelValues...)
1394 if err != nil {
1395 panic(err)
1396 }
1397 return m
1398 }
1399
1400 // NewConstHistogramWithCreatedTimestamp does the same thing as NewConstHistogram but sets the created timestamp.
1401 func NewConstHistogramWithCreatedTimestamp(
1402 desc *Desc,
1403 count uint64,
1404 sum float64,
1405 buckets map[float64]uint64,
1406 ct time.Time,
1407 labelValues ...string,
1408 ) (Metric, error) {
1409 if desc.err != nil {
1410 return nil, desc.err
1411 }
1412 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
1413 return nil, err
1414 }
1415 return &constHistogram{
1416 desc: desc,
1417 count: count,
1418 sum: sum,
1419 buckets: buckets,
1420 labelPairs: MakeLabelPairs(desc, labelValues),
1421 createdTs: timestamppb.New(ct),
1422 }, nil
1423 }
1424
1425 // MustNewConstHistogramWithCreatedTimestamp is a version of NewConstHistogramWithCreatedTimestamp that panics where
1426 // NewConstHistogramWithCreatedTimestamp would have returned an error.
1427 func MustNewConstHistogramWithCreatedTimestamp(
1428 desc *Desc,
1429 count uint64,
1430 sum float64,
1431 buckets map[float64]uint64,
1432 ct time.Time,
1433 labelValues ...string,
1434 ) Metric {
1435 m, err := NewConstHistogramWithCreatedTimestamp(desc, count, sum, buckets, ct, labelValues...)
1436 if err != nil {
1437 panic(err)
1438 }
1439 return m
1440 }
1441
1442 type buckSort []*dto.Bucket
1443
1444 func (s buckSort) Len() int {
1445 return len(s)
1446 }
1447
1448 func (s buckSort) Swap(i, j int) {
1449 s[i], s[j] = s[j], s[i]
1450 }
1451
1452 func (s buckSort) Less(i, j int) bool {
1453 return s[i].GetUpperBound() < s[j].GetUpperBound()
1454 }
1455
1456 // pickSchema returns the largest number n between -4 and 8 such that
1457 // 2^(2^-n) is less or equal the provided bucketFactor.
1458 //
1459 // Special cases:
1460 // - bucketFactor <= 1: panics.
1461 // - bucketFactor < 2^(2^-8) (but > 1): still returns 8.
1462 func pickSchema(bucketFactor float64) int32 {
1463 if bucketFactor <= 1 {
1464 panic(fmt.Errorf("bucketFactor %f is <=1", bucketFactor))
1465 }
1466 floor := math.Floor(math.Log2(math.Log2(bucketFactor)))
1467 switch {
1468 case floor <= -8:
1469 return nativeHistogramSchemaMaximum
1470 case floor >= 4:
1471 return nativeHistogramSchemaMinimum
1472 default:
1473 return -int32(floor)
1474 }
1475 }
1476
1477 func makeBuckets(buckets *sync.Map) ([]*dto.BucketSpan, []int64) {
1478 var ii []int
1479 buckets.Range(func(k, v interface{}) bool {
1480 ii = append(ii, k.(int))
1481 return true
1482 })
1483 sort.Ints(ii)
1484
1485 if len(ii) == 0 {
1486 return nil, nil
1487 }
1488
1489 var (
1490 spans []*dto.BucketSpan
1491 deltas []int64
1492 prevCount int64
1493 nextI int
1494 )
1495
1496 appendDelta := func(count int64) {
1497 *spans[len(spans)-1].Length++
1498 deltas = append(deltas, count-prevCount)
1499 prevCount = count
1500 }
1501
1502 for n, i := range ii {
1503 v, _ := buckets.Load(i)
1504 count := atomic.LoadInt64(v.(*int64))
1505 // Multiple spans with only small gaps in between are probably
1506 // encoded more efficiently as one larger span with a few empty
1507 // buckets. Needs some research to find the sweet spot. For now,
1508 // we assume that gaps of one or two buckets should not create
1509 // a new span.
1510 iDelta := int32(i - nextI)
1511 if n == 0 || iDelta > 2 {
1512 // We have to create a new span, either because we are
1513 // at the very beginning, or because we have found a gap
1514 // of more than two buckets.
1515 spans = append(spans, &dto.BucketSpan{
1516 Offset: proto.Int32(iDelta),
1517 Length: proto.Uint32(0),
1518 })
1519 } else {
1520 // We have found a small gap (or no gap at all).
1521 // Insert empty buckets as needed.
1522 for j := int32(0); j < iDelta; j++ {
1523 appendDelta(0)
1524 }
1525 }
1526 appendDelta(count)
1527 nextI = i + 1
1528 }
1529 return spans, deltas
1530 }
1531
1532 // addToBucket increments the sparse bucket at key by the provided amount. It
1533 // returns true if a new sparse bucket had to be created for that.
1534 func addToBucket(buckets *sync.Map, key int, increment int64) bool {
1535 if existingBucket, ok := buckets.Load(key); ok {
1536 // Fast path without allocation.
1537 atomic.AddInt64(existingBucket.(*int64), increment)
1538 return false
1539 }
1540 // Bucket doesn't exist yet. Slow path allocating new counter.
1541 newBucket := increment // TODO(beorn7): Check if this is sufficient to not let increment escape.
1542 if actualBucket, loaded := buckets.LoadOrStore(key, &newBucket); loaded {
1543 // The bucket was created concurrently in another goroutine.
1544 // Have to increment after all.
1545 atomic.AddInt64(actualBucket.(*int64), increment)
1546 return false
1547 }
1548 return true
1549 }
1550
1551 // addAndReset returns a function to be used with sync.Map.Range of spare
1552 // buckets in coldCounts. It increments the buckets in the provided hotBuckets
1553 // according to the buckets ranged through. It then resets all buckets ranged
1554 // through to 0 (but leaves them in place so that they don't need to get
1555 // recreated on the next scrape).
1556 func addAndReset(hotBuckets *sync.Map, bucketNumber *uint32) func(k, v interface{}) bool {
1557 return func(k, v interface{}) bool {
1558 bucket := v.(*int64)
1559 if addToBucket(hotBuckets, k.(int), atomic.LoadInt64(bucket)) {
1560 atomic.AddUint32(bucketNumber, 1)
1561 }
1562 atomic.StoreInt64(bucket, 0)
1563 return true
1564 }
1565 }
1566
1567 func deleteSyncMap(m *sync.Map) {
1568 m.Range(func(k, v interface{}) bool {
1569 m.Delete(k)
1570 return true
1571 })
1572 }
1573
1574 func findSmallestKey(m *sync.Map) int {
1575 result := math.MaxInt32
1576 m.Range(func(k, v interface{}) bool {
1577 key := k.(int)
1578 if key < result {
1579 result = key
1580 }
1581 return true
1582 })
1583 return result
1584 }
1585
1586 func getLe(key int, schema int32) float64 {
1587 // Here a bit of context about the behavior for the last bucket counting
1588 // regular numbers (called simply "last bucket" below) and the bucket
1589 // counting observations of ±Inf (called "inf bucket" below, with a key
1590 // one higher than that of the "last bucket"):
1591 //
1592 // If we apply the usual formula to the last bucket, its upper bound
1593 // would be calculated as +Inf. The reason is that the max possible
1594 // regular float64 number (math.MaxFloat64) doesn't coincide with one of
1595 // the calculated bucket boundaries. So the calculated boundary has to
1596 // be larger than math.MaxFloat64, and the only float64 larger than
1597 // math.MaxFloat64 is +Inf. However, we want to count actual
1598 // observations of ±Inf in the inf bucket. Therefore, we have to treat
1599 // the upper bound of the last bucket specially and set it to
1600 // math.MaxFloat64. (The upper bound of the inf bucket, with its key
1601 // being one higher than that of the last bucket, naturally comes out as
1602 // +Inf by the usual formula. So that's fine.)
1603 //
1604 // math.MaxFloat64 has a frac of 0.9999999999999999 and an exp of
1605 // 1024. If there were a float64 number following math.MaxFloat64, it
1606 // would have a frac of 1.0 and an exp of 1024, or equivalently a frac
1607 // of 0.5 and an exp of 1025. However, since frac must be smaller than
1608 // 1, and exp must be smaller than 1025, either representation overflows
1609 // a float64. (Which, in turn, is the reason that math.MaxFloat64 is the
1610 // largest possible float64. Q.E.D.) However, the formula for
1611 // calculating the upper bound from the idx and schema of the last
1612 // bucket results in precisely that. It is either frac=1.0 & exp=1024
1613 // (for schema < 0) or frac=0.5 & exp=1025 (for schema >=0). (This is,
1614 // by the way, a power of two where the exponent itself is a power of
1615 // two, 2¹⁰ in fact, which coinicides with a bucket boundary in all
1616 // schemas.) So these are the special cases we have to catch below.
1617 if schema < 0 {
1618 exp := key << -schema
1619 if exp == 1024 {
1620 // This is the last bucket before the overflow bucket
1621 // (for ±Inf observations). Return math.MaxFloat64 as
1622 // explained above.
1623 return math.MaxFloat64
1624 }
1625 return math.Ldexp(1, exp)
1626 }
1627
1628 fracIdx := key & ((1 << schema) - 1)
1629 frac := nativeHistogramBounds[schema][fracIdx]
1630 exp := (key >> schema) + 1
1631 if frac == 0.5 && exp == 1025 {
1632 // This is the last bucket before the overflow bucket (for ±Inf
1633 // observations). Return math.MaxFloat64 as explained above.
1634 return math.MaxFloat64
1635 }
1636 return math.Ldexp(frac, exp)
1637 }
1638
1639 // waitForCooldown returns after the count field in the provided histogramCounts
1640 // has reached the provided count value.
1641 func waitForCooldown(count uint64, counts *histogramCounts) {
1642 for count != atomic.LoadUint64(&counts.count) {
1643 runtime.Gosched() // Let observations get work done.
1644 }
1645 }
1646
1647 // atomicAddFloat adds the provided float atomically to another float
1648 // represented by the bit pattern the bits pointer is pointing to.
1649 func atomicAddFloat(bits *uint64, v float64) {
1650 for {
1651 loadedBits := atomic.LoadUint64(bits)
1652 newBits := math.Float64bits(math.Float64frombits(loadedBits) + v)
1653 if atomic.CompareAndSwapUint64(bits, loadedBits, newBits) {
1654 break
1655 }
1656 }
1657 }
1658
1659 // atomicDecUint32 atomically decrements the uint32 p points to. See
1660 // https://pkg.go.dev/sync/atomic#AddUint32 to understand how this is done.
1661 func atomicDecUint32(p *uint32) {
1662 atomic.AddUint32(p, ^uint32(0))
1663 }
1664
1665 // addAndResetCounts adds certain fields (count, sum, conventional buckets, zero
1666 // bucket) from the cold counts to the corresponding fields in the hot
1667 // counts. Those fields are then reset to 0 in the cold counts.
1668 func addAndResetCounts(hot, cold *histogramCounts) {
1669 atomic.AddUint64(&hot.count, atomic.LoadUint64(&cold.count))
1670 atomic.StoreUint64(&cold.count, 0)
1671 coldSum := math.Float64frombits(atomic.LoadUint64(&cold.sumBits))
1672 atomicAddFloat(&hot.sumBits, coldSum)
1673 atomic.StoreUint64(&cold.sumBits, 0)
1674 for i := range hot.buckets {
1675 atomic.AddUint64(&hot.buckets[i], atomic.LoadUint64(&cold.buckets[i]))
1676 atomic.StoreUint64(&cold.buckets[i], 0)
1677 }
1678 atomic.AddUint64(&hot.nativeHistogramZeroBucket, atomic.LoadUint64(&cold.nativeHistogramZeroBucket))
1679 atomic.StoreUint64(&cold.nativeHistogramZeroBucket, 0)
1680 }
1681
1682 type nativeExemplars struct {
1683 sync.Mutex
1684
1685 // Time-to-live for exemplars, it is set to -1 if exemplars are disabled, that is NativeHistogramMaxExemplars is below 0.
1686 // The ttl is used on insertion to remove an exemplar that is older than ttl, if present.
1687 ttl time.Duration
1688
1689 exemplars []*dto.Exemplar
1690 }
1691
1692 func (n *nativeExemplars) isEnabled() bool {
1693 return n.ttl != -1
1694 }
1695
1696 func makeNativeExemplars(ttl time.Duration, maxCount int) nativeExemplars {
1697 if ttl == 0 {
1698 ttl = 5 * time.Minute
1699 }
1700
1701 if maxCount == 0 {
1702 maxCount = 10
1703 }
1704
1705 if maxCount < 0 {
1706 maxCount = 0
1707 ttl = -1
1708 }
1709
1710 return nativeExemplars{
1711 ttl: ttl,
1712 exemplars: make([]*dto.Exemplar, 0, maxCount),
1713 }
1714 }
1715
1716 func (n *nativeExemplars) addExemplar(e *dto.Exemplar) {
1717 if !n.isEnabled() {
1718 return
1719 }
1720
1721 n.Lock()
1722 defer n.Unlock()
1723
1724 // When the number of exemplars has not yet exceeded or
1725 // is equal to cap(n.exemplars), then
1726 // insert the new exemplar directly.
1727 if len(n.exemplars) < cap(n.exemplars) {
1728 var nIdx int
1729 for nIdx = 0; nIdx < len(n.exemplars); nIdx++ {
1730 if *e.Value < *n.exemplars[nIdx].Value {
1731 break
1732 }
1733 }
1734 n.exemplars = append(n.exemplars[:nIdx], append([]*dto.Exemplar{e}, n.exemplars[nIdx:]...)...)
1735 return
1736 }
1737
1738 if len(n.exemplars) == 1 {
1739 // When the number of exemplars is 1, then
1740 // replace the existing exemplar with the new exemplar.
1741 n.exemplars[0] = e
1742 return
1743 }
1744 // From this point on, the number of exemplars is greater than 1.
1745
1746 // When the number of exemplars exceeds the limit, remove one exemplar.
1747 var (
1748 ot = time.Time{} // Oldest timestamp seen. Initial value doesn't matter as we replace it due to otIdx == -1 in the loop.
1749 otIdx = -1 // Index of the exemplar with the oldest timestamp.
1750
1751 md = -1.0 // Logarithm of the delta of the closest pair of exemplars.
1752
1753 // The insertion point of the new exemplar in the exemplars slice after insertion.
1754 // This is calculated purely based on the order of the exemplars by value.
1755 // nIdx == len(n.exemplars) means the new exemplar is to be inserted after the end.
1756 nIdx = -1
1757
1758 // rIdx is ultimately the index for the exemplar that we are replacing with the new exemplar.
1759 // The aim is to keep a good spread of exemplars by value and not let them bunch up too much.
1760 // It is calculated in 3 steps:
1761 // 1. First we set rIdx to the index of the older exemplar within the closest pair by value.
1762 // That is the following will be true (on log scale):
1763 // either the exemplar pair on index (rIdx-1, rIdx) or (rIdx, rIdx+1) will have
1764 // the closest values to each other from all pairs.
1765 // For example, suppose the values are distributed like this:
1766 // |-----------x-------------x----------------x----x-----|
1767 // ^--rIdx as this is older.
1768 // Or like this:
1769 // |-----------x-------------x----------------x----x-----|
1770 // ^--rIdx as this is older.
1771 // 2. If there is an exemplar that expired, then we simple reset rIdx to that index.
1772 // 3. We check if by inserting the new exemplar we would create a closer pair at
1773 // (nIdx-1, nIdx) or (nIdx, nIdx+1) and set rIdx to nIdx-1 or nIdx accordingly to
1774 // keep the spread of exemplars by value; otherwise we keep rIdx as it is.
1775 rIdx = -1
1776 cLog float64 // Logarithm of the current exemplar.
1777 pLog float64 // Logarithm of the previous exemplar.
1778 )
1779
1780 for i, exemplar := range n.exemplars {
1781 // Find the exemplar with the oldest timestamp.
1782 if otIdx == -1 || exemplar.Timestamp.AsTime().Before(ot) {
1783 ot = exemplar.Timestamp.AsTime()
1784 otIdx = i
1785 }
1786
1787 // Find the index at which to insert new the exemplar.
1788 if nIdx == -1 && *e.Value <= *exemplar.Value {
1789 nIdx = i
1790 }
1791
1792 // Find the two closest exemplars and pick the one the with older timestamp.
1793 pLog = cLog
1794 cLog = math.Log(exemplar.GetValue())
1795 if i == 0 {
1796 continue
1797 }
1798 diff := math.Abs(cLog - pLog)
1799 if md == -1 || diff < md {
1800 // The closest exemplar pair is at index: i-1, i.
1801 // Choose the exemplar with the older timestamp for replacement.
1802 md = diff
1803 if n.exemplars[i].Timestamp.AsTime().Before(n.exemplars[i-1].Timestamp.AsTime()) {
1804 rIdx = i
1805 } else {
1806 rIdx = i - 1
1807 }
1808 }
1809
1810 }
1811
1812 // If all existing exemplar are smaller than new exemplar,
1813 // then the exemplar should be inserted at the end.
1814 if nIdx == -1 {
1815 nIdx = len(n.exemplars)
1816 }
1817 // Here, we have the following relationships:
1818 // n.exemplars[nIdx-1].Value < e.Value (if nIdx > 0)
1819 // e.Value <= n.exemplars[nIdx].Value (if nIdx < len(n.exemplars))
1820
1821 if otIdx != -1 && e.Timestamp.AsTime().Sub(ot) > n.ttl {
1822 // If the oldest exemplar has expired, then replace it with the new exemplar.
1823 rIdx = otIdx
1824 } else {
1825 // In the previous for loop, when calculating the closest pair of exemplars,
1826 // we did not take into account the newly inserted exemplar.
1827 // So we need to calculate with the newly inserted exemplar again.
1828 elog := math.Log(e.GetValue())
1829 if nIdx > 0 {
1830 diff := math.Abs(elog - math.Log(n.exemplars[nIdx-1].GetValue()))
1831 if diff < md {
1832 // The value we are about to insert is closer to the previous exemplar at the insertion point than what we calculated before in rIdx.
1833 // v--rIdx
1834 // |-----------x-n-----------x----------------x----x-----|
1835 // nIdx-1--^ ^--new exemplar value
1836 // Do not make the spread worse, replace nIdx-1 and not rIdx.
1837 md = diff
1838 rIdx = nIdx - 1
1839 }
1840 }
1841 if nIdx < len(n.exemplars) {
1842 diff := math.Abs(math.Log(n.exemplars[nIdx].GetValue()) - elog)
1843 if diff < md {
1844 // The value we are about to insert is closer to the next exemplar at the insertion point than what we calculated before in rIdx.
1845 // v--rIdx
1846 // |-----------x-----------n-x----------------x----x-----|
1847 // new exemplar value--^ ^--nIdx
1848 // Do not make the spread worse, replace nIdx-1 and not rIdx.
1849 rIdx = nIdx
1850 }
1851 }
1852 }
1853
1854 // Adjust the slice according to rIdx and nIdx.
1855 switch {
1856 case rIdx == nIdx:
1857 n.exemplars[nIdx] = e
1858 case rIdx < nIdx:
1859 n.exemplars = append(n.exemplars[:rIdx], append(n.exemplars[rIdx+1:nIdx], append([]*dto.Exemplar{e}, n.exemplars[nIdx:]...)...)...)
1860 case rIdx > nIdx:
1861 n.exemplars = append(n.exemplars[:nIdx], append([]*dto.Exemplar{e}, append(n.exemplars[nIdx:rIdx], n.exemplars[rIdx+1:]...)...)...)
1862 }
1863 }
1864
1865 type constNativeHistogram struct {
1866 desc *Desc
1867 dto.Histogram
1868 labelPairs []*dto.LabelPair
1869 }
1870
1871 func validateCount(sum float64, count uint64, negativeBuckets, positiveBuckets map[int]int64, zeroBucket uint64) error {
1872 var bucketPopulationSum int64
1873 for _, v := range positiveBuckets {
1874 bucketPopulationSum += v
1875 }
1876 for _, v := range negativeBuckets {
1877 bucketPopulationSum += v
1878 }
1879 bucketPopulationSum += int64(zeroBucket)
1880
1881 // If the sum of observations is NaN, the number of observations must be greater or equal to the sum of all bucket counts.
1882 // Otherwise, the number of observations must be equal to the sum of all bucket counts .
1883
1884 if math.IsNaN(sum) && bucketPopulationSum > int64(count) ||
1885 !math.IsNaN(sum) && bucketPopulationSum != int64(count) {
1886 return errors.New("the sum of all bucket populations exceeds the count of observations")
1887 }
1888 return nil
1889 }
1890
1891 // NewConstNativeHistogram returns a metric representing a Prometheus native histogram with
1892 // fixed values for the count, sum, and positive/negative/zero bucket counts. As those parameters
1893 // cannot be changed, the returned value does not implement the Histogram
1894 // interface (but only the Metric interface). Users of this package will not
1895 // have much use for it in regular operations. However, when implementing custom
1896 // OpenTelemetry Collectors, it is useful as a throw-away metric that is generated on the fly
1897 // to send it to Prometheus in the Collect method.
1898 //
1899 // zeroBucket counts all (positive and negative)
1900 // observations in the zero bucket (with an absolute value less or equal
1901 // the current threshold).
1902 // positiveBuckets and negativeBuckets are separate maps for negative and positive
1903 // observations. The map's value is an int64, counting observations in
1904 // that bucket. The map's key is the
1905 // index of the bucket according to the used
1906 // Schema. Index 0 is for an upper bound of 1 in positive buckets and for a lower bound of -1 in negative buckets.
1907 // NewConstNativeHistogram returns an error if
1908 // - the length of labelValues is not consistent with the variable labels in Desc or if Desc is invalid.
1909 // - the schema passed is not between 8 and -4
1910 // - the sum of counts in all buckets including the zero bucket does not equal the count if sum is not NaN (or exceeds the count if sum is NaN)
1911 //
1912 // See https://opentelemetry.io/docs/specs/otel/compatibility/prometheus_and_openmetrics/#exponential-histograms for more details about the conversion from OTel to Prometheus.
1913 func NewConstNativeHistogram(
1914 desc *Desc,
1915 count uint64,
1916 sum float64,
1917 positiveBuckets, negativeBuckets map[int]int64,
1918 zeroBucket uint64,
1919 schema int32,
1920 zeroThreshold float64,
1921 createdTimestamp time.Time,
1922 labelValues ...string,
1923 ) (Metric, error) {
1924 if desc.err != nil {
1925 return nil, desc.err
1926 }
1927 if err := validateLabelValues(labelValues, len(desc.variableLabels.names)); err != nil {
1928 return nil, err
1929 }
1930 if schema > nativeHistogramSchemaMaximum || schema < nativeHistogramSchemaMinimum {
1931 return nil, errors.New("invalid native histogram schema")
1932 }
1933 if err := validateCount(sum, count, negativeBuckets, positiveBuckets, zeroBucket); err != nil {
1934 return nil, err
1935 }
1936
1937 NegativeSpan, NegativeDelta := makeBucketsFromMap(negativeBuckets)
1938 PositiveSpan, PositiveDelta := makeBucketsFromMap(positiveBuckets)
1939 ret := &constNativeHistogram{
1940 desc: desc,
1941 Histogram: dto.Histogram{
1942 CreatedTimestamp: timestamppb.New(createdTimestamp),
1943 Schema: &schema,
1944 ZeroThreshold: &zeroThreshold,
1945 SampleCount: &count,
1946 SampleSum: &sum,
1947
1948 NegativeSpan: NegativeSpan,
1949 NegativeDelta: NegativeDelta,
1950
1951 PositiveSpan: PositiveSpan,
1952 PositiveDelta: PositiveDelta,
1953
1954 ZeroCount: proto.Uint64(zeroBucket),
1955 },
1956 labelPairs: MakeLabelPairs(desc, labelValues),
1957 }
1958 if *ret.ZeroThreshold == 0 && *ret.ZeroCount == 0 && len(ret.PositiveSpan) == 0 && len(ret.NegativeSpan) == 0 {
1959 ret.PositiveSpan = []*dto.BucketSpan{{
1960 Offset: proto.Int32(0),
1961 Length: proto.Uint32(0),
1962 }}
1963 }
1964 return ret, nil
1965 }
1966
1967 // MustNewConstNativeHistogram is a version of NewConstNativeHistogram that panics where
1968 // NewConstNativeHistogram would have returned an error.
1969 func MustNewConstNativeHistogram(
1970 desc *Desc,
1971 count uint64,
1972 sum float64,
1973 positiveBuckets, negativeBuckets map[int]int64,
1974 zeroBucket uint64,
1975 nativeHistogramSchema int32,
1976 nativeHistogramZeroThreshold float64,
1977 createdTimestamp time.Time,
1978 labelValues ...string,
1979 ) Metric {
1980 nativehistogram, err := NewConstNativeHistogram(desc,
1981 count,
1982 sum,
1983 positiveBuckets,
1984 negativeBuckets,
1985 zeroBucket,
1986 nativeHistogramSchema,
1987 nativeHistogramZeroThreshold,
1988 createdTimestamp,
1989 labelValues...)
1990 if err != nil {
1991 panic(err)
1992 }
1993 return nativehistogram
1994 }
1995
1996 func (h *constNativeHistogram) Desc() *Desc {
1997 return h.desc
1998 }
1999
2000 func (h *constNativeHistogram) Write(out *dto.Metric) error {
2001 out.Histogram = &h.Histogram
2002 out.Label = h.labelPairs
2003 return nil
2004 }
2005
2006 func makeBucketsFromMap(buckets map[int]int64) ([]*dto.BucketSpan, []int64) {
2007 if len(buckets) == 0 {
2008 return nil, nil
2009 }
2010 var ii []int
2011 for k := range buckets {
2012 ii = append(ii, k)
2013 }
2014 sort.Ints(ii)
2015
2016 var (
2017 spans []*dto.BucketSpan
2018 deltas []int64
2019 prevCount int64
2020 nextI int
2021 )
2022
2023 appendDelta := func(count int64) {
2024 *spans[len(spans)-1].Length++
2025 deltas = append(deltas, count-prevCount)
2026 prevCount = count
2027 }
2028
2029 for n, i := range ii {
2030 count := buckets[i]
2031 // Multiple spans with only small gaps in between are probably
2032 // encoded more efficiently as one larger span with a few empty
2033 // buckets. Needs some research to find the sweet spot. For now,
2034 // we assume that gaps of one or two buckets should not create
2035 // a new span.
2036 iDelta := int32(i - nextI)
2037 if n == 0 || iDelta > 2 {
2038 // We have to create a new span, either because we are
2039 // at the very beginning, or because we have found a gap
2040 // of more than two buckets.
2041 spans = append(spans, &dto.BucketSpan{
2042 Offset: proto.Int32(iDelta),
2043 Length: proto.Uint32(0),
2044 })
2045 } else {
2046 // We have found a small gap (or no gap at all).
2047 // Insert empty buckets as needed.
2048 for j := int32(0); j < iDelta; j++ {
2049 appendDelta(0)
2050 }
2051 }
2052 appendDelta(count)
2053 nextI = i + 1
2054 }
2055 return spans, deltas
2056 }