|
| 1 | +"""OpenTelemetry metrics exporter built on :py:class:`temporalio.runtime.MetricBuffer`.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import contextlib |
| 5 | +import logging |
| 6 | +import threading |
| 7 | +from collections.abc import Callable, Iterable, Mapping |
| 8 | +from dataclasses import dataclass, field |
| 9 | +from datetime import timedelta |
| 10 | + |
| 11 | +import opentelemetry.metrics |
| 12 | +import opentelemetry.util.types |
| 13 | + |
| 14 | +import temporalio.common |
| 15 | +import temporalio.runtime |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class _GaugeState: |
| 22 | + lock: threading.Lock = field(default_factory=threading.Lock) |
| 23 | + # Keyed by id(BufferedMetricUpdate.attributes) so repeated updates for the |
| 24 | + # same attribute set overwrite rather than accumulate -- gauges are |
| 25 | + # "latest value wins", unlike counters. |
| 26 | + last_values: dict[ |
| 27 | + int, tuple[Mapping[str, opentelemetry.util.types.AttributeValue], int | float] |
| 28 | + ] = field(default_factory=dict) |
| 29 | + |
| 30 | + |
| 31 | +@dataclass |
| 32 | +class _Instrument: |
| 33 | + kind: temporalio.runtime.BufferedMetricKind |
| 34 | + counter: opentelemetry.metrics.Counter | None = None |
| 35 | + histogram: opentelemetry.metrics.Histogram | None = None |
| 36 | + gauge_state: "_GaugeState | None" = None |
| 37 | + |
| 38 | + |
| 39 | +def _make_gauge_callback( |
| 40 | + state: _GaugeState, |
| 41 | +) -> Callable[ |
| 42 | + [opentelemetry.metrics.CallbackOptions], |
| 43 | + Iterable[opentelemetry.metrics.Observation], |
| 44 | +]: |
| 45 | + # OTel invokes observable-gauge callbacks from its own export thread, which |
| 46 | + # runs concurrently with the drain loop mutating last_values -- hence the |
| 47 | + # lock on both sides. |
| 48 | + def callback( |
| 49 | + options: opentelemetry.metrics.CallbackOptions, |
| 50 | + ) -> Iterable[opentelemetry.metrics.Observation]: |
| 51 | + with state.lock: |
| 52 | + return [ |
| 53 | + opentelemetry.metrics.Observation(value, attributes=dict(attrs)) |
| 54 | + for attrs, value in state.last_values.values() |
| 55 | + ] |
| 56 | + |
| 57 | + return callback |
| 58 | + |
| 59 | + |
| 60 | +class MetricsExporter: |
| 61 | + """Exports metrics recorded via a :py:class:`temporalio.runtime.MetricBuffer` |
| 62 | + to an OpenTelemetry :py:class:`opentelemetry.metrics.MeterProvider`. |
| 63 | +
|
| 64 | + .. warning:: |
| 65 | + This class is experimental and may change in future versions. |
| 66 | + Use with caution in production environments. |
| 67 | +
|
| 68 | + This must be started (via :py:meth:`run` or ``async with``) after the |
| 69 | + :py:class:`temporalio.runtime.Runtime` referencing ``buffer`` has been |
| 70 | + constructed, and it must be kept running for as long as metrics should be |
| 71 | + exported. It drains the buffer on a fixed interval; per |
| 72 | + :py:class:`temporalio.runtime.MetricBuffer`, updates are dropped (with an |
| 73 | + error logged by Core) if the buffer is not drained regularly. |
| 74 | +
|
| 75 | + Example: |
| 76 | +
|
| 77 | + .. code-block:: python |
| 78 | +
|
| 79 | + from datetime import timedelta |
| 80 | +
|
| 81 | + from opentelemetry.sdk.metrics import MeterProvider |
| 82 | + from opentelemetry.sdk.metrics.export import ( |
| 83 | + ConsoleMetricExporter, |
| 84 | + PeriodicExportingMetricReader, |
| 85 | + ) |
| 86 | +
|
| 87 | + from temporalio.client import Client |
| 88 | + from temporalio.contrib.opentelemetry import MetricsExporter |
| 89 | + from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfig |
| 90 | +
|
| 91 | + buffer = MetricBuffer(10_000) |
| 92 | + runtime = Runtime(telemetry=TelemetryConfig(metrics=buffer)) |
| 93 | + meter_provider = MeterProvider( |
| 94 | + metric_readers=[ |
| 95 | + PeriodicExportingMetricReader( |
| 96 | + ConsoleMetricExporter(), export_interval_millis=5000 |
| 97 | + ) |
| 98 | + ] |
| 99 | + ) |
| 100 | +
|
| 101 | + async with MetricsExporter(buffer, meter_provider): |
| 102 | + client = await Client.connect("localhost:7233", runtime=runtime) |
| 103 | + ... |
| 104 | + """ |
| 105 | + |
| 106 | + def __init__( |
| 107 | + self, |
| 108 | + buffer: temporalio.runtime.MetricBuffer, |
| 109 | + meter_provider: opentelemetry.metrics.MeterProvider | None = None, |
| 110 | + *, |
| 111 | + meter_name: str = "temporalio", |
| 112 | + meter_version: str | None = None, |
| 113 | + poll_interval: timedelta = timedelta(seconds=1), |
| 114 | + on_error: Callable[[Exception], None] | None = None, |
| 115 | + ) -> None: |
| 116 | + """Create an exporter that drains ``buffer`` into ``meter_provider``. |
| 117 | +
|
| 118 | + Args: |
| 119 | + buffer: The buffer to drain. Must already be (or about to be) set |
| 120 | + as the ``metrics`` of a |
| 121 | + :py:class:`temporalio.runtime.TelemetryConfig` on a |
| 122 | + constructed :py:class:`temporalio.runtime.Runtime`. |
| 123 | + meter_provider: The provider to create instruments on. Defaults to |
| 124 | + :py:func:`opentelemetry.metrics.get_meter_provider` (the |
| 125 | + global provider) if not given. |
| 126 | + meter_name: Name passed to ``get_meter`` on the provider. |
| 127 | + meter_version: Version passed to ``get_meter`` on the provider. |
| 128 | + poll_interval: How often to drain the buffer. Must be reasonably |
| 129 | + frequent -- see the warning on |
| 130 | + :py:class:`temporalio.runtime.MetricBuffer`. |
| 131 | + on_error: Optional callback invoked (in addition to logging) when |
| 132 | + draining the buffer or applying an individual update fails. |
| 133 | + If this callback itself raises, that is logged and ignored. |
| 134 | + """ |
| 135 | + self._buffer = buffer |
| 136 | + self._meter = ( |
| 137 | + meter_provider or opentelemetry.metrics.get_meter_provider() |
| 138 | + ).get_meter(meter_name, meter_version) |
| 139 | + self._poll_interval = poll_interval |
| 140 | + self._on_error = on_error |
| 141 | + self._instruments: dict[int, _Instrument] = {} |
| 142 | + self._attributes_cache: dict[ |
| 143 | + int, Mapping[str, opentelemetry.util.types.AttributeValue] |
| 144 | + ] = {} |
| 145 | + self._started = False |
| 146 | + self._shutdown_event = asyncio.Event() |
| 147 | + self._run_complete_event = asyncio.Event() |
| 148 | + self._run_task: asyncio.Task | None = None |
| 149 | + |
| 150 | + async def run(self) -> None: |
| 151 | + """Drain and export on ``poll_interval`` until :py:meth:`shutdown` is called. |
| 152 | +
|
| 153 | + Raises: |
| 154 | + RuntimeError: If ``buffer`` was never attached to a constructed |
| 155 | + :py:class:`temporalio.runtime.Runtime`, or if this is called |
| 156 | + while already running. |
| 157 | + """ |
| 158 | + if self._started: |
| 159 | + raise RuntimeError("MetricsExporter is already running") |
| 160 | + self._started = True |
| 161 | + self._shutdown_event.clear() |
| 162 | + self._run_complete_event.clear() |
| 163 | + try: |
| 164 | + while not self._shutdown_event.is_set(): |
| 165 | + self._drain_once() |
| 166 | + with contextlib.suppress(asyncio.TimeoutError): |
| 167 | + await asyncio.wait_for( |
| 168 | + self._shutdown_event.wait(), |
| 169 | + timeout=self._poll_interval.total_seconds(), |
| 170 | + ) |
| 171 | + # Final drain so nothing recorded right before shutdown is lost. |
| 172 | + self._drain_once() |
| 173 | + finally: |
| 174 | + self._started = False |
| 175 | + self._run_complete_event.set() |
| 176 | + |
| 177 | + async def shutdown(self) -> None: |
| 178 | + """Stop :py:meth:`run` (including a final drain) and wait for it to finish.""" |
| 179 | + self._shutdown_event.set() |
| 180 | + await self._run_complete_event.wait() |
| 181 | + |
| 182 | + async def __aenter__(self) -> "MetricsExporter": |
| 183 | + """Start :py:meth:`run` as a background task.""" |
| 184 | + self._run_task = asyncio.ensure_future(self.run()) |
| 185 | + return self |
| 186 | + |
| 187 | + async def __aexit__(self, *exc_info: object) -> None: |
| 188 | + """Call :py:meth:`shutdown` and await the background task.""" |
| 189 | + await self.shutdown() |
| 190 | + if self._run_task: |
| 191 | + await self._run_task |
| 192 | + |
| 193 | + def _drain_once(self) -> None: |
| 194 | + try: |
| 195 | + updates = self._buffer.retrieve_updates() |
| 196 | + except RuntimeError: |
| 197 | + # Buffer was never attached to a constructed Runtime -- this is a |
| 198 | + # setup error, not a transient failure, so it should propagate |
| 199 | + # rather than spin silently and drop metrics forever. |
| 200 | + raise |
| 201 | + except Exception as err: |
| 202 | + self._handle_error(err) |
| 203 | + return |
| 204 | + |
| 205 | + for update in updates: |
| 206 | + try: |
| 207 | + self._apply_update(update) |
| 208 | + except Exception as err: |
| 209 | + self._handle_error(err) |
| 210 | + |
| 211 | + def _handle_error(self, err: Exception) -> None: |
| 212 | + logger.exception("Error exporting buffered Temporal metrics") |
| 213 | + if self._on_error: |
| 214 | + try: |
| 215 | + self._on_error(err) |
| 216 | + except Exception: |
| 217 | + logger.exception("on_error handler failed") |
| 218 | + |
| 219 | + def _apply_update(self, update: temporalio.runtime.BufferedMetricUpdate) -> None: |
| 220 | + instrument = self._get_or_create_instrument(update.metric) |
| 221 | + attributes = self._get_or_create_attributes(update.attributes) |
| 222 | + |
| 223 | + if instrument.kind == temporalio.runtime.BUFFERED_METRIC_KIND_COUNTER: |
| 224 | + assert instrument.counter is not None |
| 225 | + instrument.counter.add(update.value, attributes=attributes) |
| 226 | + elif instrument.kind == temporalio.runtime.BUFFERED_METRIC_KIND_HISTOGRAM: |
| 227 | + assert instrument.histogram is not None |
| 228 | + instrument.histogram.record(update.value, attributes=attributes) |
| 229 | + elif instrument.kind == temporalio.runtime.BUFFERED_METRIC_KIND_GAUGE: |
| 230 | + assert instrument.gauge_state is not None |
| 231 | + with instrument.gauge_state.lock: |
| 232 | + instrument.gauge_state.last_values[id(update.attributes)] = ( |
| 233 | + attributes, |
| 234 | + update.value, |
| 235 | + ) |
| 236 | + else: |
| 237 | + raise ValueError(f"Unrecognized buffered metric kind: {instrument.kind}") |
| 238 | + |
| 239 | + def _get_or_create_instrument( |
| 240 | + self, metric: temporalio.runtime.BufferedMetric |
| 241 | + ) -> _Instrument: |
| 242 | + instrument = self._instruments.get(id(metric)) |
| 243 | + if instrument is not None: |
| 244 | + return instrument |
| 245 | + |
| 246 | + unit = metric.unit or "" |
| 247 | + description = metric.description or "" |
| 248 | + instrument = _Instrument(kind=metric.kind) |
| 249 | + if metric.kind == temporalio.runtime.BUFFERED_METRIC_KIND_COUNTER: |
| 250 | + instrument.counter = self._meter.create_counter( |
| 251 | + metric.name, unit=unit, description=description |
| 252 | + ) |
| 253 | + elif metric.kind == temporalio.runtime.BUFFERED_METRIC_KIND_HISTOGRAM: |
| 254 | + instrument.histogram = self._meter.create_histogram( |
| 255 | + metric.name, unit=unit, description=description |
| 256 | + ) |
| 257 | + elif metric.kind == temporalio.runtime.BUFFERED_METRIC_KIND_GAUGE: |
| 258 | + gauge_state = _GaugeState() |
| 259 | + instrument.gauge_state = gauge_state |
| 260 | + self._meter.create_observable_gauge( |
| 261 | + metric.name, |
| 262 | + callbacks=[_make_gauge_callback(gauge_state)], |
| 263 | + unit=unit, |
| 264 | + description=description, |
| 265 | + ) |
| 266 | + else: |
| 267 | + raise ValueError(f"Unrecognized buffered metric kind: {metric.kind}") |
| 268 | + |
| 269 | + self._instruments[id(metric)] = instrument |
| 270 | + return instrument |
| 271 | + |
| 272 | + def _get_or_create_attributes( |
| 273 | + self, attributes: temporalio.common.MetricAttributes |
| 274 | + ) -> Mapping[str, opentelemetry.util.types.AttributeValue]: |
| 275 | + cached = self._attributes_cache.get(id(attributes)) |
| 276 | + if cached is not None: |
| 277 | + return cached |
| 278 | + converted: Mapping[str, opentelemetry.util.types.AttributeValue] = dict( |
| 279 | + attributes |
| 280 | + ) |
| 281 | + self._attributes_cache[id(attributes)] = converted |
| 282 | + return converted |
0 commit comments