|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import math |
| 5 | +import threading |
| 6 | +import time |
| 7 | +from typing import Optional, Sequence |
| 8 | +from opentelemetry.context import Context |
| 9 | +from opentelemetry.trace import Link, SpanKind, format_trace_id |
| 10 | +from opentelemetry.sdk.trace.sampling import ( |
| 11 | + Decision, |
| 12 | + Sampler, |
| 13 | + SamplingResult, |
| 14 | + _get_parent_trace_state, |
| 15 | +) |
| 16 | +from opentelemetry.trace.span import TraceState |
| 17 | +from opentelemetry.util.types import Attributes |
| 18 | + |
| 19 | +from azure.monitor.opentelemetry.exporter._constants import _SAMPLE_RATE_KEY |
| 20 | + |
| 21 | +from azure.monitor.opentelemetry.exporter.export.trace._utils import ( |
| 22 | + _get_DJB2_sample_score, |
| 23 | + _round_down_to_nearest, |
| 24 | + parent_context_sampling, |
| 25 | +) |
| 26 | + |
| 27 | +class _State: |
| 28 | + def __init__(self, effective_window_count: float, effective_window_nanoseconds: float, last_nano_time: int): |
| 29 | + self.effective_window_count = effective_window_count |
| 30 | + self.effective_window_nanoseconds = effective_window_nanoseconds |
| 31 | + self.last_nano_time = last_nano_time |
| 32 | + |
| 33 | +class RateLimitedSamplingPercentage: |
| 34 | + def __init__(self, target_spans_per_second_limit: float, round_to_nearest: bool = True): |
| 35 | + if target_spans_per_second_limit < 0.0: |
| 36 | + raise ValueError("Limit for sampled spans per second must be nonnegative!") |
| 37 | + # Hardcoded adaptation time of 0.1 seconds for adjusting to sudden changes in telemetry volumes |
| 38 | + adaptation_time_seconds = 0.1 |
| 39 | + self._inverse_adaptation_time_nanoseconds = 1e-9 / adaptation_time_seconds |
| 40 | + self._target_spans_per_nanosecond_limit = 1e-9 * target_spans_per_second_limit |
| 41 | + initial_nano_time = int(time.time_ns()) |
| 42 | + self._state = _State(0.0, 0.0, initial_nano_time) |
| 43 | + self._lock = threading.Lock() |
| 44 | + self._round_to_nearest = round_to_nearest |
| 45 | + |
| 46 | + def _update_state(self, old_state: _State, current_nano_time: int) -> _State: |
| 47 | + if current_nano_time <= old_state.last_nano_time: |
| 48 | + return _State( |
| 49 | + old_state.effective_window_count + 1, |
| 50 | + old_state.effective_window_nanoseconds, |
| 51 | + old_state.last_nano_time |
| 52 | + ) |
| 53 | + nano_time_delta = current_nano_time - old_state.last_nano_time |
| 54 | + decay_factor = math.exp(-nano_time_delta * self._inverse_adaptation_time_nanoseconds) |
| 55 | + current_effective_window_count = old_state.effective_window_count * decay_factor + 1 |
| 56 | + current_effective_window_nanoseconds = old_state.effective_window_nanoseconds * decay_factor + nano_time_delta |
| 57 | + |
| 58 | + return _State(current_effective_window_count, current_effective_window_nanoseconds, current_nano_time) |
| 59 | + |
| 60 | + def get(self) -> float: |
| 61 | + current_nano_time = int(time.time_ns()) |
| 62 | + |
| 63 | + with self._lock: |
| 64 | + old_state = self._state |
| 65 | + self._state = self._update_state(old_state, current_nano_time) |
| 66 | + current_state = self._state |
| 67 | + |
| 68 | + # Calculate sampling probability based on current state |
| 69 | + if current_state.effective_window_count == 0: |
| 70 | + return 100.0 |
| 71 | + |
| 72 | + sampling_probability = ( |
| 73 | + (current_state.effective_window_nanoseconds * self._target_spans_per_nanosecond_limit) / |
| 74 | + current_state.effective_window_count |
| 75 | + ) |
| 76 | + |
| 77 | + sampling_percentage = 100 * min(sampling_probability, 1.0) |
| 78 | + |
| 79 | + if self._round_to_nearest: |
| 80 | + sampling_percentage = _round_down_to_nearest(sampling_percentage) |
| 81 | + |
| 82 | + return sampling_percentage |
| 83 | + |
| 84 | + |
| 85 | +class RateLimitedSampler(Sampler): |
| 86 | + def __init__(self, target_spans_per_second_limit: float): |
| 87 | + self._sampling_percentage_generator = RateLimitedSamplingPercentage(target_spans_per_second_limit) |
| 88 | + self._description = f"RateLimitedSampler{{{target_spans_per_second_limit}}}" |
| 89 | + |
| 90 | + def should_sample( |
| 91 | + self, |
| 92 | + parent_context: Optional[Context], |
| 93 | + trace_id: int, |
| 94 | + name: str, |
| 95 | + kind: Optional[SpanKind] = None, |
| 96 | + attributes: Attributes = None, |
| 97 | + links: Optional[Sequence["Link"]] = None, |
| 98 | + trace_state: Optional["TraceState"] = None, |
| 99 | + ) -> "SamplingResult": |
| 100 | + |
| 101 | + if parent_context is not None: |
| 102 | + parent_result = parent_context_sampling(parent_context, attributes) |
| 103 | + if parent_result is not None: |
| 104 | + return parent_result |
| 105 | + |
| 106 | + sampling_percentage = self._sampling_percentage_generator.get() |
| 107 | + sampling_score = _get_DJB2_sample_score(format_trace_id(trace_id).lower()) * 100.0 |
| 108 | + |
| 109 | + if sampling_score < sampling_percentage: |
| 110 | + decision = Decision.RECORD_AND_SAMPLE |
| 111 | + else: |
| 112 | + decision = Decision.DROP |
| 113 | + |
| 114 | + if sampling_percentage == 100.0: |
| 115 | + new_attributes = {} |
| 116 | + else: |
| 117 | + new_attributes = {} if attributes is None else dict(attributes) |
| 118 | + new_attributes[_SAMPLE_RATE_KEY] = sampling_percentage |
| 119 | + |
| 120 | + return SamplingResult( |
| 121 | + decision, |
| 122 | + new_attributes, |
| 123 | + _get_parent_trace_state(parent_context), |
| 124 | + ) |
| 125 | + |
| 126 | + def get_description(self) -> str: |
| 127 | + return self._description |
0 commit comments