HAProxy /metrics scraped by the Collector, recording rules and seven alerts with promtool tests and runbooks (make alerts_test, CI step), byte-sized Collector export queues with 30 s retries, SDK internal metrics, SLO/LB/pipeline dashboard rows, driver commands alerts-check and backend-outage (change slo-alerts). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
300 lines
12 KiB
Python
300 lines
12 KiB
Python
"""Сборка провайдеров SDK OpenTelemetry и экспортёров OTLP/HTTP.
|
||
|
||
Единственный модуль пакета, который импортирует SDK, экспортёр и `requests`
|
||
(design change `job-trace-propagation`, решение 7): его импортирует только
|
||
`core.start()`, поэтому процесс с выключенной телеметрией, уборщик и команда
|
||
replay модулей SDK, protobuf и HTTP-клиента экспортёра не загружают. Остальные
|
||
модули пакета — только `opentelemetry-api`.
|
||
|
||
Всё — из `[telemetry]` (design change `otel-telemetry`, решение 8): ресурс
|
||
конструктором без детекторов, у параметров явные значения, `atexit` SDK
|
||
выключен. Sampler — `ParentBased(ALWAYS_ON)` (решение 5): корни выбираются
|
||
всегда, удалённый родитель из задания передаёт свой флаг выборки.
|
||
|
||
Внутренние метрики SDK (design change `slo-alerts`, решения 8–9): процессоры
|
||
span и журнала и экспортёры OTLP span и журнала считают отброшенное и
|
||
неудачные отправки в `MeterProvider` процесса. SDK 1.45 включает их только
|
||
переменной окружения в конструкторе, поэтому код ставит её на время их сборки
|
||
(`_internal_metrics`) — внешние `OTEL_*` к этому моменту уже удалены.
|
||
"""
|
||
|
||
import os
|
||
from collections.abc import Iterator, Mapping
|
||
from contextlib import contextmanager
|
||
from dataclasses import dataclass
|
||
from typing import Any
|
||
|
||
# транспорт экспортёров OTLP/HTTP (зависимость opentelemetry-exporter-otlp-
|
||
# proto-http): своя сессия без окружения
|
||
import requests
|
||
from opentelemetry.exporter.otlp.proto.http import Compression
|
||
from opentelemetry.exporter.otlp.proto.http._log_exporter import (
|
||
OTLPLogExporter,
|
||
)
|
||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
|
||
OTLPMetricExporter,
|
||
)
|
||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
|
||
OTLPSpanExporter,
|
||
)
|
||
from opentelemetry.sdk._logs import LoggerProvider, LogRecordLimits
|
||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||
from opentelemetry.sdk.metrics import (
|
||
AlwaysOffExemplarFilter,
|
||
Counter,
|
||
Histogram,
|
||
MeterProvider,
|
||
ObservableCounter,
|
||
ObservableGauge,
|
||
ObservableUpDownCounter,
|
||
UpDownCounter,
|
||
)
|
||
from opentelemetry.sdk.metrics.export import (
|
||
AggregationTemporality,
|
||
PeriodicExportingMetricReader,
|
||
)
|
||
from opentelemetry.sdk.metrics.view import (
|
||
DropAggregation,
|
||
ExplicitBucketHistogramAggregation,
|
||
View,
|
||
)
|
||
from opentelemetry.sdk.resources import Resource
|
||
from opentelemetry.sdk.trace import SpanLimits, TracerProvider
|
||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||
from opentelemetry.sdk.trace.sampling import ALWAYS_ON, ParentBased
|
||
|
||
from src.config.settings import Telemetry as TelemetrySettings
|
||
from src.utils.constants import (
|
||
HTTP_DURATION_BUCKETS,
|
||
JOB_DURATION_BUCKETS,
|
||
METRIC_HTTP_SERVER_DURATION,
|
||
METRIC_JOB_DURATION,
|
||
METRIC_JOB_TIME_TO_READY,
|
||
TELEMETRY_LOG_ATTRIBUTE_LENGTH,
|
||
TELEMETRY_LOGS_PATH,
|
||
TELEMETRY_MAX_ATTRIBUTES,
|
||
TELEMETRY_METRICS_PATH,
|
||
TELEMETRY_SDK_DROPPED_HISTOGRAMS,
|
||
TELEMETRY_SDK_INTERNAL_METRICS_ENV,
|
||
TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
|
||
TELEMETRY_TRACES_PATH,
|
||
TIME_TO_READY_BUCKETS,
|
||
)
|
||
|
||
# все инструменты — cumulative: Prometheus забирает накопленное (решение 3)
|
||
_CUMULATIVE = dict.fromkeys(
|
||
(
|
||
Counter,
|
||
UpDownCounter,
|
||
Histogram,
|
||
ObservableCounter,
|
||
ObservableUpDownCounter,
|
||
ObservableGauge,
|
||
),
|
||
AggregationTemporality.CUMULATIVE,
|
||
)
|
||
# границы buckets histogram по имени инструмента
|
||
_BUCKETS = {
|
||
METRIC_HTTP_SERVER_DURATION: HTTP_DURATION_BUCKETS,
|
||
METRIC_JOB_DURATION: JOB_DURATION_BUCKETS,
|
||
METRIC_JOB_TIME_TO_READY: TIME_TO_READY_BUCKETS,
|
||
}
|
||
|
||
|
||
@dataclass(frozen=True, slots=True)
|
||
class Providers:
|
||
tracer_provider: TracerProvider
|
||
meter_provider: MeterProvider
|
||
logger_provider: LoggerProvider
|
||
|
||
|
||
@contextmanager
|
||
def _internal_metrics() -> Iterator[None]:
|
||
"""Включить внутренние метрики SDK на время сборки процессоров и
|
||
экспортёров: переменную читают их конструкторы, другого выключателя в SDK
|
||
1.45 нет. После — прежнее состояние окружения (внешнее значение уже удалил
|
||
`core.remove_otel_environment`, так что переменной не остаётся)."""
|
||
previous = os.environ.get(TELEMETRY_SDK_INTERNAL_METRICS_ENV)
|
||
os.environ[TELEMETRY_SDK_INTERNAL_METRICS_ENV] = "true"
|
||
try:
|
||
yield
|
||
finally:
|
||
if previous is None:
|
||
os.environ.pop(TELEMETRY_SDK_INTERNAL_METRICS_ENV, None)
|
||
else:
|
||
os.environ[TELEMETRY_SDK_INTERNAL_METRICS_ENV] = previous
|
||
|
||
|
||
def build(
|
||
*,
|
||
resource: Mapping[str, Any],
|
||
config: TelemetrySettings,
|
||
exporters: Any | None,
|
||
) -> Providers:
|
||
"""Провайдеры трасс, метрик и логов. `exporters` — получатели вместо OTLP
|
||
(`core.Exporters`, быстрые тесты; `spans` или `logs` `None` — экспортёр
|
||
OTLP из `[telemetry]`) или `None` — всё OTLP.
|
||
|
||
Порядок (design change `slo-alerts`, решение 8): сначала `MeterProvider`,
|
||
затем процессоры span и журнала и экспортёры OTLP span и журнала с его
|
||
`meter_provider` — внутренние метрики SDK идут тем же путём, что метрики
|
||
приложения. Читатель метрик строится до провайдера и своих метрик не
|
||
получает: неудачная отправка метрик счёт не теряет (cumulative)."""
|
||
attributes = Resource(dict(resource))
|
||
timeout_ms = config.export_timeout_seconds * 1000
|
||
delay_ms = config.schedule_delay_seconds * 1000
|
||
|
||
reader = (
|
||
exporters.metrics
|
||
if exporters is not None
|
||
else otlp_metric_reader(config)
|
||
)
|
||
meter_provider = MeterProvider(
|
||
metric_readers=[reader],
|
||
resource=attributes,
|
||
exemplar_filter=AlwaysOffExemplarFilter(),
|
||
shutdown_on_exit=False,
|
||
views=[
|
||
*(
|
||
View(
|
||
instrument_name=name,
|
||
aggregation=ExplicitBucketHistogramAggregation(
|
||
boundaries=boundaries,
|
||
),
|
||
)
|
||
for name, boundaries in _BUCKETS.items()
|
||
),
|
||
# гистограммы самого SDK для учёта потерь не нужны (решение 8)
|
||
*(
|
||
View(instrument_name=name, aggregation=DropAggregation())
|
||
for name in TELEMETRY_SDK_DROPPED_HISTOGRAMS
|
||
),
|
||
],
|
||
)
|
||
with _internal_metrics():
|
||
span_exporter = getattr(exporters, "spans", None)
|
||
if span_exporter is None:
|
||
span_exporter = otlp_span_exporter(
|
||
config,
|
||
meter_provider=meter_provider,
|
||
)
|
||
log_exporter = getattr(exporters, "logs", None)
|
||
if log_exporter is None:
|
||
log_exporter = otlp_log_exporter(
|
||
config,
|
||
meter_provider=meter_provider,
|
||
)
|
||
span_processor = BatchSpanProcessor(
|
||
span_exporter,
|
||
max_queue_size=config.max_queue_size,
|
||
schedule_delay_millis=delay_ms,
|
||
max_export_batch_size=config.max_export_batch_size,
|
||
export_timeout_millis=timeout_ms,
|
||
meter_provider=meter_provider,
|
||
)
|
||
log_processor = BatchLogRecordProcessor(
|
||
log_exporter,
|
||
schedule_delay_millis=delay_ms,
|
||
max_export_batch_size=config.max_export_batch_size,
|
||
export_timeout_millis=timeout_ms,
|
||
max_queue_size=config.max_queue_size,
|
||
meter_provider=meter_provider,
|
||
)
|
||
|
||
tracer_provider = TracerProvider(
|
||
sampler=ParentBased(ALWAYS_ON),
|
||
resource=attributes,
|
||
shutdown_on_exit=False,
|
||
span_limits=SpanLimits(
|
||
max_attributes=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_events=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_links=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_span_attributes=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_event_attributes=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_link_attributes=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_attribute_length=TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
|
||
max_span_attribute_length=TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
|
||
),
|
||
)
|
||
tracer_provider.add_span_processor(span_processor)
|
||
logger_provider = LoggerProvider(
|
||
resource=attributes,
|
||
shutdown_on_exit=False,
|
||
log_record_limits=LogRecordLimits(
|
||
max_attributes=TELEMETRY_MAX_ATTRIBUTES,
|
||
max_attribute_length=TELEMETRY_LOG_ATTRIBUTE_LENGTH,
|
||
),
|
||
)
|
||
logger_provider.add_log_record_processor(log_processor)
|
||
return Providers(
|
||
tracer_provider=tracer_provider,
|
||
meter_provider=meter_provider,
|
||
logger_provider=logger_provider,
|
||
)
|
||
|
||
|
||
def export_session() -> requests.Session:
|
||
"""Сессия отправки без окружения: `HTTP(S)_PROXY`, `NO_PROXY`, `.netrc`
|
||
и `REQUESTS_CA_BUNDLE` на неё не действуют — данные идут только по адресу
|
||
`[telemetry]` (verify S5 change `otel-telemetry`, как с `OTEL_*`)."""
|
||
session = requests.Session()
|
||
session.trust_env = False
|
||
return session
|
||
|
||
|
||
# OTLP/HTTP protobuf только из `[telemetry]`: адрес, срок, без заголовков и
|
||
# сжатия, своя сессия без прокси окружения
|
||
|
||
|
||
def otlp_metric_reader(
|
||
config: TelemetrySettings,
|
||
) -> PeriodicExportingMetricReader:
|
||
"""Читатель метрик с экспортёром OTLP; строится до `MeterProvider` и
|
||
внутренних метрик SDK не получает."""
|
||
timeout = config.export_timeout_seconds
|
||
return PeriodicExportingMetricReader(
|
||
OTLPMetricExporter(
|
||
endpoint=config.otlp_endpoint + TELEMETRY_METRICS_PATH,
|
||
headers={},
|
||
timeout=timeout,
|
||
compression=Compression.NoCompression,
|
||
preferred_temporality=_CUMULATIVE,
|
||
session=export_session(),
|
||
),
|
||
export_interval_millis=config.metric_export_interval_seconds * 1000,
|
||
export_timeout_millis=timeout * 1000,
|
||
)
|
||
|
||
|
||
def otlp_span_exporter(
|
||
config: TelemetrySettings,
|
||
*,
|
||
meter_provider: MeterProvider | None,
|
||
) -> OTLPSpanExporter:
|
||
"""Экспортёр span; с `meter_provider` внутри `_internal_metrics` —
|
||
счёт отправленного и неудачных отправок (`otel.sdk.exporter.span.*`)."""
|
||
return OTLPSpanExporter(
|
||
endpoint=config.otlp_endpoint + TELEMETRY_TRACES_PATH,
|
||
headers={},
|
||
timeout=config.export_timeout_seconds,
|
||
compression=Compression.NoCompression,
|
||
session=export_session(),
|
||
meter_provider=meter_provider,
|
||
)
|
||
|
||
|
||
def otlp_log_exporter(
|
||
config: TelemetrySettings,
|
||
*,
|
||
meter_provider: MeterProvider | None,
|
||
) -> OTLPLogExporter:
|
||
"""Экспортёр записей журнала; счёт — `otel.sdk.exporter.log.*`."""
|
||
return OTLPLogExporter(
|
||
endpoint=config.otlp_endpoint + TELEMETRY_LOGS_PATH,
|
||
headers={},
|
||
timeout=config.export_timeout_seconds,
|
||
compression=Compression.NoCompression,
|
||
session=export_session(),
|
||
meter_provider=meter_provider,
|
||
)
|