feat: add SLOs, Prometheus alert rules and telemetry loss accounting
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>
This commit is contained in:
@@ -59,11 +59,12 @@ PROPAGATOR = TraceContextTextMapPropagator()
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Exporters:
|
||||
"""Получатели сигналов вместо OTLP — только для быстрых тестов
|
||||
(in-memory экспортёры SDK)."""
|
||||
(in-memory экспортёры SDK). `spans` или `logs` `None` — экспортёр OTLP из
|
||||
`[telemetry]` (тест его внутренних метрик на подставной отправке)."""
|
||||
|
||||
spans: "SpanExporter"
|
||||
spans: "SpanExporter | None"
|
||||
metrics: "MetricReader"
|
||||
logs: "LogRecordExporter"
|
||||
logs: "LogRecordExporter | None"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
||||
+143
-66
@@ -10,9 +10,17 @@ replay модулей SDK, protobuf и HTTP-клиента экспортёра
|
||||
конструктором без детекторов, у параметров явные значения, `atexit` SDK
|
||||
выключен. Sampler — `ParentBased(ALWAYS_ON)` (решение 5): корни выбираются
|
||||
всегда, удалённый родитель из задания передаёт свой флаг выборки.
|
||||
|
||||
Внутренние метрики SDK (design change `slo-alerts`, решения 8–9): процессоры
|
||||
span и журнала и экспортёры OTLP span и журнала считают отброшенное и
|
||||
неудачные отправки в `MeterProvider` процесса. SDK 1.45 включает их только
|
||||
переменной окружения в конструкторе, поэтому код ставит её на время их сборки
|
||||
(`_internal_metrics`) — внешние `OTEL_*` к этому моменту уже удалены.
|
||||
"""
|
||||
|
||||
from collections.abc import Mapping
|
||||
import os
|
||||
from collections.abc import Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
@@ -46,6 +54,7 @@ from opentelemetry.sdk.metrics.export import (
|
||||
PeriodicExportingMetricReader,
|
||||
)
|
||||
from opentelemetry.sdk.metrics.view import (
|
||||
DropAggregation,
|
||||
ExplicitBucketHistogramAggregation,
|
||||
View,
|
||||
)
|
||||
@@ -65,6 +74,8 @@ from src.utils.constants import (
|
||||
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,
|
||||
@@ -97,6 +108,23 @@ class Providers:
|
||||
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],
|
||||
@@ -104,13 +132,75 @@ def build(
|
||||
exporters: Any | None,
|
||||
) -> Providers:
|
||||
"""Провайдеры трасс, метрик и логов. `exporters` — получатели вместо OTLP
|
||||
(`core.Exporters`, быстрые тесты) или `None`."""
|
||||
if exporters is None:
|
||||
exporters = otlp_exporters(config)
|
||||
(`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,
|
||||
@@ -126,30 +216,7 @@ def build(
|
||||
max_span_attribute_length=TELEMETRY_SPAN_ATTRIBUTE_LENGTH,
|
||||
),
|
||||
)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
exporters.spans,
|
||||
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 = MeterProvider(
|
||||
metric_readers=[exporters.metrics],
|
||||
resource=attributes,
|
||||
exemplar_filter=AlwaysOffExemplarFilter(),
|
||||
shutdown_on_exit=False,
|
||||
views=[
|
||||
View(
|
||||
instrument_name=name,
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=boundaries,
|
||||
),
|
||||
)
|
||||
for name, boundaries in _BUCKETS.items()
|
||||
],
|
||||
)
|
||||
tracer_provider.add_span_processor(span_processor)
|
||||
logger_provider = LoggerProvider(
|
||||
resource=attributes,
|
||||
shutdown_on_exit=False,
|
||||
@@ -158,15 +225,7 @@ def build(
|
||||
max_attribute_length=TELEMETRY_LOG_ATTRIBUTE_LENGTH,
|
||||
),
|
||||
)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
exporters.logs,
|
||||
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,
|
||||
),
|
||||
)
|
||||
logger_provider.add_log_record_processor(log_processor)
|
||||
return Providers(
|
||||
tracer_provider=tracer_provider,
|
||||
meter_provider=meter_provider,
|
||||
@@ -183,40 +242,58 @@ def export_session() -> requests.Session:
|
||||
return session
|
||||
|
||||
|
||||
def otlp_exporters(config: TelemetrySettings) -> Any:
|
||||
"""OTLP/HTTP protobuf только из `[telemetry]`: адрес, срок, без
|
||||
заголовков и сжатия, своя сессия без прокси окружения."""
|
||||
# тип получателей живёт в core: он нужен быстрым тестам без этого модуля
|
||||
from src.infra.telemetry.core import Exporters
|
||||
# OTLP/HTTP protobuf только из `[telemetry]`: адрес, срок, без заголовков и
|
||||
# сжатия, своя сессия без прокси окружения
|
||||
|
||||
|
||||
def otlp_metric_reader(
|
||||
config: TelemetrySettings,
|
||||
) -> PeriodicExportingMetricReader:
|
||||
"""Читатель метрик с экспортёром OTLP; строится до `MeterProvider` и
|
||||
внутренних метрик SDK не получает."""
|
||||
timeout = config.export_timeout_seconds
|
||||
endpoint = config.otlp_endpoint
|
||||
return Exporters(
|
||||
spans=OTLPSpanExporter(
|
||||
endpoint=endpoint + TELEMETRY_TRACES_PATH,
|
||||
headers={},
|
||||
timeout=timeout,
|
||||
compression=Compression.NoCompression,
|
||||
session=export_session(),
|
||||
),
|
||||
metrics=PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(
|
||||
endpoint=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,
|
||||
),
|
||||
logs=OTLPLogExporter(
|
||||
endpoint=endpoint + TELEMETRY_LOGS_PATH,
|
||||
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,
|
||||
)
|
||||
|
||||
@@ -286,6 +286,16 @@ QUEUE_SNAPSHOT_STALE_SECONDS = 30
|
||||
# cgroup v2 контейнера изнутри (решение 12)
|
||||
CGROUP_ROOT = "/sys/fs/cgroup"
|
||||
|
||||
# внутренние метрики SDK для учёта потерь (design change `slo-alerts`,
|
||||
# решения 8–9): SDK 1.45 читает эту переменную в конструкторах процессоров и
|
||||
# экспортёров OTLP; код ставит её только на время их сборки
|
||||
TELEMETRY_SDK_INTERNAL_METRICS_ENV = "OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED"
|
||||
# гистограммы длительности самого SDK: для учёта не нужны и множат ряды
|
||||
TELEMETRY_SDK_DROPPED_HISTOGRAMS = (
|
||||
"otel.sdk.exporter.operation.duration",
|
||||
"otel.sdk.metric_reader.collection.duration",
|
||||
)
|
||||
|
||||
# хранилище объектов (S3)
|
||||
# имя bucket по правилам S3: 3–63 символа, строчные латинские буквы,
|
||||
# цифры, точка и дефис, по краям — буква или цифра
|
||||
|
||||
Reference in New Issue
Block a user