-
Notifications
You must be signed in to change notification settings - Fork 698
/
Copy pathaggregation.py
1474 lines (1230 loc) · 50.3 KB
/
aggregation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-lines
from abc import ABC, abstractmethod
from bisect import bisect_left
from enum import IntEnum
from functools import partial
from logging import getLogger
from math import inf
from threading import Lock
from typing import (
Callable,
Generic,
List,
Optional,
Sequence,
Type,
TypeVar,
)
from opentelemetry.metrics import (
Asynchronous,
Counter,
Histogram,
Instrument,
ObservableCounter,
ObservableGauge,
ObservableUpDownCounter,
Synchronous,
UpDownCounter,
_Gauge,
)
from opentelemetry.sdk.metrics._internal.exemplar import (
Exemplar,
ExemplarReservoirBuilder,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.buckets import (
Buckets,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping import (
Mapping,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.exponent_mapping import (
ExponentMapping,
)
from opentelemetry.sdk.metrics._internal.exponential_histogram.mapping.logarithm_mapping import (
LogarithmMapping,
)
from opentelemetry.sdk.metrics._internal.measurement import Measurement
from opentelemetry.sdk.metrics._internal.point import Buckets as BucketsPoint
from opentelemetry.sdk.metrics._internal.point import (
ExponentialHistogramDataPoint,
HistogramDataPoint,
NumberDataPoint,
Sum,
)
from opentelemetry.sdk.metrics._internal.point import Gauge as GaugePoint
from opentelemetry.sdk.metrics._internal.point import (
Histogram as HistogramPoint,
)
from opentelemetry.util.types import Attributes
_DataPointVarT = TypeVar("_DataPointVarT", NumberDataPoint, HistogramDataPoint)
_logger = getLogger(__name__)
class AggregationTemporality(IntEnum):
"""
The temporality to use when aggregating data.
Can be one of the following values:
"""
UNSPECIFIED = 0
DELTA = 1
CUMULATIVE = 2
class _Aggregation(ABC, Generic[_DataPointVarT]):
def __init__(
self,
attributes: Attributes,
reservoir_builder: ExemplarReservoirBuilder,
):
self._lock = Lock()
self._attributes = attributes
self._reservoir = reservoir_builder()
self._previous_point = None
@abstractmethod
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
) -> None:
"""Aggregate a measurement.
Args:
measurement: Measurement to aggregate
should_sample_exemplar: Whether the measurement should be sampled by the exemplars reservoir or not.
"""
@abstractmethod
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[_DataPointVarT]:
pass
def _collect_exemplars(self) -> Sequence[Exemplar]:
"""Returns the collected exemplars.
Returns:
The exemplars collected by the reservoir
"""
return self._reservoir.collect(self._attributes)
def _sample_exemplar(
self, measurement: Measurement, should_sample_exemplar: bool
) -> None:
"""Offer the measurement to the exemplar reservoir for sampling.
It should be called within the each :ref:`aggregate` call.
Args:
measurement: The new measurement
should_sample_exemplar: Whether the measurement should be sampled by the exemplars reservoir or not.
"""
if should_sample_exemplar:
self._reservoir.offer(
measurement.value,
measurement.time_unix_nano,
measurement.attributes,
measurement.context,
)
class _DropAggregation(_Aggregation):
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
) -> None:
pass
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[_DataPointVarT]:
pass
class _SumAggregation(_Aggregation[Sum]):
def __init__(
self,
attributes: Attributes,
instrument_is_monotonic: bool,
instrument_aggregation_temporality: AggregationTemporality,
start_time_unix_nano: int,
reservoir_builder: ExemplarReservoirBuilder,
):
super().__init__(attributes, reservoir_builder)
self._start_time_unix_nano = start_time_unix_nano
self._instrument_aggregation_temporality = (
instrument_aggregation_temporality
)
self._instrument_is_monotonic = instrument_is_monotonic
self._value = None
self._previous_collection_start_nano = self._start_time_unix_nano
self._previous_value = 0
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
) -> None:
with self._lock:
if self._value is None:
self._value = 0
self._value = self._value + measurement.value
self._sample_exemplar(measurement, should_sample_exemplar)
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[NumberDataPoint]:
"""
Atomically return a point for the current value of the metric and
reset the aggregation value.
Synchronous instruments have a method which is called directly with
increments for a given quantity:
For example, an instrument that counts the amount of passengers in
every vehicle that crosses a certain point in a highway:
synchronous_instrument.add(2)
collect(...) # 2 passengers are counted
synchronous_instrument.add(3)
collect(...) # 3 passengers are counted
synchronous_instrument.add(1)
collect(...) # 1 passenger is counted
In this case the instrument aggregation temporality is DELTA because
every value represents an increment to the count,
Asynchronous instruments have a callback which returns the total value
of a given quantity:
For example, an instrument that measures the amount of bytes written to
a certain hard drive:
callback() -> 1352
collect(...) # 1352 bytes have been written so far
callback() -> 2324
collect(...) # 2324 bytes have been written so far
callback() -> 4542
collect(...) # 4542 bytes have been written so far
In this case the instrument aggregation temporality is CUMULATIVE
because every value represents the total of the measurement.
There is also the collection aggregation temporality, which is passed
to this method. The collection aggregation temporality defines the
nature of the returned value by this aggregation.
When the collection aggregation temporality matches the
instrument aggregation temporality, then this method returns the
current value directly:
synchronous_instrument.add(2)
collect(DELTA) -> 2
synchronous_instrument.add(3)
collect(DELTA) -> 3
synchronous_instrument.add(1)
collect(DELTA) -> 1
callback() -> 1352
collect(CUMULATIVE) -> 1352
callback() -> 2324
collect(CUMULATIVE) -> 2324
callback() -> 4542
collect(CUMULATIVE) -> 4542
When the collection aggregation temporality does not match the
instrument aggregation temporality, then a conversion is made. For this
purpose, this aggregation keeps a private attribute,
self._previous_value.
When the instrument is synchronous:
self._previous_value is the sum of every previously
collected (delta) value. In this case, the returned (cumulative) value
will be:
self._previous_value + value
synchronous_instrument.add(2)
collect(CUMULATIVE) -> 2
synchronous_instrument.add(3)
collect(CUMULATIVE) -> 5
synchronous_instrument.add(1)
collect(CUMULATIVE) -> 6
Also, as a diagram:
time ->
self._previous_value
|-------------|
value (delta)
|----|
returned value (cumulative)
|------------------|
When the instrument is asynchronous:
self._previous_value is the value of the previously
collected (cumulative) value. In this case, the returned (delta) value
will be:
value - self._previous_value
callback() -> 1352
collect(DELTA) -> 1352
callback() -> 2324
collect(DELTA) -> 972
callback() -> 4542
collect(DELTA) -> 2218
Also, as a diagram:
time ->
self._previous_value
|-------------|
value (cumulative)
|------------------|
returned value (delta)
|----|
"""
with self._lock:
value = self._value
self._value = None
if (
self._instrument_aggregation_temporality
is AggregationTemporality.DELTA
):
# This happens when the corresponding instrument for this
# aggregation is synchronous.
if (
collection_aggregation_temporality
is AggregationTemporality.DELTA
):
previous_collection_start_nano = (
self._previous_collection_start_nano
)
self._previous_collection_start_nano = (
collection_start_nano
)
if value is None:
return None
return NumberDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=previous_collection_start_nano,
time_unix_nano=collection_start_nano,
value=value,
)
if value is None:
value = 0
self._previous_value = value + self._previous_value
return NumberDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=self._start_time_unix_nano,
time_unix_nano=collection_start_nano,
value=self._previous_value,
)
# This happens when the corresponding instrument for this
# aggregation is asynchronous.
if value is None:
# This happens when the corresponding instrument callback
# does not produce measurements.
return None
if (
collection_aggregation_temporality
is AggregationTemporality.DELTA
):
result_value = value - self._previous_value
self._previous_value = value
previous_collection_start_nano = (
self._previous_collection_start_nano
)
self._previous_collection_start_nano = collection_start_nano
return NumberDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=previous_collection_start_nano,
time_unix_nano=collection_start_nano,
value=result_value,
)
return NumberDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=self._start_time_unix_nano,
time_unix_nano=collection_start_nano,
value=value,
)
class _LastValueAggregation(_Aggregation[GaugePoint]):
def __init__(
self,
attributes: Attributes,
reservoir_builder: ExemplarReservoirBuilder,
):
super().__init__(attributes, reservoir_builder)
self._value = None
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
):
with self._lock:
self._value = measurement.value
self._sample_exemplar(measurement, should_sample_exemplar)
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[_DataPointVarT]:
"""
Atomically return a point for the current value of the metric.
"""
with self._lock:
if self._value is None:
return None
value = self._value
self._value = None
exemplars = self._collect_exemplars()
return NumberDataPoint(
attributes=self._attributes,
exemplars=exemplars,
start_time_unix_nano=None,
time_unix_nano=collection_start_nano,
value=value,
)
_DEFAULT_EXPLICIT_BUCKET_HISTOGRAM_AGGREGATION_BOUNDARIES: Sequence[float] = (
0.0,
5.0,
10.0,
25.0,
50.0,
75.0,
100.0,
250.0,
500.0,
750.0,
1000.0,
2500.0,
5000.0,
7500.0,
10000.0,
)
class _ExplicitBucketHistogramAggregation(_Aggregation[HistogramPoint]):
def __init__(
self,
attributes: Attributes,
instrument_aggregation_temporality: AggregationTemporality,
start_time_unix_nano: int,
reservoir_builder: ExemplarReservoirBuilder,
boundaries: Optional[Sequence[float]] = None,
record_min_max: bool = True,
):
if boundaries is None:
boundaries = (
_DEFAULT_EXPLICIT_BUCKET_HISTOGRAM_AGGREGATION_BOUNDARIES
)
super().__init__(
attributes,
reservoir_builder=partial(
reservoir_builder, boundaries=boundaries
),
)
self._instrument_aggregation_temporality = (
instrument_aggregation_temporality
)
self._start_time_unix_nano = start_time_unix_nano
self._boundaries = tuple(boundaries)
self._record_min_max = record_min_max
self._value = None
self._min = inf
self._max = -inf
self._sum = 0
self._previous_value = None
self._previous_min = inf
self._previous_max = -inf
self._previous_sum = 0
self._previous_collection_start_nano = self._start_time_unix_nano
def _get_empty_bucket_counts(self) -> List[int]:
return [0] * (len(self._boundaries) + 1)
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
) -> None:
with self._lock:
if self._value is None:
self._value = self._get_empty_bucket_counts()
measurement_value = measurement.value
self._sum += measurement_value
if self._record_min_max:
self._min = min(self._min, measurement_value)
self._max = max(self._max, measurement_value)
self._value[bisect_left(self._boundaries, measurement_value)] += 1
self._sample_exemplar(measurement, should_sample_exemplar)
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[_DataPointVarT]:
"""
Atomically return a point for the current value of the metric.
"""
with self._lock:
value = self._value
sum_ = self._sum
min_ = self._min
max_ = self._max
self._value = None
self._sum = 0
self._min = inf
self._max = -inf
if (
self._instrument_aggregation_temporality
is AggregationTemporality.DELTA
):
# This happens when the corresponding instrument for this
# aggregation is synchronous.
if (
collection_aggregation_temporality
is AggregationTemporality.DELTA
):
previous_collection_start_nano = (
self._previous_collection_start_nano
)
self._previous_collection_start_nano = (
collection_start_nano
)
if value is None:
return None
return HistogramDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=previous_collection_start_nano,
time_unix_nano=collection_start_nano,
count=sum(value),
sum=sum_,
bucket_counts=tuple(value),
explicit_bounds=self._boundaries,
min=min_,
max=max_,
)
if value is None:
value = self._get_empty_bucket_counts()
if self._previous_value is None:
self._previous_value = self._get_empty_bucket_counts()
self._previous_value = [
value_element + previous_value_element
for (
value_element,
previous_value_element,
) in zip(value, self._previous_value)
]
self._previous_min = min(min_, self._previous_min)
self._previous_max = max(max_, self._previous_max)
self._previous_sum = sum_ + self._previous_sum
return HistogramDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=self._start_time_unix_nano,
time_unix_nano=collection_start_nano,
count=sum(self._previous_value),
sum=self._previous_sum,
bucket_counts=tuple(self._previous_value),
explicit_bounds=self._boundaries,
min=self._previous_min,
max=self._previous_max,
)
return None
# pylint: disable=protected-access
class _ExponentialBucketHistogramAggregation(_Aggregation[HistogramPoint]):
# _min_max_size and _max_max_size are the smallest and largest values
# the max_size parameter may have, respectively.
# _min_max_size is is the smallest reasonable value which is small enough
# to contain the entire normal floating point range at the minimum scale.
_min_max_size = 2
# _max_max_size is an arbitrary limit meant to limit accidental creation of
# giant exponential bucket histograms.
_max_max_size = 16384
def __init__(
self,
attributes: Attributes,
reservoir_builder: ExemplarReservoirBuilder,
instrument_aggregation_temporality: AggregationTemporality,
start_time_unix_nano: int,
# This is the default maximum number of buckets per positive or
# negative number range. The value 160 is specified by OpenTelemetry.
# See the derivation here:
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exponential-bucket-histogram-aggregation)
max_size: int = 160,
max_scale: int = 20,
):
# max_size is the maximum capacity of the positive and negative
# buckets.
# _sum is the sum of all the values aggregated by this aggregator.
# _count is the count of all calls to aggregate.
# _zero_count is the count of all the calls to aggregate when the value
# to be aggregated is exactly 0.
# _min is the smallest value aggregated by this aggregator.
# _max is the smallest value aggregated by this aggregator.
# _positive holds the positive values.
# _negative holds the negative values by their absolute value.
if max_size < self._min_max_size:
raise ValueError(
f"Buckets max size {max_size} is smaller than "
"minimum max size {self._min_max_size}"
)
if max_size > self._max_max_size:
raise ValueError(
f"Buckets max size {max_size} is larger than "
"maximum max size {self._max_max_size}"
)
if max_scale > 20:
_logger.warning(
"max_scale is set to %s which is "
"larger than the recommended value of 20",
max_scale,
)
# This aggregation is analogous to _ExplicitBucketHistogramAggregation,
# the only difference is that with every call to aggregate, the size
# and amount of buckets can change (in
# _ExplicitBucketHistogramAggregation both size and amount of buckets
# remain constant once it is instantiated).
super().__init__(
attributes,
reservoir_builder=partial(
reservoir_builder, size=min(20, max_size)
),
)
self._instrument_aggregation_temporality = (
instrument_aggregation_temporality
)
self._start_time_unix_nano = start_time_unix_nano
self._max_size = max_size
self._max_scale = max_scale
self._value_positive = None
self._value_negative = None
self._min = inf
self._max = -inf
self._sum = 0
self._count = 0
self._zero_count = 0
self._scale = None
self._previous_value_positive = None
self._previous_value_negative = None
self._previous_min = inf
self._previous_max = -inf
self._previous_sum = 0
self._previous_count = 0
self._previous_zero_count = 0
self._previous_scale = None
self._previous_collection_start_nano = self._start_time_unix_nano
self._mapping = self._new_mapping(self._max_scale)
def aggregate(
self, measurement: Measurement, should_sample_exemplar: bool = True
) -> None:
# pylint: disable=too-many-branches,too-many-statements, too-many-locals
with self._lock:
if self._value_positive is None:
self._value_positive = Buckets()
if self._value_negative is None:
self._value_negative = Buckets()
measurement_value = measurement.value
self._sum += measurement_value
self._min = min(self._min, measurement_value)
self._max = max(self._max, measurement_value)
self._count += 1
if measurement_value == 0:
self._zero_count += 1
if self._count == self._zero_count:
self._scale = 0
return
if measurement_value > 0:
value = self._value_positive
else:
measurement_value = -measurement_value
value = self._value_negative
# The following code finds out if it is necessary to change the
# buckets to hold the incoming measurement_value, changes them if
# necessary. This process does not exist in
# _ExplicitBucketHistogram aggregation because the buckets there
# are constant in size and amount.
index = self._mapping.map_to_index(measurement_value)
is_rescaling_needed = False
low, high = 0, 0
if len(value) == 0:
value.index_start = index
value.index_end = index
value.index_base = index
elif (
index < value.index_start
and (value.index_end - index) >= self._max_size
):
is_rescaling_needed = True
low = index
high = value.index_end
elif (
index > value.index_end
and (index - value.index_start) >= self._max_size
):
is_rescaling_needed = True
low = value.index_start
high = index
if is_rescaling_needed:
scale_change = self._get_scale_change(low, high)
self._downscale(
scale_change,
self._value_positive,
self._value_negative,
)
self._mapping = self._new_mapping(
self._mapping.scale - scale_change
)
index = self._mapping.map_to_index(measurement_value)
self._scale = self._mapping.scale
if index < value.index_start:
span = value.index_end - index
if span >= len(value.counts):
value.grow(span + 1, self._max_size)
value.index_start = index
elif index > value.index_end:
span = index - value.index_start
if span >= len(value.counts):
value.grow(span + 1, self._max_size)
value.index_end = index
bucket_index = index - value.index_base
if bucket_index < 0:
bucket_index += len(value.counts)
# Now the buckets have been changed if needed and bucket_index will
# be used to increment the counter of the bucket that needs to be
# incremented.
# This is analogous to
# self._value[bisect_left(self._boundaries, measurement_value)] += 1
# in _ExplicitBucketHistogramAggregation.aggregate
value.increment_bucket(bucket_index)
self._sample_exemplar(measurement, should_sample_exemplar)
def collect(
self,
collection_aggregation_temporality: AggregationTemporality,
collection_start_nano: int,
) -> Optional[_DataPointVarT]:
"""
Atomically return a point for the current value of the metric.
"""
# pylint: disable=too-many-statements, too-many-locals
with self._lock:
value_positive = self._value_positive
value_negative = self._value_negative
sum_ = self._sum
min_ = self._min
max_ = self._max
count = self._count
zero_count = self._zero_count
scale = self._scale
self._value_positive = None
self._value_negative = None
self._sum = 0
self._min = inf
self._max = -inf
self._count = 0
self._zero_count = 0
self._scale = None
if (
self._instrument_aggregation_temporality
is AggregationTemporality.DELTA
):
# This happens when the corresponding instrument for this
# aggregation is synchronous.
if (
collection_aggregation_temporality
is AggregationTemporality.DELTA
):
previous_collection_start_nano = (
self._previous_collection_start_nano
)
self._previous_collection_start_nano = (
collection_start_nano
)
if value_positive is None and value_negative is None:
return None
return ExponentialHistogramDataPoint(
attributes=self._attributes,
exemplars=self._collect_exemplars(),
start_time_unix_nano=previous_collection_start_nano,
time_unix_nano=collection_start_nano,
count=count,
sum=sum_,
scale=scale,
zero_count=zero_count,
positive=BucketsPoint(
offset=value_positive.offset,
bucket_counts=(value_positive.get_offset_counts()),
),
negative=BucketsPoint(
offset=value_negative.offset,
bucket_counts=(value_negative.get_offset_counts()),
),
# FIXME: Find the right value for flags
flags=0,
min=min_,
max=max_,
)
# Here collection_temporality is CUMULATIVE.
# instrument_temporality is always DELTA for the time being.
# Here we need to handle the case where:
# collect is called after at least one other call to collect
# (there is data in previous buckets, a call to merge is needed
# to handle possible differences in bucket sizes).
# collect is called without another call previous call to
# collect was made (there is no previous buckets, previous,
# empty buckets that are the same scale of the current buckets
# need to be made so that they can be cumulatively aggregated
# to the current buckets).
if (
value_positive is None
and self._previous_value_positive is None
):
# This happens if collect is called for the first time
# and aggregate has not yet been called.
value_positive = Buckets()
self._previous_value_positive = value_positive.copy_empty()
if (
value_negative is None
and self._previous_value_negative is None
):
value_negative = Buckets()
self._previous_value_negative = value_negative.copy_empty()
if scale is None and self._previous_scale is None:
scale = self._mapping.scale
self._previous_scale = scale
if (
value_positive is not None
and self._previous_value_positive is None
):
# This happens when collect is called the very first time
# and aggregate has been called before.
# We need previous buckets to add them to the current ones.
# When collect is called for the first time, there are no
# previous buckets, so we need to create empty buckets to
# add them to the current ones. The addition of empty
# buckets to the current ones will result in the current
# ones unchanged.
# The way the previous buckets are generated here is
# different from the explicit bucket histogram where
# the size and amount of the buckets does not change once
# they are instantiated. Here, the size and amount of the
# buckets can change with every call to aggregate. In order
# to get empty buckets that can be added to the current
# ones resulting in the current ones unchanged we need to
# generate empty buckets that have the same size and amount
# as the current ones, this is what copy_empty does.
self._previous_value_positive = value_positive.copy_empty()
if (
value_negative is not None
and self._previous_value_negative is None
):
self._previous_value_negative = value_negative.copy_empty()
if scale is not None and self._previous_scale is None:
self._previous_scale = scale
if (
value_positive is None
and self._previous_value_positive is not None
):
value_positive = self._previous_value_positive.copy_empty()
if (
value_negative is None
and self._previous_value_negative is not None
):
value_negative = self._previous_value_negative.copy_empty()
if scale is None and self._previous_scale is not None:
scale = self._previous_scale
min_scale = min(self._previous_scale, scale)
low_positive, high_positive = (
self._get_low_high_previous_current(
self._previous_value_positive,
value_positive,
scale,
min_scale,
)
)
low_negative, high_negative = (
self._get_low_high_previous_current(
self._previous_value_negative,
value_negative,
scale,
min_scale,
)
)
min_scale = min(
min_scale
- self._get_scale_change(low_positive, high_positive),
min_scale
- self._get_scale_change(low_negative, high_negative),
)
self._downscale(
self._previous_scale - min_scale,
self._previous_value_positive,
self._previous_value_negative,