|
13 | 13 | # limitations under the License. |
14 | 14 | import logging |
15 | 15 | from os import environ |
16 | | -from typing import Dict, List |
| 16 | +from typing import Dict, List, Sequence |
17 | 17 |
|
18 | 18 | from opentelemetry.exporter.otlp.proto.common._internal import ( |
19 | 19 | _encode_attributes, |
|
43 | 43 | ) |
44 | 44 | from opentelemetry.sdk.metrics.export import ( |
45 | 45 | AggregationTemporality, |
| 46 | + ExponentialHistogram as ExponentialHistogramType, |
46 | 47 | Gauge, |
| 48 | + Histogram as HistogramType, |
47 | 49 | MetricExporter, |
48 | 50 | MetricsData, |
49 | 51 | Sum, |
@@ -167,6 +169,12 @@ def _get_aggregation( |
167 | 169 |
|
168 | 170 | return instrument_class_aggregation |
169 | 171 |
|
| 172 | +def truncate_trailing_zeros(lst: Sequence[int]) -> Sequence[int]: |
| 173 | + if lst: |
| 174 | + for i, value in enumerate(reversed(lst)): |
| 175 | + if value != 0: |
| 176 | + return lst[0:len(lst)-i] |
| 177 | + return [] |
170 | 178 |
|
171 | 179 | class EncodingException(Exception): |
172 | 180 | """ |
@@ -207,12 +215,17 @@ def encode_metrics(data: MetricsData) -> ExportMetricsServiceRequest: |
207 | 215 |
|
208 | 216 |
|
209 | 217 | def _encode_resource_metrics(resource_metrics, resource_metrics_dict): |
| 218 | + |
210 | 219 | resource = resource_metrics.resource |
| 220 | + |
211 | 221 | # It is safe to assume that each entry in data.resource_metrics is |
212 | 222 | # associated with an unique resource. |
213 | 223 | scope_metrics_dict = {} |
| 224 | + |
214 | 225 | resource_metrics_dict[resource] = scope_metrics_dict |
| 226 | + |
215 | 227 | for scope_metrics in resource_metrics.scope_metrics: |
| 228 | + |
216 | 229 | instrumentation_scope = scope_metrics.scope |
217 | 230 |
|
218 | 231 | # The SDK groups metrics in instrumentation scopes already so |
@@ -299,18 +312,19 @@ def _encode_metric(metric, pb2_metric): |
299 | 312 |
|
300 | 313 | elif isinstance(metric.data, ExponentialHistogramType): |
301 | 314 | for data_point in metric.data.data_points: |
302 | | - if data_point.positive.bucket_counts: |
| 315 | + |
| 316 | + if positive_buckets := truncate_trailing_zeros(data_point.positive.bucket_counts): |
303 | 317 | positive = pb2.ExponentialHistogramDataPoint.Buckets( |
304 | 318 | offset=data_point.positive.offset, |
305 | | - bucket_counts=data_point.positive.bucket_counts, |
| 319 | + bucket_counts=positive_buckets, |
306 | 320 | ) |
307 | 321 | else: |
308 | 322 | positive = None |
309 | 323 |
|
310 | | - if data_point.negative.bucket_counts: |
| 324 | + if negative_buckets := truncate_trailing_zeros(data_point.negative.bucket_counts): |
311 | 325 | negative = pb2.ExponentialHistogramDataPoint.Buckets( |
312 | 326 | offset=data_point.negative.offset, |
313 | | - bucket_counts=data_point.negative.bucket_counts, |
| 327 | + bucket_counts=negative_buckets, |
314 | 328 | ) |
315 | 329 | else: |
316 | 330 | negative = None |
|
0 commit comments