Metrics: database timing, pool state, DB-backed gauges, gunicorn
- Statement latency by operation and connection-pool gauges via SQLAlchemy events - Users, active users (1h/24h/7d) and now-playing gauges computed at scrape time, cached for 60s, from a NullPool engine that is safe in the gunicorn master; exports nothing (not an error) if the DB is down - gunicorn.conf.py: multiprocess metrics aggregated across workers and served by the master on METRICS_PORT, stale files cleared at start, dead workers marked - Tests cover labels, in-flight gauge, DB metrics, the collector and a real two-worker gunicorn aggregation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
89f8589424
commit
faa74871a5
7 files changed
+319
-7
No files matched your search
@@ -118,3 +118,10 @@ build_info = Gauge(
|
||||
multiprocess_mode="max",
|
||||
)
|
||||
build_info.labels(version=__version__, python_version=platform.python_version()).set(1)
|
||||
|
||||
# Gauges computed from the database by metrics.collectors.DatabaseStatsCollector.
|
||||
COLLECTED = {
|
||||
"users": "scrobbler_users",
|
||||
"active_users": "scrobbler_active_users",
|
||||
"now_playing_active": "scrobbler_now_playing_active",
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Gauges computed from the database at scrape time, cached so frequent scrapes
|
||||
don't load Postgres. Uses its own NullPool engine, so it's safe to run in the
|
||||
gunicorn master process (no pooled connections to leak into forked workers)."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
from prometheus_client.core import GaugeMetricFamily
|
||||
from prometheus_client.registry import Collector
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from scrobbler.metrics import COLLECTED
|
||||
|
||||
ACTIVE_WINDOWS = {"1h": "1 hour", "24h": "24 hours", "7d": "7 days"}
|
||||
|
||||
|
||||
class DatabaseStatsCollector(Collector):
|
||||
def __init__(self, database_url: str, ttl_seconds: float = 60):
|
||||
self.engine = create_engine(database_url, poolclass=NullPool)
|
||||
self.ttl = ttl_seconds
|
||||
self._lock = threading.Lock()
|
||||
self._cached_at = 0.0
|
||||
self._values: dict | None = None
|
||||
|
||||
def _query(self) -> dict:
|
||||
with self.engine.connect() as conn:
|
||||
users = conn.execute(text("SELECT count(*) FROM users")).scalar_one()
|
||||
active = {
|
||||
window: conn.execute(
|
||||
text(
|
||||
"SELECT count(DISTINCT user_id) FROM scrobbles "
|
||||
f"WHERE played_at > now() - interval '{interval}'"
|
||||
)
|
||||
).scalar_one()
|
||||
for window, interval in ACTIVE_WINDOWS.items()
|
||||
}
|
||||
now_playing = conn.execute(
|
||||
text("SELECT count(*) FROM now_playing WHERE expires_at > now()")
|
||||
).scalar_one()
|
||||
return {"users": users, "active": active, "now_playing": now_playing}
|
||||
|
||||
def values(self) -> dict | None:
|
||||
with self._lock:
|
||||
if self._values is None or time.monotonic() - self._cached_at > self.ttl:
|
||||
try:
|
||||
self._values = self._query()
|
||||
self._cached_at = time.monotonic()
|
||||
except Exception: # database down: export nothing rather than fail the scrape
|
||||
return None
|
||||
return self._values
|
||||
|
||||
def collect(self):
|
||||
values = self.values()
|
||||
if values is None:
|
||||
return
|
||||
yield GaugeMetricFamily(COLLECTED["users"], "Registered users", value=values["users"])
|
||||
active = GaugeMetricFamily(
|
||||
COLLECTED["active_users"], "Users who scrobbled within the window", labels=["window"]
|
||||
)
|
||||
for window, count in values["active"].items():
|
||||
active.add_metric([window], count)
|
||||
yield active
|
||||
yield GaugeMetricFamily(
|
||||
COLLECTED["now_playing_active"],
|
||||
"Users currently playing a track",
|
||||
value=values["now_playing"],
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""SQLAlchemy hooks: statement latency and connection-pool state."""
|
||||
|
||||
import time
|
||||
|
||||
from sqlalchemy import event
|
||||
from sqlalchemy.engine import Engine
|
||||
|
||||
from scrobbler import metrics
|
||||
|
||||
_OPERATIONS = {"select", "insert", "update", "delete"}
|
||||
|
||||
|
||||
def _operation(statement: str) -> str:
|
||||
word = statement.lstrip().split(None, 1)[0].lower() if statement.strip() else ""
|
||||
return word if word in _OPERATIONS else "other"
|
||||
|
||||
|
||||
def instrument(engine: Engine) -> None:
|
||||
@event.listens_for(engine, "before_cursor_execute")
|
||||
def _before(conn, cursor, statement, parameters, context, executemany):
|
||||
conn.info.setdefault("_query_start", []).append(time.perf_counter())
|
||||
|
||||
@event.listens_for(engine, "after_cursor_execute")
|
||||
def _after(conn, cursor, statement, parameters, context, executemany):
|
||||
start = conn.info["_query_start"].pop()
|
||||
metrics.db_query_duration_seconds.labels(operation=_operation(statement)).observe(
|
||||
time.perf_counter() - start
|
||||
)
|
||||
|
||||
@event.listens_for(engine, "handle_error")
|
||||
def _error(context):
|
||||
stack = context.connection.info.get("_query_start") if context.connection else None
|
||||
if stack:
|
||||
stack.pop()
|
||||
|
||||
pool = engine.pool
|
||||
|
||||
def _report_pool(*_args):
|
||||
# QueuePool exposes these; other pools (e.g. NullPool in tools) don't.
|
||||
if not hasattr(pool, "checkedout"):
|
||||
return
|
||||
metrics.db_pool_connections.labels(state="checked_out").set(pool.checkedout())
|
||||
metrics.db_pool_connections.labels(state="idle").set(pool.checkedin())
|
||||
metrics.db_pool_connections.labels(state="overflow").set(max(0, pool.overflow()))
|
||||
metrics.db_pool_connections.labels(state="size").set(pool.size())
|
||||
|
||||
for name in ("connect", "checkout", "checkin", "close"):
|
||||
event.listen(pool, name, _report_pool)
|
||||
@@ -3,21 +3,27 @@ import os
|
||||
|
||||
from prometheus_client import REGISTRY, CollectorRegistry, multiprocess, start_http_server
|
||||
|
||||
from scrobbler.metrics.collectors import DatabaseStatsCollector
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def metrics_registry() -> CollectorRegistry:
|
||||
"""Registry to expose: aggregated across workers when running under gunicorn."""
|
||||
def metrics_registry(database_url: str | None = None) -> CollectorRegistry:
|
||||
"""Registry to expose. Under gunicorn (PROMETHEUS_MULTIPROC_DIR set) it aggregates
|
||||
every worker's metrics; otherwise it's this process's default registry."""
|
||||
if os.environ.get("PROMETHEUS_MULTIPROC_DIR"):
|
||||
registry = CollectorRegistry()
|
||||
multiprocess.MultiProcessCollector(registry)
|
||||
return registry
|
||||
return REGISTRY
|
||||
else:
|
||||
registry = REGISTRY
|
||||
if database_url:
|
||||
registry.register(DatabaseStatsCollector(database_url))
|
||||
return registry
|
||||
|
||||
|
||||
def start_metrics_server(port: int, registry: CollectorRegistry | None = None) -> bool:
|
||||
def start_metrics_server(port: int, database_url: str | None = None) -> bool:
|
||||
try:
|
||||
start_http_server(port, registry=registry or metrics_registry())
|
||||
start_http_server(port, registry=metrics_registry(database_url))
|
||||
except OSError as exc: # e.g. the dev-server reloader's second process
|
||||
log.warning("metrics server not started on port %s: %s", port, exc)
|
||||
return False
|
||||
|
||||
Reference in new issue
Block a user