Monitoring stack, containers and dashboards
- API image (uv multi-stage, non-root, gunicorn, migrations on start, health check) and UI image (nginx, CSP, config.js rendered from API_BASE_URL); /healthz documented in OpenAPI - docker compose runs db, api and ui; the "monitoring" profile adds Prometheus, postgres-exporter and Grafana, all provisioned from files - Grafana dashboards: API overview (RED), Last.fm API, Usage, Database - Prometheus alert rules: API down, error rate, latency, auth failure spike, ignored scrobbles, DB pool saturation, Postgres down - Pool checkout gauge counts events (the pool's own counters lag the checkin event); error ratios show 0 instead of "No data" - Tests check dashboards and alerts only use metrics that exist - scripts/generate_traffic.py drives realistic traffic for demos 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
faa74871a5
commit
ea705589f1
28 files changed
+3508
-14
No files matched your search
@@ -31,3 +31,7 @@ def test_build_info_is_exported(metric_delta):
|
||||
|
||||
samples = [s for m in REGISTRY.collect() if m.name == "scrobbler_build_info" for s in m.samples]
|
||||
assert samples and samples[0].labels["version"] == __version__
|
||||
|
||||
|
||||
def test_healthz(client):
|
||||
assert client.get("/healthz").get_json() == {"status": "ok"}
|
||||
@@ -0,0 +1,77 @@
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
from prometheus_client.metrics import MetricWrapperBase
|
||||
|
||||
from scrobbler import metrics
|
||||
|
||||
DEPLOY = Path(__file__).resolve().parents[1] / "deploy"
|
||||
DASHBOARDS = sorted((DEPLOY / "grafana" / "dashboards").glob("*.json"))
|
||||
METRIC_NAME = re.compile(r"\bscrobbler_[a-z0-9_]+")
|
||||
|
||||
|
||||
def defined_series() -> set[str]:
|
||||
"""Every series name the service can export."""
|
||||
names = set(metrics.COLLECTED.values())
|
||||
for value in vars(metrics).values():
|
||||
if not isinstance(value, MetricWrapperBase):
|
||||
continue
|
||||
name, kind = value._name, value._type
|
||||
if kind == "counter":
|
||||
names |= {f"{name}_total", f"{name}_created"}
|
||||
elif kind == "histogram":
|
||||
names |= {f"{name}_bucket", f"{name}_sum", f"{name}_count", f"{name}_created"}
|
||||
else:
|
||||
names.add(name)
|
||||
return names
|
||||
|
||||
|
||||
def exprs(node):
|
||||
if isinstance(node, dict):
|
||||
for key, value in node.items():
|
||||
if key in ("expr", "query", "definition") and isinstance(value, str):
|
||||
yield value
|
||||
else:
|
||||
yield from exprs(value)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
yield from exprs(item)
|
||||
|
||||
|
||||
def test_there_are_four_dashboards():
|
||||
assert {p.stem for p in DASHBOARDS} == {"api-overview", "lastfm-api", "usage", "database"}
|
||||
|
||||
|
||||
def test_dashboard_uids_are_unique():
|
||||
uids = [json.loads(p.read_text())["uid"] for p in DASHBOARDS]
|
||||
assert len(uids) == len(set(uids))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", DASHBOARDS, ids=lambda p: p.stem)
|
||||
def test_dashboard_queries_only_use_defined_metrics(path):
|
||||
board = json.loads(path.read_text())
|
||||
used = {name for expr in exprs(board) for name in METRIC_NAME.findall(expr)}
|
||||
assert used, f"{path.name} queries no scrobbler metrics"
|
||||
assert used <= defined_series(), f"undefined metrics: {sorted(used - defined_series())}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", DASHBOARDS, ids=lambda p: p.stem)
|
||||
def test_panels_use_the_provisioned_datasource(path):
|
||||
board = json.loads(path.read_text())
|
||||
for panel in board["panels"]:
|
||||
if panel["type"] != "row":
|
||||
assert panel["datasource"]["uid"] == "prometheus", panel["title"]
|
||||
|
||||
|
||||
def test_alert_rules_only_use_defined_metrics():
|
||||
rules = yaml.safe_load((DEPLOY / "prometheus" / "alerts.yml").read_text())
|
||||
used = {
|
||||
name
|
||||
for group in rules["groups"]
|
||||
for rule in group["rules"]
|
||||
for name in METRIC_NAME.findall(rule["expr"])
|
||||
}
|
||||
assert used <= defined_series(), f"undefined metrics: {sorted(used - defined_series())}"
|
||||
+15
-1
@@ -54,7 +54,21 @@ def test_pool_gauges_are_exported(client, user):
|
||||
if m.name == "scrobbler_db_pool_connections"
|
||||
for s in m.samples
|
||||
}
|
||||
assert {"checked_out", "idle", "overflow", "size"} <= states
|
||||
assert {"checked_out", "overflow", "size"} <= states
|
||||
|
||||
|
||||
def test_checked_out_connections_return_to_zero(client, user):
|
||||
from prometheus_client import REGISTRY
|
||||
|
||||
from scrobbler.extensions import db
|
||||
|
||||
db.session.remove() # return the test session's connection
|
||||
before = REGISTRY.get_sample_value("scrobbler_db_pool_connections", {"state": "checked_out"})
|
||||
client.post("/api/v1/auth/login", json={"username": "alice", "password": "hunter22"})
|
||||
# The request shares the test's app context, so end its session as teardown would.
|
||||
db.session.remove()
|
||||
after = REGISTRY.get_sample_value("scrobbler_db_pool_connections", {"state": "checked_out"})
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_database_stats_collector(app, user, make_user):
|
||||
|
||||
@@ -8,7 +8,7 @@ from openapi_spec_validator import validate
|
||||
from scrobbler.lastfm.registry import METHODS
|
||||
|
||||
COMMITTED_SPEC = Path(__file__).resolve().parents[1] / "docs" / "openapi.json"
|
||||
DOCUMENTED_PREFIXES = ("/api/v1/", "/2.0/", "/api/auth/")
|
||||
DOCUMENTED_PREFIXES = ("/api/v1/", "/2.0/", "/api/auth/", "/healthz")
|
||||
HTTP_VERBS = {"get", "put", "post", "delete", "patch", "head", "options"}
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user