forked from mtusi2026/mtusi2026lab7
115 lines
5.2 KiB
Python
115 lines
5.2 KiB
Python
"""
|
|
Собственные метрики приложения (lab6). Имена в OTel → Prometheus (через Collector):
|
|
|
|
messenger.jobs.processed counter {job.type, outcome} → messenger_jobs_processed_total
|
|
messenger.job.duration histogram {job.type, outcome}, s → messenger_job_duration_seconds_*
|
|
messenger.attachment.time_to_ready histogram, s → messenger_attachment_time_to_ready_seconds_*
|
|
messenger.queue.depth gauge {queue, state} → messenger_queue_depth
|
|
messenger.queue.oldest_age gauge {queue}, s → messenger_queue_oldest_age_seconds
|
|
messenger.db.pool.connections gauge {state=used|idle} → messenger_db_pool_connections
|
|
messenger.db.pool.max gauge → messenger_db_pool_max
|
|
messenger.db.pool.waiting gauge → messenger_db_pool_waiting
|
|
messenger.worker.busy / .capacity gauge → messenger_worker_busy, messenger_worker_capacity
|
|
|
|
Атрибуты только низкокардинальные. outcome: ready | retry | failed | duplicate | lease_lost.
|
|
Очередь считает API (а не worker): при остановленном worker возраст задач всё равно виден.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
|
|
from opentelemetry.metrics import CallbackOptions, Observation
|
|
|
|
from .telemetry import meter
|
|
|
|
JOB_TYPE = "attachment.process.v1"
|
|
|
|
jobs_processed = meter.create_counter(
|
|
"messenger.jobs.processed", unit="{job}",
|
|
description="Завершённые попытки обработки заданий по исходу")
|
|
job_duration = meter.create_histogram(
|
|
"messenger.job.duration", unit="s",
|
|
description="Время одной попытки обработки задания в worker")
|
|
time_to_ready = meter.create_histogram(
|
|
"messenger.attachment.time_to_ready", unit="s",
|
|
description="От устойчивого приёма (202) до публикации ready")
|
|
|
|
# ------------------------------------------------------------------ очередь (API)
|
|
_queue = {"queued": 0, "processing": 0, "outbox_unpublished": 0, "oldest_age": 0.0, "fresh": False}
|
|
_queue_lock = threading.Lock()
|
|
|
|
|
|
def set_queue_stats(queued: int, processing: int, outbox: int, oldest_age: float) -> None:
|
|
with _queue_lock:
|
|
_queue.update(queued=queued, processing=processing, outbox_unpublished=outbox,
|
|
oldest_age=oldest_age, fresh=True)
|
|
|
|
|
|
def _observe_depth(options: CallbackOptions):
|
|
with _queue_lock:
|
|
if not _queue["fresh"]:
|
|
return []
|
|
return [Observation(_queue[s], {"queue": "attachments", "state": s})
|
|
for s in ("queued", "processing", "outbox_unpublished")]
|
|
|
|
|
|
def _observe_age(options: CallbackOptions):
|
|
with _queue_lock:
|
|
return [Observation(_queue["oldest_age"], {"queue": "attachments"})] if _queue["fresh"] else []
|
|
|
|
|
|
def register_queue_gauges() -> None:
|
|
meter.create_observable_gauge("messenger.queue.depth", [_observe_depth], unit="{job}",
|
|
description="Незавершённые задания по состоянию")
|
|
meter.create_observable_gauge("messenger.queue.oldest_age", [_observe_age], unit="s",
|
|
description="Возраст старейшего незавершённого задания")
|
|
|
|
|
|
# ------------------------------------------------------------------ пул БД (API и worker)
|
|
def register_pool_gauges(get_pool) -> None:
|
|
"""get_pool() → psycopg_pool (sync или async); get_stats() не делает I/O."""
|
|
def stats():
|
|
try:
|
|
return get_pool().get_stats()
|
|
except Exception: # noqa: BLE001 — пул ещё не открыт
|
|
return None
|
|
|
|
def conns(options: CallbackOptions):
|
|
s = stats()
|
|
if not s:
|
|
return []
|
|
size, idle = s.get("pool_size", 0), s.get("pool_available", 0)
|
|
return [Observation(size - idle, {"state": "used"}), Observation(idle, {"state": "idle"})]
|
|
|
|
def waiting(options: CallbackOptions):
|
|
s = stats()
|
|
return [Observation(s.get("requests_waiting", 0))] if s else []
|
|
|
|
def maximum(options: CallbackOptions):
|
|
s = stats()
|
|
return [Observation(s.get("pool_max", 0))] if s else []
|
|
|
|
meter.create_observable_gauge("messenger.db.pool.connections", [conns], unit="{connection}")
|
|
meter.create_observable_gauge("messenger.db.pool.waiting", [waiting], unit="{request}")
|
|
meter.create_observable_gauge("messenger.db.pool.max", [maximum], unit="{connection}")
|
|
|
|
|
|
# ------------------------------------------------------------------ worker saturation
|
|
_busy = 0
|
|
_busy_lock = threading.Lock()
|
|
|
|
|
|
def busy_inc(delta: int) -> None:
|
|
global _busy
|
|
with _busy_lock:
|
|
_busy += delta
|
|
|
|
|
|
def register_worker_gauges(capacity: int) -> None:
|
|
meter.create_observable_gauge(
|
|
"messenger.worker.busy", [lambda o: [Observation(_busy)]], unit="{job}",
|
|
description="Задания в обработке сейчас")
|
|
meter.create_observable_gauge(
|
|
"messenger.worker.capacity", [lambda o: [Observation(capacity)]], unit="{job}",
|
|
description="WORKER_CONCURRENCY")
|