-
Notifications
You must be signed in to change notification settings - Fork 636
/
exemplar_reservoir.py
321 lines (266 loc) · 10.3 KB
/
exemplar_reservoir.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
# 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.
from abc import ABC, abstractmethod
from random import randrange
from typing import Any, Callable, Dict, List, Optional, Sequence, Union
from opentelemetry import trace
from opentelemetry.context import Context
from opentelemetry.trace.span import INVALID_SPAN
from opentelemetry.util.types import Attributes
from .exemplar import Exemplar
class ExemplarReservoir(ABC):
"""ExemplarReservoir provide a method to offer measurements to the reservoir
and another to collect accumulated Exemplars.
Note:
The constructor MUST accept ``**kwargs`` that may be set from aggregation
parameters.
Reference:
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exemplarreservoir
"""
@abstractmethod
def offer(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> None:
"""Offers a measurement to be sampled.
Args:
value: Measured value
time_unix_nano: Measurement instant
attributes: Measurement attributes
context: Measurement context
"""
raise NotImplementedError("ExemplarReservoir.offer is not implemented")
@abstractmethod
def collect(self, point_attributes: Attributes) -> List[Exemplar]:
"""Returns accumulated Exemplars and also resets the reservoir for the next
sampling period
Args:
point_attributes: The attributes associated with metric point.
Returns:
a list of ``opentelemetry.sdk.metrics._internal.exemplar.exemplar.Exemplar`` s. Returned
exemplars contain the attributes that were filtered out by the aggregator,
but recorded alongside the original measurement.
"""
raise NotImplementedError(
"ExemplarReservoir.collect is not implemented"
)
class ExemplarBucket:
def __init__(self) -> None:
self.__value: Union[int, float] = 0
self.__attributes: Attributes = None
self.__time_unix_nano: int = 0
self.__span_id: Optional[int] = None
self.__trace_id: Optional[int] = None
self.__offered: bool = False
def offer(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> None:
"""Offers a measurement to be sampled.
Args:
value: Measured value
time_unix_nano: Measurement instant
attributes: Measurement attributes
context: Measurement context
"""
self.__value = value
self.__time_unix_nano = time_unix_nano
self.__attributes = attributes
span = trace.get_current_span(context)
if span != INVALID_SPAN:
span_context = span.get_span_context()
self.__span_id = span_context.span_id
self.__trace_id = span_context.trace_id
self.__offered = True
def collect(self, point_attributes: Attributes) -> Optional[Exemplar]:
"""May return an Exemplar and resets the bucket for the next sampling period."""
if not self.__offered:
return None
# filters out attributes from the measurement that are already included in the metric data point
# See the specification for more details:
# https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#exemplar
filtered_attributes = (
{
k: v
for k, v in self.__attributes.items()
if k not in point_attributes
}
if self.__attributes
else None
)
exemplar = Exemplar(
filtered_attributes,
self.__value,
self.__time_unix_nano,
self.__span_id,
self.__trace_id,
)
self.__reset()
return exemplar
def __reset(self) -> None:
"""Reset the bucket state after a collection cycle."""
self.__value = 0
self.__attributes = {}
self.__time_unix_nano = 0
self.__span_id = None
self.__trace_id = None
self.__offered = False
class BucketIndexError(ValueError):
"""An exception raised when the bucket index cannot be found."""
class FixedSizeExemplarReservoirABC(ExemplarReservoir):
"""Abstract class for a reservoir with fixed size."""
def __init__(self, size: int, **kwargs) -> None:
super().__init__(**kwargs)
self._size: int = size
self._reservoir_storage: List[ExemplarBucket] = [
ExemplarBucket() for _ in range(self._size)
]
def collect(self, point_attributes: Attributes) -> List[Exemplar]:
"""Returns accumulated Exemplars and also resets the reservoir for the next
sampling period
Args:
point_attributes: The attributes associated with metric point.
Returns:
a list of ``opentelemetry.sdk.metrics._internal.exemplar.exemplar.Exemplar`` s. Returned
exemplars contain the attributes that were filtered out by the aggregator,
but recorded alongside the original measurement.
"""
exemplars = filter(
lambda e: e is not None,
map(
lambda bucket: bucket.collect(point_attributes),
self._reservoir_storage,
),
)
self._reset()
return [*exemplars]
def offer(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> None:
"""Offers a measurement to be sampled.
Args:
value: Measured value
time_unix_nano: Measurement instant
attributes: Measurement attributes
context: Measurement context
"""
try:
index = self._find_bucket_index(
value, time_unix_nano, attributes, context
)
self._reservoir_storage[index].offer(
value, time_unix_nano, attributes, context
)
except BucketIndexError:
# Ignore invalid bucket index
pass
@abstractmethod
def _find_bucket_index(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> int:
"""Determines the bucket index for the given measurement.
It should be implemented by subclasses based on specific strategies.
Args:
value: Measured value
time_unix_nano: Measurement instant
attributes: Measurement attributes
context: Measurement context
Returns:
The bucket index
Raises:
BucketIndexError: If no bucket index can be found.
"""
def _reset(self) -> None:
"""Reset the reservoir by resetting any stateful logic after a collection cycle."""
class SimpleFixedSizeExemplarReservoir(FixedSizeExemplarReservoirABC):
"""This reservoir uses an uniformly-weighted sampling algorithm based on the number
of samples the reservoir has seen so far to determine if the offered measurements
should be sampled.
Reference:
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#simplefixedsizeexemplarreservoir
"""
def __init__(self, size: int = 1, **kwargs) -> None:
super().__init__(size, **kwargs)
self._measurements_seen: int = 0
def _reset(self) -> None:
super()._reset()
self._measurements_seen = 0
def _find_bucket_index(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> int:
self._measurements_seen += 1
if self._measurements_seen < self._size:
return self._measurements_seen - 1
index = randrange(0, self._measurements_seen)
if index < self._size:
return index
raise BucketIndexError("Unable to find the bucket index.")
class AlignedHistogramBucketExemplarReservoir(FixedSizeExemplarReservoirABC):
"""This Exemplar reservoir takes a configuration parameter that is the
configuration of a Histogram. This implementation keeps the last seen measurement
that falls within a histogram bucket.
Reference:
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#alignedhistogrambucketexemplarreservoir
"""
def __init__(self, boundaries: Sequence[float], **kwargs) -> None:
super().__init__(len(boundaries) + 1, **kwargs)
self._boundaries: Sequence[float] = boundaries
def offer(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> None:
"""Offers a measurement to be sampled."""
index = self._find_bucket_index(
value, time_unix_nano, attributes, context
)
self._reservoir_storage[index].offer(
value, time_unix_nano, attributes, context
)
def _find_bucket_index(
self,
value: Union[int, float],
time_unix_nano: int,
attributes: Attributes,
context: Context,
) -> int:
for index, boundary in enumerate(self._boundaries):
if value <= boundary:
return index
return len(self._boundaries)
ExemplarReservoirBuilder = Callable[[Dict[str, Any]], ExemplarReservoir]
ExemplarReservoirBuilder.__doc__ = """ExemplarReservoir builder.
It may receive the Aggregation parameters it is bounded to; e.g.
the _ExplicitBucketHistogramAggregation will provide the boundaries.
"""