diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9aaa085 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,13 @@ +.git +.gitea +.venv +.idea +.junie +.env +**/__pycache__ +.pytest_cache +.ruff_cache +tests +docs +deploy/grafana +deploy/prometheus diff --git a/.env.example b/.env.example index 715b532..caea81c 100644 --- a/.env.example +++ b/.env.example @@ -12,3 +12,10 @@ UI_BASE_URL=http://localhost:8080 # Prometheus metrics are served on a separate port. METRICS_PORT=9100 + +# docker compose host ports (defaults shown) +API_PORT=5050 +UI_PORT=8080 +PROMETHEUS_PORT=9090 +GRAFANA_PORT=3000 +GRAFANA_ADMIN_PASSWORD=admin diff --git a/deploy/grafana/dashboards/api-overview.json b/deploy/grafana/dashboards/api-overview.json new file mode 100644 index 0000000..405c71c --- /dev/null +++ b/deploy/grafana/dashboards/api-overview.json @@ -0,0 +1,843 @@ +{ + "uid": "scrobbler-api-overview", + "title": "Scrobbler: API overview", + "description": "Rate, errors and duration for every endpoint of the Scrobbler API.", + "tags": [ + "scrobbler" + ], + "timezone": "browser", + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 41, + "version": 1, + "templating": { + "list": [ + { + "name": "endpoint", + "label": "Endpoint", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "query": { + "query": "label_values(scrobbler_http_requests_total, endpoint)", + "refId": "var" + }, + "definition": "label_values(scrobbler_http_requests_total, endpoint)", + "includeAll": true, + "multi": true, + "allValue": ".*", + "current": { + "selected": true, + "text": [ + "All" + ], + "value": [ + "$__all" + ] + }, + "refresh": 2, + "sort": 1 + } + ] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "type": "dashboards", + "tags": [ + "scrobbler" + ], + "asDropdown": true, + "title": "Scrobbler", + "includeVars": false + } + ], + "panels": [ + { + "type": "row", + "title": "Health", + "id": 1, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "API", + "description": "Is Prometheus able to scrape the API's metrics?", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "up{job=\"scrobbler-api\"}", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + }, + "mappings": [ + { + "type": "value", + "options": { + "0": { + "text": "Down", + "color": "red" + }, + "1": { + "text": "Up", + "color": "green" + } + } + } + ] + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 2, + "gridPos": { + "x": 0, + "y": 1, + "w": 4, + "h": 4 + } + }, + { + "type": "stat", + "title": "Requests / s", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(scrobbler_http_requests_total[$__rate_interval]))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "decimals": 2, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 3, + "gridPos": { + "x": 4, + "y": 1, + "w": 5, + "h": 4 + } + }, + { + "type": "stat", + "title": "Server errors", + "description": "Share of requests answered with a 5xx status.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(rate(scrobbler_http_requests_total{status=~\"5..\"}[$__rate_interval])) or vector(0)) / sum(rate(scrobbler_http_requests_total[$__rate_interval]))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "decimals": 2, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 0.01 + }, + { + "color": "red", + "value": 0.05 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 4, + "gridPos": { + "x": 9, + "y": 1, + "w": 5, + "h": 4 + } + }, + { + "type": "stat", + "title": "p95 latency", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "orange", + "value": 0.5 + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 5, + "gridPos": { + "x": 14, + "y": 1, + "w": 5, + "h": 4 + } + }, + { + "type": "stat", + "title": "Version", + "description": "Version reported by the running API.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (version) (scrobbler_build_info)", + "legendFormat": "{{version}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "name", + "justifyMode": "auto" + }, + "id": 6, + "gridPos": { + "x": 19, + "y": 1, + "w": 5, + "h": 4 + } + }, + { + "type": "row", + "title": "Traffic", + "id": 7, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 5, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Requests / s by endpoint", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (endpoint) (rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\"}[$__rate_interval]))", + "legendFormat": "{{endpoint}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 8, + "gridPos": { + "x": 0, + "y": 6, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Error ratio", + "description": "4xx is mostly clients (bad params, expired tokens); 5xx is us.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\",status=~\"5..\"}[$__rate_interval])) or vector(0)) / sum(rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\"}[$__rate_interval]))", + "legendFormat": "5xx", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "(sum(rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\",status=~\"4..\"}[$__rate_interval])) or vector(0)) / sum(rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\"}[$__rate_interval]))", + "legendFormat": "4xx", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "5xx" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "red" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "4xx" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "orange" + } + } + ] + } + ] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 9, + "gridPos": { + "x": 12, + "y": 6, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Requests / s by status", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (status) (rate(scrobbler_http_requests_total{endpoint=~\"$endpoint\"}[$__rate_interval]))", + "legendFormat": "{{status}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 10, + "gridPos": { + "x": 0, + "y": 14, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "In-flight requests", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (endpoint) (scrobbler_http_requests_in_progress{endpoint=~\"$endpoint\"})", + "legendFormat": "{{endpoint}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 11, + "gridPos": { + "x": 12, + "y": 14, + "w": 12, + "h": 8 + } + }, + { + "type": "row", + "title": "Latency", + "id": 12, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 22, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Latency percentiles", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"$endpoint\"}[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"$endpoint\"}[$__rate_interval])))", + "legendFormat": "p95", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"$endpoint\"}[$__rate_interval])))", + "legendFormat": "p99", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 13, + "gridPos": { + "x": 0, + "y": 23, + "w": 12, + "h": 9 + } + }, + { + "type": "timeseries", + "title": "p95 latency by endpoint", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, endpoint) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"$endpoint\"}[$__rate_interval])))", + "legendFormat": "{{endpoint}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 14, + "gridPos": { + "x": 12, + "y": 23, + "w": 12, + "h": 9 + } + }, + { + "type": "table", + "title": "Slowest endpoints (p95 over the selected range)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "topk(10, histogram_quantile(0.95, sum by (le, endpoint) (rate(scrobbler_http_request_duration_seconds_bucket[$__range]))))", + "legendFormat": "{{endpoint}}", + "refId": "A", + "instant": true, + "range": false, + "format": "table" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s" + }, + "overrides": [] + }, + "options": { + "showHeader": true, + "sortBy": [ + { + "displayName": "Value", + "desc": true + } + ] + }, + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true + }, + "renameByName": { + "Value": "p95" + } + } + } + ], + "id": 15, + "gridPos": { + "x": 0, + "y": 32, + "w": 24, + "h": 8 + } + } + ] +} diff --git a/deploy/grafana/dashboards/database.json b/deploy/grafana/dashboards/database.json new file mode 100644 index 0000000..f439529 --- /dev/null +++ b/deploy/grafana/dashboards/database.json @@ -0,0 +1,790 @@ +{ + "uid": "scrobbler-database", + "title": "Scrobbler: Database", + "description": "Query latency and pool use from the app's side; Postgres health from postgres-exporter.", + "tags": [ + "scrobbler" + ], + "timezone": "browser", + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 41, + "version": 1, + "templating": { + "list": [] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "type": "dashboards", + "tags": [ + "scrobbler" + ], + "asDropdown": true, + "title": "Scrobbler", + "includeVars": false + } + ], + "panels": [ + { + "type": "row", + "title": "From the API", + "id": 1, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Query latency by operation (p95)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, operation) (rate(scrobbler_db_query_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "{{operation}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 2, + "gridPos": { + "x": 0, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Queries / s by operation", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (operation) (rate(scrobbler_db_query_duration_seconds_count[$__rate_interval]))", + "legendFormat": "{{operation}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 3, + "gridPos": { + "x": 12, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Connection pool", + "description": "Summed across gunicorn workers. In use at or above pool size means requests are running on overflow connections.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(scrobbler_db_pool_connections{state=\"checked_out\"})", + "legendFormat": "in use", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(scrobbler_db_pool_connections{state=\"overflow\"})", + "legendFormat": "overflow", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(scrobbler_db_pool_connections{state=\"size\"})", + "legendFormat": "pool size", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "pool size" + }, + "properties": [ + { + "id": "custom.lineStyle", + "value": { + "fill": "dash", + "dash": [ + 10, + 10 + ] + } + }, + { + "id": "custom.fillOpacity", + "value": 0 + } + ] + } + ] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 4, + "gridPos": { + "x": 0, + "y": 9, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Query latency percentiles (all operations)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(scrobbler_db_query_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.99, sum by (le) (rate(scrobbler_db_query_duration_seconds_bucket[$__rate_interval])))", + "legendFormat": "p99", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 5, + "gridPos": { + "x": 12, + "y": 9, + "w": 12, + "h": 8 + } + }, + { + "type": "row", + "title": "Postgres", + "id": 6, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 17, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Postgres", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "pg_up", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + }, + "mappings": [ + { + "type": "value", + "options": { + "0": { + "text": "Down", + "color": "red" + }, + "1": { + "text": "Up", + "color": "green" + } + } + } + ] + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 7, + "gridPos": { + "x": 0, + "y": 18, + "w": 4, + "h": 5 + } + }, + { + "type": "stat", + "title": "Database size", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "pg_database_size_bytes{datname=\"scrobbler\"}", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 8, + "gridPos": { + "x": 4, + "y": 18, + "w": 5, + "h": 5 + } + }, + { + "type": "stat", + "title": "Connections", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(pg_stat_database_numbackends{datname=\"scrobbler\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 9, + "gridPos": { + "x": 9, + "y": 18, + "w": 5, + "h": 5 + } + }, + { + "type": "stat", + "title": "Cache hit ratio", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(pg_stat_database_blks_hit{datname=\"scrobbler\"}[$__rate_interval])) / (sum(rate(pg_stat_database_blks_hit{datname=\"scrobbler\"}[$__rate_interval])) + sum(rate(pg_stat_database_blks_read{datname=\"scrobbler\"}[$__rate_interval])))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percentunit", + "decimals": 1, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": null + }, + { + "color": "orange", + "value": 0.9 + }, + { + "color": "green", + "value": 0.99 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 10, + "gridPos": { + "x": 14, + "y": 18, + "w": 5, + "h": 5 + } + }, + { + "type": "stat", + "title": "Deadlocks (range)", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(pg_stat_database_deadlocks{datname=\"scrobbler\"}[$__range]))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "green", + "value": null + }, + { + "color": "red", + "value": 1 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 11, + "gridPos": { + "x": 19, + "y": 18, + "w": 5, + "h": 5 + } + }, + { + "type": "timeseries", + "title": "Transactions / s", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(pg_stat_database_xact_commit{datname=\"scrobbler\"}[$__rate_interval]))", + "legendFormat": "commits", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(pg_stat_database_xact_rollback{datname=\"scrobbler\"}[$__rate_interval]))", + "legendFormat": "rollbacks", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "ops", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 12, + "gridPos": { + "x": 0, + "y": 23, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Locks by mode", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (mode) (pg_locks_count{datname=\"scrobbler\"})", + "legendFormat": "{{mode}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 13, + "gridPos": { + "x": 12, + "y": 23, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Database size", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "pg_database_size_bytes{datname=\"scrobbler\"}", + "legendFormat": "scrobbler", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "bytes", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + } + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 14, + "gridPos": { + "x": 0, + "y": 31, + "w": 24, + "h": 7 + } + } + ] +} diff --git a/deploy/grafana/dashboards/lastfm-api.json b/deploy/grafana/dashboards/lastfm-api.json new file mode 100644 index 0000000..8b27dd8 --- /dev/null +++ b/deploy/grafana/dashboards/lastfm-api.json @@ -0,0 +1,656 @@ +{ + "uid": "scrobbler-lastfm", + "title": "Scrobbler: Last.fm API", + "description": "The Last.fm-compatible /2.0/ API: which methods clients call, what fails, and what happens to scrobbles.", + "tags": [ + "scrobbler" + ], + "timezone": "browser", + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 41, + "version": 1, + "templating": { + "list": [ + { + "name": "method", + "label": "Method", + "type": "query", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "query": { + "query": "label_values(scrobbler_lastfm_requests_total, lastfm_method)", + "refId": "var" + }, + "definition": "label_values(scrobbler_lastfm_requests_total, lastfm_method)", + "includeAll": true, + "multi": true, + "allValue": ".*", + "current": { + "selected": true, + "text": [ + "All" + ], + "value": [ + "$__all" + ] + }, + "refresh": 2, + "sort": 1 + } + ] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "type": "dashboards", + "tags": [ + "scrobbler" + ], + "asDropdown": true, + "title": "Scrobbler", + "includeVars": false + } + ], + "panels": [ + { + "type": "row", + "title": "Calls", + "id": 1, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Calls / s by method", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (lastfm_method) (rate(scrobbler_lastfm_requests_total{lastfm_method=~\"$method\"}[$__rate_interval]))", + "legendFormat": "{{lastfm_method}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 2, + "gridPos": { + "x": 0, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "p95 latency by method", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, lastfm_method) (rate(scrobbler_lastfm_request_duration_seconds_bucket{lastfm_method=~\"$method\"}[$__rate_interval])))", + "legendFormat": "{{lastfm_method}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 3, + "gridPos": { + "x": 12, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Errors by Last.fm code", + "description": "3 unknown method, 4 bad password/token, 6 bad parameters, 9 bad session key, 10 bad API key, 13 bad signature, 14 unapproved token, 15 expired token.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (code) (rate(scrobbler_lastfm_errors_total{lastfm_method=~\"$method\"}[$__rate_interval]))", + "legendFormat": "error {{code}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 4, + "gridPos": { + "x": 0, + "y": 9, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Authentication failures by reason", + "description": "Includes both Last.fm and signature failures. A spike from one reason usually means one misconfigured client.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (reason) (rate(scrobbler_auth_failures_total[$__rate_interval]))", + "legendFormat": "{{reason}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 5, + "gridPos": { + "x": 12, + "y": 9, + "w": 12, + "h": 8 + } + }, + { + "type": "row", + "title": "Scrobbles", + "id": 6, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 17, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Scrobbles / min by result", + "description": "Duplicates are resubmissions of scrobbles already stored (normal for clients that retry).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_scrobbles_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "accepted" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "green" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "duplicate" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "blue" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "ignored" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "orange" + } + } + ] + } + ] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 7, + "gridPos": { + "x": 0, + "y": 18, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Ignored scrobbles by reason", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_ignored_total{reason=\"1\"}[$__rate_interval]))", + "legendFormat": "Empty artist", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_ignored_total{reason=\"2\"}[$__rate_interval]))", + "legendFormat": "Empty track", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_ignored_total{reason=\"3\"}[$__rate_interval]))", + "legendFormat": "Too old (>14 days)", + "refId": "C" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_ignored_total{reason=\"4\"}[$__rate_interval]))", + "legendFormat": "In the future", + "refId": "D" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + }, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 8, + "gridPos": { + "x": 12, + "y": 18, + "w": 12, + "h": 8 + } + }, + { + "type": "heatmap", + "title": "Tracks per scrobble request", + "description": "Large batches are clients flushing an offline cache.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (le) (increase(scrobbler_scrobble_batch_size_bucket[$__rate_interval]))", + "legendFormat": "{{le}}", + "refId": "A", + "format": "heatmap" + } + ], + "options": { + "calculate": false, + "yAxis": { + "unit": "short" + }, + "color": { + "mode": "scheme", + "scheme": "Oranges", + "steps": 64 + }, + "cellGap": 1, + "tooltip": { + "mode": "single", + "yHistogram": true + } + }, + "id": 9, + "gridPos": { + "x": 0, + "y": 26, + "w": 8, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Scrobble lag", + "description": "Time between a track being played and its scrobble arriving.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(scrobbler_scrobble_lag_seconds_bucket[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_scrobble_lag_seconds_bucket[$__rate_interval])))", + "legendFormat": "p95", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 10, + "gridPos": { + "x": 8, + "y": 26, + "w": 8, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Now playing & sign-ins", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(scrobbler_now_playing_updates_total[$__rate_interval])) * 60", + "legendFormat": "now-playing updates / min", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (flow) (increase(scrobbler_auth_sessions_created_total[$__rate_interval]))", + "legendFormat": "sessions created ({{flow}})", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 11, + "gridPos": { + "x": 16, + "y": 26, + "w": 8, + "h": 8 + } + } + ] +} diff --git a/deploy/grafana/dashboards/usage.json b/deploy/grafana/dashboards/usage.json new file mode 100644 index 0000000..961918b --- /dev/null +++ b/deploy/grafana/dashboards/usage.json @@ -0,0 +1,574 @@ +{ + "uid": "scrobbler-usage", + "title": "Scrobbler: Usage", + "description": "Who is using the service and how much they're listening.", + "tags": [ + "scrobbler" + ], + "timezone": "browser", + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 41, + "version": 1, + "templating": { + "list": [] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "type": "dashboards", + "tags": [ + "scrobbler" + ], + "asDropdown": true, + "title": "Scrobbler", + "includeVars": false + } + ], + "panels": [ + { + "type": "row", + "title": "Now", + "id": 1, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Scrobbles in the last 24h", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_total{result=\"accepted\"}[24h]))", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0, + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 2, + "gridPos": { + "x": 0, + "y": 1, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Users", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_users)", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 3, + "gridPos": { + "x": 6, + "y": 1, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Active in the last 24h", + "description": "Users with at least one scrobble in the last 24 hours.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_active_users{window=\"24h\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 4, + "gridPos": { + "x": 12, + "y": 1, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Listening now", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_now_playing_active)", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 5, + "gridPos": { + "x": 18, + "y": 1, + "w": 6, + "h": 5 + } + }, + { + "type": "row", + "title": "Listening", + "id": 6, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 6, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Scrobbles / min", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(rate(scrobbler_scrobbles_total{result=\"accepted\"}[$__rate_interval])) * 60", + "legendFormat": "accepted", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 7, + "gridPos": { + "x": 0, + "y": 7, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Listening now", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_now_playing_active)", + "legendFormat": "users playing a track", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 8, + "gridPos": { + "x": 12, + "y": 7, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Scrobbles per day", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_scrobbles_total{result=\"accepted\"}[1d]))", + "legendFormat": "scrobbles", + "refId": "A", + "interval": "1d" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "timeFrom": "30d", + "id": 9, + "gridPos": { + "x": 0, + "y": 15, + "w": 24, + "h": 8 + } + }, + { + "type": "row", + "title": "People", + "id": 10, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 23, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Active users", + "description": "Distinct users scrobbling within each window.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max by (window) (scrobbler_active_users)", + "legendFormat": "{{window}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 11, + "gridPos": { + "x": 0, + "y": 24, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Sign-ups and web logins", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_registrations_total[$__rate_interval]))", + "legendFormat": "registrations", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_ui_logins_total{result=\"success\"}[$__rate_interval]))", + "legendFormat": "logins", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum(increase(scrobbler_ui_logins_total{result=\"failure\"}[$__rate_interval]))", + "legendFormat": "failed logins", + "refId": "C" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 12, + "gridPos": { + "x": 12, + "y": 24, + "w": 12, + "h": 8 + } + } + ] +} diff --git a/deploy/grafana/provisioning/dashboards/dashboards.yml b/deploy/grafana/provisioning/dashboards/dashboards.yml new file mode 100644 index 0000000..6fd7be4 --- /dev/null +++ b/deploy/grafana/provisioning/dashboards/dashboards.yml @@ -0,0 +1,8 @@ +apiVersion: 1 +providers: + - name: scrobbler + folder: Scrobbler + type: file + allowUiUpdates: true + options: + path: /var/lib/grafana/dashboards diff --git a/deploy/grafana/provisioning/datasources/prometheus.yml b/deploy/grafana/provisioning/datasources/prometheus.yml new file mode 100644 index 0000000..a1b3124 --- /dev/null +++ b/deploy/grafana/provisioning/datasources/prometheus.yml @@ -0,0 +1,10 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + jsonData: + timeInterval: 15s diff --git a/deploy/nginx/default.conf.template b/deploy/nginx/default.conf.template new file mode 100644 index 0000000..9b8ef32 --- /dev/null +++ b/deploy/nginx/default.conf.template @@ -0,0 +1,23 @@ +# Rendered by the nginx image's envsubst step (API_BASE_URL comes from the environment). +server { + listen 80; + server_name _; + root /usr/share/nginx/html; + index index.html; + server_tokens off; + + # add_header isn't inherited by locations that set their own, so the security + # headers live in the location that serves pages. + location / { + try_files $uri $uri/ =404; + # Files aren't fingerprinted, so always revalidate. + add_header Cache-Control "no-cache"; + add_header Content-Security-Policy "default-src 'self'; connect-src 'self' ${API_BASE_URL}; img-src 'self' data:; style-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always; + add_header X-Content-Type-Options nosniff always; + add_header Referrer-Policy same-origin always; + } + + location /fonts/ { + add_header Cache-Control "public, max-age=2592000, immutable"; + } +} diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml new file mode 100644 index 0000000..88e7532 --- /dev/null +++ b/deploy/prometheus/alerts.yml @@ -0,0 +1,65 @@ +groups: + - name: scrobbler + rules: + - alert: ScrobblerDown + expr: up{job="scrobbler-api"} == 0 + for: 2m + labels: {severity: critical} + annotations: + summary: Scrobbler API metrics endpoint is down + description: Prometheus hasn't been able to scrape {{ $labels.instance }} for 2 minutes. + + - alert: HighErrorRate + expr: | + sum(rate(scrobbler_http_requests_total{status=~"5.."}[5m])) + / sum(rate(scrobbler_http_requests_total[5m])) > 0.05 + for: 5m + labels: {severity: critical} + annotations: + summary: More than 5% of API requests are failing + description: 5xx ratio is {{ $value | humanizePercentage }}. + + - alert: HighLatency + expr: | + histogram_quantile(0.95, + sum by (le) (rate(scrobbler_http_request_duration_seconds_bucket[5m]))) > 1 + for: 10m + labels: {severity: warning} + annotations: + summary: API p95 latency is above 1s + description: p95 latency is {{ $value | humanizeDuration }}. + + - alert: AuthFailureSpike + expr: sum(rate(scrobbler_auth_failures_total[5m])) > 10 + for: 5m + labels: {severity: warning} + annotations: + summary: Unusually many authentication failures + description: "{{ $value | humanize }} failures/s: check for a misconfigured client or credential stuffing." + + - alert: ScrobbleIgnoreRateHigh + expr: | + sum(rate(scrobbler_scrobbles_total{result="ignored"}[15m])) + / sum(rate(scrobbler_scrobbles_total[15m])) > 0.2 + for: 15m + labels: {severity: warning} + annotations: + summary: More than 20% of scrobbles are being ignored + description: A client may be sending bad timestamps or empty metadata. + + - alert: DBPoolExhausted + expr: | + sum(scrobbler_db_pool_connections{state="checked_out"}) + >= sum(scrobbler_db_pool_connections{state="size"}) + for: 5m + labels: {severity: warning} + annotations: + summary: Every pooled database connection is in use + description: Workers are running on overflow connections; requests may queue. + + - alert: PostgresDown + expr: pg_up == 0 + for: 2m + labels: {severity: critical} + annotations: + summary: Postgres is unreachable from postgres-exporter diff --git a/deploy/prometheus/prometheus.yml b/deploy/prometheus/prometheus.yml new file mode 100644 index 0000000..d1e3bd8 --- /dev/null +++ b/deploy/prometheus/prometheus.yml @@ -0,0 +1,19 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +rule_files: + - alerts.yml + +scrape_configs: + - job_name: scrobbler-api + static_configs: + - targets: ["api:9100"] + + - job_name: postgres + static_configs: + - targets: ["postgres-exporter:9187"] + + - job_name: prometheus + static_configs: + - targets: ["localhost:9090"] diff --git a/docker-compose.yml b/docker-compose.yml index 2b90392..d4b650c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,14 @@ +# Core services: docker compose up +# With monitoring: docker compose --profile monitoring up +# Published images: SCROBBLER_IMAGE_TAG=main docker compose up --no-build +name: scrobbler + services: db: image: postgres:16 environment: POSTGRES_USER: scrobbler - POSTGRES_PASSWORD: scrobbler + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-scrobbler} POSTGRES_DB: scrobbler ports: - "${DB_PORT:-5432}:5432" @@ -16,5 +21,76 @@ services: timeout: 3s retries: 10 + api: + image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local} + build: + context: . + dockerfile: docker/api.Dockerfile + environment: + DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler + SECRET_KEY: ${SECRET_KEY:-change-me} + CORS_ORIGINS: ${UI_BASE_URL:-http://localhost:8080} + UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080} + WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} + FORWARDED_ALLOW_IPS: "*" + ports: + - "${API_PORT:-5050}:8000" + expose: + - "9100" # metrics: internal network only + depends_on: + db: + condition: service_healthy + + ui: + image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-ui:${SCROBBLER_IMAGE_TAG:-local} + build: + context: . + dockerfile: docker/ui.Dockerfile + environment: + API_BASE_URL: ${API_BASE_URL:-http://localhost:5050} + ports: + - "${UI_PORT:-8080}:80" + + prometheus: + profiles: [monitoring] + image: prom/prometheus:v3.5.0 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.retention.time=30d + volumes: + - ./deploy/prometheus:/etc/prometheus:ro + - prometheus-data:/prometheus + ports: + - "${PROMETHEUS_PORT:-9090}:9090" + + postgres-exporter: + profiles: [monitoring] + image: quay.io/prometheuscommunity/postgres-exporter:v0.17.1 + environment: + DATA_SOURCE_URI: db:5432/scrobbler?sslmode=disable + DATA_SOURCE_USER: scrobbler + DATA_SOURCE_PASS: ${POSTGRES_PASSWORD:-scrobbler} + depends_on: + db: + condition: service_healthy + + grafana: + profiles: [monitoring] + image: grafana/grafana:12.1.0 + environment: + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin} + GF_USERS_ALLOW_SIGN_UP: "false" + GF_DASHBOARDS_DEFAULT_HOME_DASHBOARD_PATH: /var/lib/grafana/dashboards/api-overview.json + volumes: + - ./deploy/grafana/provisioning:/etc/grafana/provisioning:ro + - ./deploy/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafana-data:/var/lib/grafana + ports: + - "${GRAFANA_PORT:-3000}:3000" + depends_on: + - prometheus + volumes: db-data: + prometheus-data: + grafana-data: diff --git a/docker/api-entrypoint.sh b/docker/api-entrypoint.sh new file mode 100755 index 0000000..72c75ea --- /dev/null +++ b/docker/api-entrypoint.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# Apply database migrations (unless RUN_MIGRATIONS=0), then start the given command. +set -e +if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then + # Not under gunicorn, so don't use (or pollute) the multiprocess metrics directory. + env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade +fi +exec "$@" diff --git a/docker/api.Dockerfile b/docker/api.Dockerfile new file mode 100644 index 0000000..538d662 --- /dev/null +++ b/docker/api.Dockerfile @@ -0,0 +1,29 @@ +# Scrobbler API: gunicorn serving the Flask app, metrics on :9100. +FROM ghcr.io/astral-sh/uv:0.7.21 AS uv + +FROM python:3.13-slim AS build +COPY --from=uv /uv /usr/local/bin/uv +ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy UV_PYTHON_DOWNLOADS=never +WORKDIR /app +COPY pyproject.toml uv.lock ./ +RUN uv sync --locked --no-dev --no-install-project +COPY src ./src +RUN uv sync --locked --no-dev --no-editable + +FROM python:3.13-slim +RUN useradd --system --uid 10001 --no-create-home scrobbler +WORKDIR /app +COPY --from=build /app/.venv /app/.venv +COPY gunicorn.conf.py docker/api-entrypoint.sh ./ +ENV PATH=/app/.venv/bin:$PATH \ + PYTHONUNBUFFERED=1 \ + PROMETHEUS_MULTIPROC_DIR=/tmp/scrobbler-metrics \ + BIND=0.0.0.0:8000 \ + METRICS_PORT=9100 \ + OPENAPI_DOCS_ENABLED=1 +USER scrobbler +EXPOSE 8000 9100 +HEALTHCHECK --interval=15s --timeout=3s --start-period=20s \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)" +ENTRYPOINT ["./api-entrypoint.sh"] +CMD ["gunicorn", "-c", "gunicorn.conf.py"] diff --git a/docker/ui-config.sh b/docker/ui-config.sh new file mode 100755 index 0000000..0595b80 --- /dev/null +++ b/docker/ui-config.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Point the UI at the API: rewrite config.js from $API_BASE_URL at container start. +set -e +case "$API_BASE_URL" in + http://*|https://*) ;; + *) echo "API_BASE_URL must start with http:// or https://" >&2; exit 1 ;; +esac +url=$(printf '%s' "$API_BASE_URL" | sed 's#/*$##; s#["\\]##g') +cat > /usr/share/nginx/html/config.js </dev/null || exit 1 diff --git a/docs/openapi.json b/docs/openapi.json index b759e2e..decf6ce 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -992,6 +992,40 @@ ] } }, + "/healthz": { + "get": { + "responses": { + "503": { + "description": "The database is unreachable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Health check", + "description": "Returns 200 when the API can reach its database.", + "tags": [ + "Health" + ] + } + }, "/2.0/": { "get": { "tags": [ @@ -1495,6 +1529,10 @@ "name": "Stats", "description": "Your listening history and statistics" }, + { + "name": "Health", + "description": "Liveness for load balancers and containers" + }, { "name": "Last.fm", "description": "Last.fm-compatible API for players and scrobblers" @@ -1936,6 +1974,16 @@ }, "additionalProperties": false }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "example": "ok" + } + }, + "additionalProperties": false + }, "LastfmError": { "type": "object", "properties": { diff --git a/frontend/js/dom.js b/frontend/js/dom.js index 53104ac..883a8f0 100644 --- a/frontend/js/dom.js +++ b/frontend/js/dom.js @@ -7,6 +7,8 @@ export function h(tag, attrs = {}, ...children) { if (value === false || value === null || value === undefined) continue; if (key.startsWith("on") && typeof value === "function") el.addEventListener(key.slice(2), value); else if (key === "class") el.className = value; + // CSSOM, not a style attribute, so it's allowed by the UI's CSP (style-src 'self'). + else if (key === "style") el.style.cssText = value; else if (key === "dataset") Object.assign(el.dataset, value); else el.setAttribute(key, value === true ? "" : String(value)); } diff --git a/pyproject.toml b/pyproject.toml index d9f8a54..e05e52a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -40,6 +40,7 @@ dev = [ "openapi-spec-validator>=0.9.0", "pylast>=7.1.0", "pytest>=9.1.1", + "pyyaml>=6.0.3", "ruff>=0.16.9", ] diff --git a/scripts/generate_traffic.py b/scripts/generate_traffic.py new file mode 100644 index 0000000..3c786a2 --- /dev/null +++ b/scripts/generate_traffic.py @@ -0,0 +1,164 @@ +"""Send realistic traffic to a running Scrobbler, e.g. to see the Grafana dashboards move. + + uv run python scripts/generate_traffic.py --api http://localhost:5050 --minutes 5 + +Uses only the public APIs: registers (or logs in) a user, creates an API app, signs in +like a player, then loops scrobbling, updating now-playing and reading stats. A share +of requests are deliberately bad (ignored scrobbles, bad signatures, wrong passwords) +so the error panels have something to show. +""" + +import argparse +import json +import random +import time +import urllib.error +import urllib.parse +import urllib.request + +from scrobbler.lastfm.signature import sign + +LIBRARY = [ + ("Radiohead", "In Rainbows", ["Reckoner", "Nude", "Weird Fishes/Arpeggi", "House of Cards"]), + ("Björk", "Homogenic", ["Jóga", "Hunter", "Bachelorette", "All Is Full of Love"]), + ("Portishead", "Dummy", ["Roads", "Glory Box", "Sour Times"]), + ("Boards of Canada", "Music Has the Right to Children", ["Roygbiv", "Aquarius"]), + ("Khruangbin", "Con Todo El Mundo", ["Maria También", "Friday Morning"]), + ("Little Simz", "Sometimes I Might Be Introvert", ["Introvert", "Woman"]), +] + + +class Client: + def __init__(self, api: str): + self.api = api.rstrip("/") + self.token = None + self.key = self.secret = self.sk = None + + def rest(self, method, path, body=None): + req = urllib.request.Request( + f"{self.api}/api/v1{path}", + method=method, + data=json.dumps(body).encode() if body is not None else None, + headers={ + "Content-Type": "application/json", + **({"Authorization": f"Bearer {self.token}"} if self.token else {}), + }, + ) + try: + with urllib.request.urlopen(req, timeout=10) as response: + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as err: + return err.code, json.loads(err.read() or b"null") + + def lastfm(self, method, *, signed=True, session=False, bad_sig=False, **params): + params = {"method": method, "api_key": self.key, **params} + if session: + params["sk"] = self.sk + if signed: + params["api_sig"] = "0" * 32 if bad_sig else sign(params, self.secret) + data = urllib.parse.urlencode({**params, "format": "json"}).encode() + try: + with urllib.request.urlopen(f"{self.api}/2.0/", data, timeout=10) as response: + return json.load(response) + except urllib.error.HTTPError as err: + return json.load(err) + + +def setup(client: Client, username: str, password: str) -> None: + status, body = client.rest( + "POST", + "/auth/register", + {"username": username, "email": f"{username}@example.com", "password": password}, + ) + if status == 409: + status, body = client.rest( + "POST", "/auth/login", {"username": username, "password": password} + ) + if status not in (200, 201): + raise SystemExit(f"could not sign in as {username}: {body}") + client.token = body["token"] + _, apps = client.rest("GET", "/apps") + app = apps[0] if apps else client.rest("POST", "/apps", {"name": "Traffic generator"})[1] + client.key, client.secret = app["api_key"], app["shared_secret"] + session = client.lastfm("auth.getMobileSession", username=username, password=password) + client.sk = session["session"]["key"] + + +def random_track(offset_seconds: int) -> dict: + artist, album, tracks = random.choice(LIBRARY) + return { + "artist": artist, + "album": album, + "track": random.choice(tracks), + "duration": str(random.randint(150, 360)), + "timestamp": str(int(time.time()) - offset_seconds), + } + + +def batch_params(tracks: list[dict]) -> dict: + return {f"{k}[{i}]": v for i, t in enumerate(tracks) for k, v in t.items()} + + +def tick(client: Client, username: str) -> None: + roll = random.random() + if roll < 0.35: + track = random_track(0) + client.lastfm( + "track.updateNowPlaying", + session=True, + **{k: v for k, v in track.items() if k != "timestamp"}, + ) + elif roll < 0.65: + tracks = [ + random_track(random.randint(60, 3600)) for _ in range(random.choice([1, 1, 2, 5])) + ] + client.lastfm("track.scrobble", session=True, **batch_params(tracks)) + elif roll < 0.70: + # Offline cache flush: a big batch of older plays + tracks = [ + random_track(random.randint(3600, 5 * 86400)) for _ in range(random.randint(10, 50)) + ] + client.lastfm("track.scrobble", session=True, **batch_params(tracks)) + elif roll < 0.75: + # Ignored scrobbles: too old, in the future, empty artist + bad = random.choice( + [random_track(20 * 86400), random_track(-7200), {**random_track(60), "artist": ""}] + ) + client.lastfm("track.scrobble", session=True, **batch_params([bad])) + elif roll < 0.78: + client.lastfm( + "track.scrobble", session=True, bad_sig=True, **batch_params([random_track(60)]) + ) + elif roll < 0.80: + client.rest("POST", "/auth/login", {"username": username, "password": "wrong-password"}) + elif roll < 0.90: + path = random.choice(["/me/summary", "/me/recent", "/me/now-playing", "/me/counts"]) + client.rest("GET", path) + client.rest("GET", f"/me/top/{random.choice(['artists', 'albums', 'tracks'])}?period=7day") + else: + method = random.choice(["user.getRecentTracks", "user.getTopArtists", "user.getInfo"]) + client.lastfm(method, signed=False, user=username) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--api", default="http://localhost:5050") + parser.add_argument("--username", default="traffic") + parser.add_argument("--password", default="traffic-password") + parser.add_argument("--minutes", type=float, default=5) + parser.add_argument("--rate", type=float, default=5, help="requests per second") + args = parser.parse_args() + + client = Client(args.api) + setup(client, args.username, args.password) + end = time.time() + args.minutes * 60 + sent = 0 + while time.time() < end: + tick(client, args.username) + sent += 1 + time.sleep(random.expovariate(args.rate)) + print(f"sent {sent} requests") + + +if __name__ == "__main__": + main() diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index 7a520ab..ebd89ac 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -43,13 +43,14 @@ def init_app(app: Flask) -> None: }, ) - from scrobbler.api import apps, auth, sessions, stats, tokens + from scrobbler.api import apps, auth, health, sessions, stats, tokens api.register_blueprint(auth.blp, url_prefix="/api/v1/auth") api.register_blueprint(apps.blp, url_prefix="/api/v1/apps") api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions") api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens") api.register_blueprint(stats.blp, url_prefix="/api/v1/me") + api.register_blueprint(health.blp) from scrobbler.openapi import lastfm diff --git a/src/scrobbler/api/health.py b/src/scrobbler/api/health.py new file mode 100644 index 0000000..86b5acb --- /dev/null +++ b/src/scrobbler/api/health.py @@ -0,0 +1,28 @@ +from flask_smorest import Blueprint, abort +from marshmallow import Schema, fields +from sqlalchemy import text + +from scrobbler.extensions import db +from scrobbler.schemas import ErrorSchema + +blp = Blueprint("Health", __name__, description="Liveness for load balancers and containers") + + +class HealthSchema(Schema): + status = fields.String(metadata={"example": "ok"}) + + +@blp.route("/healthz", methods=["GET"]) +@blp.response(200, HealthSchema) +@blp.alt_response(503, schema=ErrorSchema, description="The database is unreachable") +def healthz(): + """Health check + + Returns 200 when the API can reach its database. + """ + try: + db.session.execute(text("SELECT 1")) + except Exception: + db.session.rollback() + abort(503, code="database_unavailable", message="The database is unreachable") + return {"status": "ok"} diff --git a/src/scrobbler/metrics/db.py b/src/scrobbler/metrics/db.py index 4947f6f..9409365 100644 --- a/src/scrobbler/metrics/db.py +++ b/src/scrobbler/metrics/db.py @@ -34,15 +34,26 @@ def instrument(engine: Engine) -> None: stack.pop() pool = engine.pool + if not hasattr(pool, "size"): # e.g. NullPool in tools: nothing worth reporting + return + checked_out = metrics.db_pool_connections.labels(state="checked_out") + overflow = metrics.db_pool_connections.labels(state="overflow") + metrics.db_pool_connections.labels(state="size").set(pool.size()) - 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()) + # Pool events fire before the pool updates its own counters, so reading + # pool.checkedout() inside them is off by one; count the events instead. + @event.listens_for(pool, "checkout") + def _checkout(*_args): + checked_out.inc() - for name in ("connect", "checkout", "checkin", "close"): - event.listen(pool, name, _report_pool) + @event.listens_for(pool, "checkin") + def _checkin(*_args): + checked_out.dec() + + @event.listens_for(pool, "connect") + def _connect(*_args): + overflow.set(max(0, pool.overflow())) + + @event.listens_for(pool, "close") + def _close(*_args): + overflow.set(max(0, pool.overflow())) diff --git a/tests/test_app.py b/tests/test_app.py index a282a79..d7c4af8 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -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"} diff --git a/tests/test_dashboards.py b/tests/test_dashboards.py new file mode 100644 index 0000000..f2cbc02 --- /dev/null +++ b/tests/test_dashboards.py @@ -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())}" diff --git a/tests/test_metrics.py b/tests/test_metrics.py index ff86498..1a7da4b 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -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): diff --git a/tests/test_openapi.py b/tests/test_openapi.py index da5b309..8e84d9f 100644 --- a/tests/test_openapi.py +++ b/tests/test_openapi.py @@ -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"} diff --git a/uv.lock b/uv.lock index cad86ad..f408730 100644 --- a/uv.lock +++ b/uv.lock @@ -846,6 +846,7 @@ dev = [ { name = "openapi-spec-validator" }, { name = "pylast" }, { name = "pytest" }, + { name = "pyyaml" }, { name = "ruff" }, ] @@ -867,6 +868,7 @@ dev = [ { name = "openapi-spec-validator", specifier = ">=0.9.0" }, { name = "pylast", specifier = ">=7.1.0" }, { name = "pytest", specifier = ">=9.1.1" }, + { name = "pyyaml", specifier = ">=6.0.3" }, { name = "ruff", specifier = ">=0.16.9" }, ]