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
@@ -0,0 +1,34 @@
|
|||||||
|
"""Gunicorn settings for the API. Metrics from every worker are aggregated through
|
||||||
|
prometheus_client's multiprocess mode and served by the master on METRICS_PORT."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
|
||||||
|
# Must be set before prometheus_client is imported by anything.
|
||||||
|
MULTIPROC_DIR = os.environ.setdefault("PROMETHEUS_MULTIPROC_DIR", "/tmp/scrobbler-metrics")
|
||||||
|
|
||||||
|
wsgi_app = "scrobbler:create_app()"
|
||||||
|
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
||||||
|
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
||||||
|
accesslog = "-"
|
||||||
|
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
||||||
|
|
||||||
|
|
||||||
|
def on_starting(server):
|
||||||
|
# Stale files from a previous run would double-count.
|
||||||
|
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
|
||||||
|
os.makedirs(MULTIPROC_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def when_ready(server):
|
||||||
|
from scrobbler.metrics.server import start_metrics_server
|
||||||
|
|
||||||
|
start_metrics_server(
|
||||||
|
int(os.environ.get("METRICS_PORT", "9100")), os.environ.get("DATABASE_URL")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def child_exit(server, worker):
|
||||||
|
from prometheus_client import multiprocess
|
||||||
|
|
||||||
|
multiprocess.mark_process_dead(worker.pid)
|
||||||
@@ -32,10 +32,15 @@ def create_app(config_object=None):
|
|||||||
max_age=600,
|
max_age=600,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from scrobbler.metrics import db as db_metrics
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
db_metrics.instrument(db.engine)
|
||||||
|
|
||||||
if app.config["START_METRICS_SERVER"]:
|
if app.config["START_METRICS_SERVER"]:
|
||||||
from scrobbler.metrics.server import start_metrics_server
|
from scrobbler.metrics.server import start_metrics_server
|
||||||
|
|
||||||
start_metrics_server(app.config["METRICS_PORT"])
|
start_metrics_server(app.config["METRICS_PORT"], app.config["SQLALCHEMY_DATABASE_URI"])
|
||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|||||||
@@ -118,3 +118,10 @@ build_info = Gauge(
|
|||||||
multiprocess_mode="max",
|
multiprocess_mode="max",
|
||||||
)
|
)
|
||||||
build_info.labels(version=__version__, python_version=platform.python_version()).set(1)
|
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 prometheus_client import REGISTRY, CollectorRegistry, multiprocess, start_http_server
|
||||||
|
|
||||||
|
from scrobbler.metrics.collectors import DatabaseStatsCollector
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def metrics_registry() -> CollectorRegistry:
|
def metrics_registry(database_url: str | None = None) -> CollectorRegistry:
|
||||||
"""Registry to expose: aggregated across workers when running under gunicorn."""
|
"""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"):
|
if os.environ.get("PROMETHEUS_MULTIPROC_DIR"):
|
||||||
registry = CollectorRegistry()
|
registry = CollectorRegistry()
|
||||||
multiprocess.MultiProcessCollector(registry)
|
multiprocess.MultiProcessCollector(registry)
|
||||||
return registry
|
else:
|
||||||
return REGISTRY
|
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:
|
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
|
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)
|
log.warning("metrics server not started on port %s: %s", port, exc)
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from prometheus_client import CollectorRegistry, generate_latest
|
||||||
|
from prometheus_client.parser import text_string_to_metric_families
|
||||||
|
|
||||||
|
from scrobbler.metrics.collectors import DatabaseStatsCollector
|
||||||
|
from scrobbler.services import scrobbles
|
||||||
|
from scrobbler.services.scrobbles import TrackInput
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_http_metrics_use_the_flask_endpoint_name(client, auth, metric_delta):
|
||||||
|
ok = metric_delta(
|
||||||
|
"scrobbler_http_requests_total", endpoint="Auth.me", http_method="GET", status="200"
|
||||||
|
)
|
||||||
|
denied = metric_delta(
|
||||||
|
"scrobbler_http_requests_total", endpoint="Auth.me", http_method="GET", status="401"
|
||||||
|
)
|
||||||
|
latency = metric_delta(
|
||||||
|
"scrobbler_http_request_duration_seconds_count", endpoint="Auth.me", http_method="GET"
|
||||||
|
)
|
||||||
|
client.get("/api/v1/auth/me", headers=auth)
|
||||||
|
client.get("/api/v1/auth/me")
|
||||||
|
assert (ok.delta, denied.delta, latency.delta) == (1, 1, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_progress_gauge_returns_to_zero(client, metric_delta):
|
||||||
|
in_progress = metric_delta("scrobbler_http_requests_in_progress", endpoint="lastfm.dispatch")
|
||||||
|
client.get("/2.0/?method=nope")
|
||||||
|
assert in_progress.delta == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_db_query_latency_is_recorded(client, user, metric_delta):
|
||||||
|
selects = metric_delta("scrobbler_db_query_duration_seconds_count", operation="select")
|
||||||
|
client.post("/api/v1/auth/login", json={"username": "alice", "password": "hunter22"})
|
||||||
|
assert selects.delta >= 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_pool_gauges_are_exported(client, user):
|
||||||
|
from prometheus_client import REGISTRY
|
||||||
|
|
||||||
|
client.get("/api/v1/auth/me")
|
||||||
|
states = {
|
||||||
|
s.labels["state"]
|
||||||
|
for m in REGISTRY.collect()
|
||||||
|
if m.name == "scrobbler_db_pool_connections"
|
||||||
|
for s in m.samples
|
||||||
|
}
|
||||||
|
assert {"checked_out", "idle", "overflow", "size"} <= states
|
||||||
|
|
||||||
|
|
||||||
|
def test_database_stats_collector(app, user, make_user):
|
||||||
|
make_user(username="bob")
|
||||||
|
scrobbles.submit_scrobbles(
|
||||||
|
user, None, [TrackInput(artist="A", track="T", timestamp=int(time.time()) - 60)]
|
||||||
|
)
|
||||||
|
scrobbles.update_now_playing(user, TrackInput(artist="A", track="U"))
|
||||||
|
|
||||||
|
registry = CollectorRegistry()
|
||||||
|
registry.register(DatabaseStatsCollector(app.config["SQLALCHEMY_DATABASE_URI"]))
|
||||||
|
families = {
|
||||||
|
f.name: f for f in text_string_to_metric_families(generate_latest(registry).decode())
|
||||||
|
}
|
||||||
|
assert families["scrobbler_users"].samples[0].value == 2
|
||||||
|
active = {s.labels["window"]: s.value for s in families["scrobbler_active_users"].samples}
|
||||||
|
assert active == {"1h": 1, "24h": 1, "7d": 1}
|
||||||
|
assert families["scrobbler_now_playing_active"].samples[0].value == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_database_stats_collector_caches(app, user):
|
||||||
|
collector = DatabaseStatsCollector(app.config["SQLALCHEMY_DATABASE_URI"], ttl_seconds=60)
|
||||||
|
first = collector.values()
|
||||||
|
user_count = first["users"]
|
||||||
|
from scrobbler.services.accounts import register
|
||||||
|
|
||||||
|
register("carol", "carol@example.com", "password123")
|
||||||
|
assert collector.values()["users"] == user_count # still cached
|
||||||
|
|
||||||
|
|
||||||
|
def test_database_stats_collector_survives_db_outage():
|
||||||
|
collector = DatabaseStatsCollector("postgresql+psycopg://nobody:x@127.0.0.1:1/none")
|
||||||
|
assert list(collector.collect()) == []
|
||||||
|
|
||||||
|
|
||||||
|
def _free_port() -> int:
|
||||||
|
with socket.socket() as s:
|
||||||
|
s.bind(("127.0.0.1", 0))
|
||||||
|
return s.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _get(url: str, retries: int = 50) -> str:
|
||||||
|
for _ in range(retries):
|
||||||
|
try:
|
||||||
|
return urllib.request.urlopen(url, timeout=2).read().decode()
|
||||||
|
except OSError:
|
||||||
|
time.sleep(0.2)
|
||||||
|
raise AssertionError(f"{url} never answered")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(sys.platform == "win32", reason="gunicorn is POSIX only")
|
||||||
|
def test_gunicorn_aggregates_worker_metrics(app, tmp_path):
|
||||||
|
api_port, metrics_port = _free_port(), _free_port()
|
||||||
|
env = {
|
||||||
|
**os.environ,
|
||||||
|
"BIND": f"127.0.0.1:{api_port}",
|
||||||
|
"WEB_CONCURRENCY": "2",
|
||||||
|
"METRICS_PORT": str(metrics_port),
|
||||||
|
"PROMETHEUS_MULTIPROC_DIR": str(tmp_path / "metrics"),
|
||||||
|
"DATABASE_URL": app.config["SQLALCHEMY_DATABASE_URI"],
|
||||||
|
"START_METRICS_SERVER": "0",
|
||||||
|
}
|
||||||
|
server = subprocess.Popen(
|
||||||
|
[sys.executable, "-m", "gunicorn", "-c", str(ROOT / "gunicorn.conf.py")],
|
||||||
|
cwd=ROOT,
|
||||||
|
env=env,
|
||||||
|
stdout=subprocess.DEVNULL,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
_get(f"http://127.0.0.1:{api_port}/api/openapi.json")
|
||||||
|
for _ in range(9): # spread over both workers
|
||||||
|
_get(f"http://127.0.0.1:{api_port}/api/openapi.json")
|
||||||
|
body = _get(f"http://127.0.0.1:{metrics_port}/metrics")
|
||||||
|
finally:
|
||||||
|
server.terminate()
|
||||||
|
server.wait(timeout=10)
|
||||||
|
|
||||||
|
families = {f.name: f for f in text_string_to_metric_families(body)}
|
||||||
|
[openapi] = [
|
||||||
|
s
|
||||||
|
for s in families["scrobbler_http_requests"].samples
|
||||||
|
if s.name == "scrobbler_http_requests_total"
|
||||||
|
and s.labels.get("endpoint") == "api-docs.openapi_json"
|
||||||
|
]
|
||||||
|
assert openapi.value == 10
|
||||||
|
assert "scrobbler_users" in families
|
||||||
Reference in new issue
Block a user