observability: metrics, dashboard and morning check for the debrid pipeline
The rdtc incident was reconstructed from SQLite by hand because nothing was watching. Now three layers exist: * rdtc-async-add serves /metrics (adds accepted/deduped/delivered/failed, retries, delivery histogram); two tests pin the counters. * tools/debrid-metrics merges that with rdtc's queue health (pending rows with no provider id, torrents stuck at 0%, oldest pending age) and nginx's add-request log (latency histogram, 499/504 counts) into one node_exporter textfile every 15s. The access log is parsed incrementally with an inode and offset state file, so restarts do not double-count or lose lines. * tools/rtdc-health/check.sh answers 'did it work overnight' from Prometheus, the rdtc database and logs, and Radarr's log, and exits non-zero on failure. Also fixes the reason the incident was invisible: rdtc logged nothing because General:LogLevel was 4 (Error) and DownloadClient:LogLevel 5 (Fatal). Both are now Information/Debug, journald is persistent with a 2G cap, and the rdtc API vhost writes a dedicated access log with $request_time. Grafana dashboard debrid-pipeline (13 panels) is provisioned on xatu and live.
This commit is contained in:
1 parent
faa175809d
commit
0502804032
8 files changed
+1364
-5
No files matched your search
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=Export debrid pipeline metrics for node_exporter
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/bin/debrid_metrics.py
|
||||
Nice=10
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Run debrid pipeline metrics export every 15s
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=15s
|
||||
AccuracySec=1s
|
||||
Unit=debrid-metrics.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write debrid-pipeline metrics for yveltal's node_exporter textfile collector.
|
||||
|
||||
Three sources, one .prom file:
|
||||
|
||||
1. rdtc-async-add's own /metrics (counters and delivery histogram)
|
||||
2. rdtc's SQLite database (queue health: the "stuck without a provider id" symptom)
|
||||
3. nginx's rdtc-api access log (client-visible add latency, 499s, 504s)
|
||||
|
||||
The access log is parsed incrementally: the byte offset and the cumulative counters
|
||||
live in a state file, so restarts and log rotation do not lose or double-count.
|
||||
Runs every 15s from a systemd timer. Exits non-zero only on an internal error;
|
||||
unreachable sources are reported as *up 0 instead.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
SHIM_METRICS = "http://127.0.0.1:6502/metrics"
|
||||
DB = "/home/ziadarafat/.local/share/rdtc-fresh/db/rdtclient.db"
|
||||
ACCESS_LOG = "/var/log/nginx/rdtc-api.log"
|
||||
STATE = "/var/lib/debrid-metrics/state.json"
|
||||
OUT = "/var/lib/node_exporter/textfile/debrid.prom"
|
||||
|
||||
ADD_URI = "/api/v2/torrents/add"
|
||||
LATENCY_BUCKETS = [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 100]
|
||||
STUCK_MIN_AGE = 15 * 60 # a 0%-progress torrent older than this is jammed
|
||||
|
||||
LINE = re.compile(
|
||||
r'^(?P<ts>\S+) (?P<ip>\S+) (?P<method>\S+) (?P<uri>\S+) (?P<status>\d{3}) '
|
||||
r'(?P<rt>[\d.]+) (?P<urt>[\d.-]+) (?P<bytes>\d+)$'
|
||||
)
|
||||
|
||||
|
||||
def load_state() -> dict:
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def save_state(state: dict) -> None:
|
||||
os.makedirs(os.path.dirname(STATE), exist_ok=True)
|
||||
tmp = STATE + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
json.dump(state, f)
|
||||
os.replace(tmp, STATE)
|
||||
|
||||
|
||||
def shim_metrics():
|
||||
"""The proxy's own exposition, passed through, plus an availability gauge."""
|
||||
try:
|
||||
with urllib.request.urlopen(SHIM_METRICS, timeout=5) as r:
|
||||
body = r.read().decode()
|
||||
return body, 1
|
||||
except Exception:
|
||||
return "", 0
|
||||
|
||||
|
||||
def rdtc_metrics():
|
||||
"""Queue health straight from rdtc's database."""
|
||||
out = []
|
||||
up = 1
|
||||
try:
|
||||
con = sqlite3.connect(f"file:{DB}?mode=ro", uri=True, timeout=5)
|
||||
con.row_factory = sqlite3.Row
|
||||
now = time.time()
|
||||
|
||||
rows = con.execute(
|
||||
'select RdStatus, RdId, RdProgress, Added from Torrents'
|
||||
).fetchall()
|
||||
|
||||
by_status: dict[int, int] = {}
|
||||
no_provider = 0
|
||||
stuck = 0
|
||||
oldest_pending = 0.0
|
||||
for r in rows:
|
||||
status = r["RdStatus"] or 0
|
||||
by_status[status] = by_status.get(status, 0) + 1
|
||||
if status in (0, 1) and not r["RdId"]:
|
||||
no_provider += 1
|
||||
age = 0.0
|
||||
if r["Added"]:
|
||||
try:
|
||||
iso = str(r["Added"]).replace("Z", "+00:00")
|
||||
age = now - time.mktime(time.strptime(iso[:19], "%Y-%m-%d %H:%M:%S"))
|
||||
except ValueError:
|
||||
age = 0.0
|
||||
if status in (0, 1):
|
||||
oldest_pending = max(oldest_pending, age)
|
||||
if age > STUCK_MIN_AGE and (r["RdProgress"] or 0) == 0:
|
||||
stuck += 1
|
||||
|
||||
out.append(("# HELP debrid_rdtc_torrents_total Torrent rows rdtc holds.", "counter", None))
|
||||
out.append(("debrid_rdtc_torrents_total", "counter", len(rows)))
|
||||
for status, count in sorted(by_status.items()):
|
||||
out.append(('debrid_rdtc_torrents_by_status{status="%d"}' % status, "gauge", count))
|
||||
out.append(("debrid_rdtc_pending_without_provider", "gauge", no_provider))
|
||||
out.append(("debrid_rdtc_stuck_zero_progress", "gauge", stuck))
|
||||
out.append(("debrid_rdtc_oldest_pending_age_seconds", "gauge", round(oldest_pending, 1)))
|
||||
con.close()
|
||||
except Exception:
|
||||
up = 0
|
||||
return out, up
|
||||
|
||||
|
||||
def nginx_metrics(state: dict):
|
||||
"""Incrementally parse the add-request log into cumulative counters."""
|
||||
st = state.setdefault("nginx", {
|
||||
"inode": None, "offset": 0,
|
||||
"codes": {}, "add_codes": {}, "add_sum": 0.0, "add_count": 0,
|
||||
"buckets": [0] * len(LATENCY_BUCKETS),
|
||||
})
|
||||
try:
|
||||
stt = os.stat(ACCESS_LOG)
|
||||
except OSError:
|
||||
return [], 0
|
||||
|
||||
if st.get("inode") != stt.st_ino or stt.st_size < st.get("offset", 0):
|
||||
st.update({"inode": stt.st_ino, "offset": 0}) # rotated or truncated
|
||||
|
||||
fresh = 0
|
||||
with open(ACCESS_LOG, "r", errors="replace") as f:
|
||||
f.seek(st["offset"])
|
||||
for line in f:
|
||||
if not line.endswith("\n"):
|
||||
break # partial write, retry next tick
|
||||
st["offset"] += len(line.encode())
|
||||
m = LINE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
status = m["status"]
|
||||
st["codes"][status] = st["codes"].get(status, 0) + 1
|
||||
if m["uri"] != ADD_URI:
|
||||
continue
|
||||
fresh += 1
|
||||
st["add_codes"][status] = st["add_codes"].get(status, 0) + 1
|
||||
try:
|
||||
rt = float(m["rt"])
|
||||
except ValueError:
|
||||
continue
|
||||
st["add_sum"] += rt
|
||||
st["add_count"] += 1
|
||||
for i, ub in enumerate(LATENCY_BUCKETS):
|
||||
if rt <= ub:
|
||||
st["buckets"][i] += 1
|
||||
|
||||
out = []
|
||||
for code, count in sorted(st["codes"].items()):
|
||||
out.append(('debrid_nginx_requests_total{code="%s"}' % code, "counter", count))
|
||||
for code, count in sorted(st["add_codes"].items()):
|
||||
out.append(('debrid_nginx_add_requests_total{code="%s"}' % code, "counter", count))
|
||||
for ub, count in zip(LATENCY_BUCKETS, st["buckets"]):
|
||||
out.append(('debrid_nginx_add_seconds_bucket{le="%g"}' % ub, "counter", count))
|
||||
out.append(('debrid_nginx_add_seconds_bucket{le="+Inf"}', "counter", st["add_count"]))
|
||||
out.append(("debrid_nginx_add_seconds_sum", "counter", round(st["add_sum"], 6)))
|
||||
out.append(("debrid_nginx_add_seconds_count", "counter", st["add_count"]))
|
||||
state["nginx_lines_since_last_tick"] = fresh
|
||||
return out, 1
|
||||
|
||||
|
||||
def render(shim_body, shim_up, rdtc_rows, rdtc_up, nginx_rows, nginx_up) -> str:
|
||||
parts = [
|
||||
"# HELP debrid_shim_up Whether the rdtc-async-add metrics endpoint answered.",
|
||||
"# TYPE debrid_shim_up gauge",
|
||||
f"debrid_shim_up {shim_up}",
|
||||
"# HELP debrid_rdtc_up Whether rdtc's database could be read.",
|
||||
"# TYPE debrid_rdtc_up gauge",
|
||||
f"debrid_rdtc_up {rdtc_up}",
|
||||
"# HELP debrid_nginx_up Whether the add-request access log could be read.",
|
||||
"# TYPE debrid_nginx_up gauge",
|
||||
f"debrid_nginx_up {nginx_up}",
|
||||
]
|
||||
if shim_body:
|
||||
parts.append(shim_body.rstrip())
|
||||
for group in (rdtc_rows, nginx_rows):
|
||||
for name, _typ, value in group:
|
||||
parts.append(name if value is None else f"{name} {value}")
|
||||
return "\n".join(parts) + "\n"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
state = load_state()
|
||||
shim_body, shim_up = shim_metrics()
|
||||
rdtc_rows, rdtc_up = rdtc_metrics()
|
||||
nginx_rows, nginx_up = nginx_metrics(state)
|
||||
|
||||
payload = render(shim_body, shim_up, rdtc_rows, rdtc_up, nginx_rows, nginx_up)
|
||||
os.makedirs(os.path.dirname(OUT), exist_ok=True)
|
||||
tmp = OUT + ".tmp"
|
||||
with open(tmp, "w") as f:
|
||||
f.write(payload)
|
||||
os.chmod(tmp, 0o644)
|
||||
os.replace(tmp, OUT)
|
||||
save_state(state)
|
||||
if os.environ.get("DEBRID_METRICS_VERBOSE"):
|
||||
print(payload)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,744 @@
|
||||
{
|
||||
"uid": "debrid-pipeline",
|
||||
"title": "Debrid pipeline \u2014 rdtc, shim, *arr",
|
||||
"tags": [
|
||||
"homelab",
|
||||
"debrid",
|
||||
"rdtc",
|
||||
"arr"
|
||||
],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "1m",
|
||||
"time": {
|
||||
"from": "now-24h",
|
||||
"to": "now"
|
||||
},
|
||||
"annotations": {
|
||||
"list": []
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "stat",
|
||||
"title": "Add front door",
|
||||
"description": "rdtc-async-add answering. 0 means *arr is talking straight to rdtc and is exposed to its 100s add timeout again.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 4,
|
||||
"h": 4
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "red",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "green",
|
||||
"value": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"colorMode": "background",
|
||||
"graphMode": "area",
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "debrid_shim_up",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "stat",
|
||||
"title": "Adds accepted (1h)",
|
||||
"description": "Requests answered 200 immediately. This is the number that used to become 499s.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 4,
|
||||
"y": 0,
|
||||
"w": 5,
|
||||
"h": 4
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"colorMode": "background",
|
||||
"graphMode": "area",
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "increase(debrid_shim_adds_accepted_total[1h])",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "stat",
|
||||
"title": "Duplicates suppressed (1h)",
|
||||
"description": "Identical bodies inside the 60s window; each would otherwise have been a second copy.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 9,
|
||||
"y": 0,
|
||||
"w": 5,
|
||||
"h": 4
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"colorMode": "background",
|
||||
"graphMode": "area",
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "increase(debrid_shim_adds_deduped_total[1h])",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "stat",
|
||||
"title": "Delivery failures (1h)",
|
||||
"description": "rdtc never accepted these after every retry. *arr was told 200 anyway, so no duplicate was triggered; the release is lost instead.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 14,
|
||||
"y": 0,
|
||||
"w": 5,
|
||||
"h": 4
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "orange",
|
||||
"value": 1
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"colorMode": "background",
|
||||
"graphMode": "area",
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "increase(debrid_shim_adds_failed_total[1h])",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "stat",
|
||||
"title": "Pending without provider id",
|
||||
"description": "The 2026-11-25 smoking gun: rows queued but never submitted to TorBox.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 19,
|
||||
"y": 0,
|
||||
"w": 5,
|
||||
"h": 4
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"color": {
|
||||
"mode": "thresholds"
|
||||
},
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "green",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "orange",
|
||||
"value": 1
|
||||
},
|
||||
{
|
||||
"color": "red",
|
||||
"value": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
},
|
||||
"colorMode": "background",
|
||||
"graphMode": "area",
|
||||
"textMode": "auto"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "debrid_rdtc_pending_without_provider",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Add latency, what *arr sees (nginx)",
|
||||
"description": "Measured at nginx from $request_time. Must stay in the milliseconds: *arr gives up at ~100s, then grabs another release.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 4,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(debrid_nginx_add_seconds_bucket[15m])) by (le))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.5, sum(rate(debrid_nginx_add_seconds_bucket[15m])) by (le))",
|
||||
"legendFormat": "p50"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "timeseries",
|
||||
"title": "Adds by HTTP status",
|
||||
"description": "200 healthy. 499 = *arr closed the connection (duplicate-grab trigger). 504 = nginx upstream timeout.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 4,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(debrid_nginx_add_requests_total[5m])) by (code)",
|
||||
"legendFormat": "{{code}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"type": "timeseries",
|
||||
"title": "Delivery outcomes per minute",
|
||||
"description": "What the shim did with the adds it accepted.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 12,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "rate(debrid_shim_adds_delivered_total[5m])",
|
||||
"legendFormat": "delivered"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "B",
|
||||
"expr": "rate(debrid_shim_adds_failed_total[5m])",
|
||||
"legendFormat": "failed"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "C",
|
||||
"expr": "rate(debrid_shim_delivery_retries_total[5m])",
|
||||
"legendFormat": "retries"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "D",
|
||||
"expr": "rate(debrid_shim_adds_deduped_total[5m])",
|
||||
"legendFormat": "deduped"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"type": "timeseries",
|
||||
"title": "rdtc queue health",
|
||||
"description": "Stuck-at-0% torrents are what consumed Provider:MaxParallelDownloads and blocked every later add.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 12,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "debrid_rdtc_pending_without_provider",
|
||||
"legendFormat": "pending, no provider id"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "B",
|
||||
"expr": "debrid_rdtc_stuck_zero_progress",
|
||||
"legendFormat": "stuck at 0% (>15m)"
|
||||
},
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "C",
|
||||
"expr": "sum(debrid_rdtc_torrents_by_status{status=~\"0|1\"})",
|
||||
"legendFormat": "queued + downloading"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
"type": "timeseries",
|
||||
"title": "Oldest pending torrent",
|
||||
"description": "Provider:Default:TorrentLifetime is 20 minutes, so a value far above 1200s means expiry is not firing.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 20,
|
||||
"w": 8,
|
||||
"h": 7
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "debrid_rdtc_oldest_pending_age_seconds",
|
||||
"legendFormat": ""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"type": "timeseries",
|
||||
"title": "Delivery duration p95 (shim)",
|
||||
"description": "How long rdtc actually took to accept an add.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 8,
|
||||
"y": 20,
|
||||
"w": 8,
|
||||
"h": 7
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(debrid_shim_delivery_seconds_bucket[15m])) by (le))",
|
||||
"legendFormat": "p95"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 32,
|
||||
"type": "timeseries",
|
||||
"title": "All edge requests by status",
|
||||
"description": "The whole private API vhost, not just adds.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 16,
|
||||
"y": 20,
|
||||
"w": 8,
|
||||
"h": 7
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"fillOpacity": 8,
|
||||
"lineWidth": 2,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(debrid_nginx_requests_total[5m])) by (code)",
|
||||
"legendFormat": "{{code}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"type": "text",
|
||||
"title": "Runbook \u2014 the three faults this guards against",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 27,
|
||||
"w": 24,
|
||||
"h": 7
|
||||
},
|
||||
"options": {
|
||||
"mode": "markdown",
|
||||
"content": "**1. Duplicate grabs (five Passengers in seven minutes).** rdtc answered `POST /api/v2/torrents/add` only after the provider call, past *arr's hardcoded ~100s timeout; *arr blocklisted the release and grabbed the next one. Guard: `debrid_nginx_add_requests_total{code=\"499\"}` rising or add latency above ~30s.\n\n**2. Exhausted provider slots.** Two torrents stalled at 0% on TorBox consumed `Provider:MaxParallelDownloads`, so every later add sat behind them with no provider id. Guard: `debrid_rdtc_pending_without_provider`, `debrid_rdtc_stuck_zero_progress`.\n\n**3. Silent rdtc.** `General:LogLevel=4` / `DownloadClient:LogLevel=5` logged nothing but fatal errors, so the incident had to be reconstructed from SQLite. Now Information/Debug in `~/.local/share/rdtc-fresh/db/rdtclient.log`.\n\nRunbook: `homelab/reference/services/rdtc` on the wiki. Check script: `~/.dotfiles/tools/rdtc-health/check.sh`."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -42,6 +42,19 @@ proxy_pass http://127.0.0.1:6502; # was 6500
|
||||
|
||||
The browser UI vhost still talks to `:6500` directly — only \*arr's path goes through the proxy.
|
||||
|
||||
## Metrics
|
||||
|
||||
`GET /metrics` (on the same loopback listener, so Prometheus reaches it only through
|
||||
node_exporter's textfile collector) exposes `debrid_shim_adds_accepted_total`,
|
||||
`debrid_shim_adds_deduped_total`, `debrid_shim_adds_delivered_total`,
|
||||
`debrid_shim_adds_failed_total`, `debrid_shim_adds_rejected_total`,
|
||||
`debrid_shim_delivery_retries_total` and the `debrid_shim_delivery_seconds` histogram.
|
||||
|
||||
`tools/debrid-metrics/` collects those, plus rdtc's queue depth and nginx's add
|
||||
latency, into `/var/lib/node_exporter/textfile/debrid.prom` every 15s. The Grafana
|
||||
dashboard is `debrid-pipeline` (provisioned from
|
||||
`/etc/monitoring/grafana/dashboards/debrid-pipeline.json` on xatu).
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Default | Meaning |
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
@@ -37,13 +38,76 @@ type Config struct {
|
||||
MaxBody int64 // largest add body we will buffer
|
||||
}
|
||||
|
||||
// metrics holds the counters the Grafana panel reads. Everything is cumulative so
|
||||
// Prometheus can rate() it; the mutex is what keeps the map-free design simple.
|
||||
type metrics struct {
|
||||
mu sync.Mutex
|
||||
accepted int64
|
||||
deduped int64
|
||||
delivered int64
|
||||
failed int64
|
||||
rejected int64
|
||||
retries int64
|
||||
buckets []float64 // upper bounds, ascending
|
||||
counts []int64 // cumulative counts per bucket
|
||||
sumSeconds float64
|
||||
count int64
|
||||
}
|
||||
|
||||
func newMetrics() *metrics {
|
||||
b := []float64{0.05, 0.25, 1, 5, 30, 60, 120, 300, 600, 900}
|
||||
return &metrics{buckets: b, counts: make([]int64, len(b))}
|
||||
}
|
||||
|
||||
func (m *metrics) observeDelivery(seconds float64) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.sumSeconds += seconds
|
||||
m.count++
|
||||
for i, ub := range m.buckets {
|
||||
if seconds <= ub {
|
||||
m.counts[i]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *metrics) render() string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
var b strings.Builder
|
||||
w := func(name, help, typ string) {
|
||||
fmt.Fprintf(&b, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, typ)
|
||||
}
|
||||
w("debrid_shim_adds_accepted_total", "Add requests answered immediately.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_adds_accepted_total %d\n", m.accepted)
|
||||
w("debrid_shim_adds_deduped_total", "Identical adds suppressed inside the dedupe window.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_adds_deduped_total %d\n", m.deduped)
|
||||
w("debrid_shim_adds_delivered_total", "Adds rdtc accepted in the background.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_adds_delivered_total %d\n", m.delivered)
|
||||
w("debrid_shim_adds_failed_total", "Adds rdtc never accepted, after every retry.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_adds_failed_total %d\n", m.failed)
|
||||
w("debrid_shim_adds_rejected_total", "Adds refused because the body was too large.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_adds_rejected_total %d\n", m.rejected)
|
||||
w("debrid_shim_delivery_retries_total", "Individual retry attempts that failed.", "counter")
|
||||
fmt.Fprintf(&b, "debrid_shim_delivery_retries_total %d\n", m.retries)
|
||||
w("debrid_shim_delivery_seconds", "Time from accepting an add to rdtc accepting it.", "histogram")
|
||||
for i, ub := range m.buckets {
|
||||
fmt.Fprintf(&b, "debrid_shim_delivery_seconds_bucket{le=\"%g\"} %d\n", ub, m.counts[i])
|
||||
}
|
||||
fmt.Fprintf(&b, "debrid_shim_delivery_seconds_bucket{le=\"+Inf\"} %d\n", m.count)
|
||||
fmt.Fprintf(&b, "debrid_shim_delivery_seconds_sum %g\n", m.sumSeconds)
|
||||
fmt.Fprintf(&b, "debrid_shim_delivery_seconds_count %d\n", m.count)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
type proxy struct {
|
||||
cfg Config
|
||||
client *http.Client
|
||||
logger *log.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
seen map[string]time.Time
|
||||
mu sync.Mutex
|
||||
seen map[string]time.Time
|
||||
metrics *metrics
|
||||
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
@@ -62,13 +126,19 @@ func newProxyHandler(cfg Config) *proxy {
|
||||
cfg: cfg,
|
||||
// The provider call may legitimately run for minutes; the client timeout
|
||||
// here only guards against a wedged socket.
|
||||
client: &http.Client{Timeout: 15 * time.Minute},
|
||||
logger: log.New(os.Stdout, "", log.LstdFlags|log.LUTC),
|
||||
seen: make(map[string]time.Time),
|
||||
client: &http.Client{Timeout: 15 * time.Minute},
|
||||
logger: log.New(os.Stdout, "", log.LstdFlags|log.LUTC),
|
||||
seen: make(map[string]time.Time),
|
||||
metrics: newMetrics(),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/metrics" {
|
||||
w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8")
|
||||
_, _ = w.Write([]byte(p.metrics.render()))
|
||||
return
|
||||
}
|
||||
if r.URL.Path != addPath {
|
||||
p.passThrough(w, r)
|
||||
return
|
||||
@@ -80,6 +150,9 @@ func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if int64(len(body)) > p.cfg.MaxBody {
|
||||
p.metrics.mu.Lock()
|
||||
p.metrics.rejected++
|
||||
p.metrics.mu.Unlock()
|
||||
p.logger.Printf("add rejected: body larger than %d bytes", p.cfg.MaxBody)
|
||||
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
|
||||
return
|
||||
@@ -87,6 +160,9 @@ func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
key := dedupeKey(body, r.URL.RawQuery)
|
||||
if p.seenRecently(key) {
|
||||
p.metrics.mu.Lock()
|
||||
p.metrics.deduped++
|
||||
p.metrics.mu.Unlock()
|
||||
p.logger.Printf("add: duplicate suppressed q=%q bytes=%d", r.URL.RawQuery, len(body))
|
||||
writeOk(w)
|
||||
return
|
||||
@@ -100,6 +176,10 @@ func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
h := sha256.Sum256(body)
|
||||
|
||||
p.metrics.mu.Lock()
|
||||
p.metrics.accepted++
|
||||
p.metrics.mu.Unlock()
|
||||
|
||||
p.wg.Add(1)
|
||||
go func() {
|
||||
defer p.wg.Done()
|
||||
@@ -118,6 +198,19 @@ func writeOk(w http.ResponseWriter) {
|
||||
|
||||
// deliver retries the add against rdtc until it is accepted or attempts run out.
|
||||
func (p *proxy) deliver(tpl *http.Request, body []byte, id string) {
|
||||
startedAt := time.Now()
|
||||
ok := false
|
||||
defer func() {
|
||||
p.metrics.observeDelivery(time.Since(startedAt).Seconds())
|
||||
p.metrics.mu.Lock()
|
||||
if ok {
|
||||
p.metrics.delivered++
|
||||
} else {
|
||||
p.metrics.failed++
|
||||
}
|
||||
p.metrics.mu.Unlock()
|
||||
}()
|
||||
|
||||
var last string
|
||||
for attempt := 1; attempt <= p.cfg.Retries; attempt++ {
|
||||
req := tpl.Clone(tpl.Context())
|
||||
@@ -135,6 +228,7 @@ func (p *proxy) deliver(tpl *http.Request, body []byte, id string) {
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode < http.StatusBadRequest {
|
||||
ok = true
|
||||
p.logger.Printf("add delivered %s attempt=%d status=%d", id, attempt, resp.StatusCode)
|
||||
return
|
||||
}
|
||||
@@ -143,6 +237,9 @@ func (p *proxy) deliver(tpl *http.Request, body []byte, id string) {
|
||||
last = err.Error()
|
||||
}
|
||||
|
||||
p.metrics.mu.Lock()
|
||||
p.metrics.retries++
|
||||
p.metrics.mu.Unlock()
|
||||
p.logger.Printf("add delivery %s attempt=%d/%d failed: %s", id, attempt, p.cfg.Retries, last)
|
||||
if attempt < p.cfg.Retries {
|
||||
time.Sleep(time.Duration(attempt) * p.cfg.RetryDelay)
|
||||
|
||||
@@ -364,3 +364,72 @@ func TestMultipartTorrentForwarded(t *testing.T) {
|
||||
t.Fatalf("multipart body was mangled: %q", got.body)
|
||||
}
|
||||
}
|
||||
|
||||
// 10. The Grafana panel needs counters from the proxy itself.
|
||||
func TestMetricsEndpointReportsActivity(t *testing.T) {
|
||||
f, up := newFakeUpstream(t)
|
||||
srv, _ := newProxy(t, up.URL)
|
||||
|
||||
post := func(body string) {
|
||||
resp, err := http.Post(srv.URL+"/api/v2/torrents/add", "application/x-www-form-urlencoded",
|
||||
strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("post: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
post("urls=magnet:?xt=urn:btih:one")
|
||||
post("urls=magnet:?xt=urn:btih:one") // deduped
|
||||
post("urls=magnet:?xt=urn:btih:two") // accepted
|
||||
f.waitFor(t, 2, 2*time.Second)
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
resp, err := http.Get(srv.URL + "/metrics")
|
||||
if err != nil {
|
||||
t.Fatalf("metrics: %v", err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("metrics status = %d", resp.StatusCode)
|
||||
}
|
||||
text := string(body)
|
||||
for _, want := range []string{
|
||||
"debrid_shim_adds_accepted_total 2",
|
||||
"debrid_shim_adds_deduped_total 1",
|
||||
"debrid_shim_adds_delivered_total 2",
|
||||
"debrid_shim_adds_failed_total 0",
|
||||
"debrid_shim_delivery_seconds_bucket",
|
||||
} {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("metrics missing %q\n%s", want, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 11. Failures must be counted, so the panel can show a dead provider.
|
||||
func TestMetricsCountsDeliveryFailures(t *testing.T) {
|
||||
f, up := newFakeUpstream(t)
|
||||
f.handle = func(w http.ResponseWriter, r *http.Request, body []byte) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}
|
||||
srv, p := newProxy(t, up.URL)
|
||||
|
||||
resp, err := http.Post(srv.URL+"/api/v2/torrents/add", "application/x-www-form-urlencoded",
|
||||
strings.NewReader("urls=magnet:?xt=urn:btih:dead"))
|
||||
if err != nil {
|
||||
t.Fatalf("post: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
p.wait()
|
||||
|
||||
resp, err = http.Get(srv.URL + "/metrics")
|
||||
if err != nil {
|
||||
t.Fatalf("metrics: %v", err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if !strings.Contains(string(body), "debrid_shim_adds_failed_total 1") {
|
||||
t.Fatalf("failure not counted:\n%s", body)
|
||||
}
|
||||
}
|
||||
Executable
+206
@@ -0,0 +1,206 @@
|
||||
#!/usr/bin/env bash
|
||||
# rdtc-health — did the debrid pipeline behave since we put the shim in front of rdtc?
|
||||
#
|
||||
# Answers four questions in one run:
|
||||
# 1. Did *arr ever time out on an add? (nginx 499/504, add latency)
|
||||
# 2. Did rdtc jam its provider slots again? (pending rows without a provider id)
|
||||
# 3. Did the same release arrive several times? (near-duplicate names in the window)
|
||||
# 4. Can we still diagnose it next time? (rdtc log freshness, shim journal)
|
||||
#
|
||||
# Sources: Prometheus on xatu (aggregates), rdtc's database, its log and the shim's
|
||||
# journal on yveltal, Radarr's log on dragapult.
|
||||
#
|
||||
# ./check.sh 24h report, exit 1 on any FAIL
|
||||
# WINDOW=6h ./check.sh shorter lookback
|
||||
#
|
||||
# Hosts are overridable: RDTC_HOST, ARR_HOST, PROM_HOST.
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
WINDOW="${WINDOW:-24h}"
|
||||
RDTC_HOST="${RDTC_HOST:-yveltal_local}"
|
||||
ARR_HOST="${ARR_HOST:-ziadarafat@10.0.0.123}"
|
||||
PROM_HOST="${PROM_HOST:-root@10.0.0.130}"
|
||||
PROM="${PROM:-http://127.0.0.1:9090}"
|
||||
|
||||
fails=0
|
||||
warns=0
|
||||
note() { printf ' %b\n' "$1"; }
|
||||
pass() { printf ' \033[32mPASS\033[0m %s\n' "$1"; }
|
||||
warn() { printf ' \033[33mWARN\033[0m %s\n' "$1"; warns=$((warns + 1)); }
|
||||
fail() { printf ' \033[31mFAIL\033[0m %s\n' "$1"; fails=$((fails + 1)); }
|
||||
|
||||
# PromQL has to be URL-encoded; these helpers keep the calls readable.
|
||||
prom() {
|
||||
ssh -o BatchMode=yes "$PROM_HOST" \
|
||||
"curl -s --max-time 8 '${PROM}/api/v1/query?query=$1'" 2>/dev/null \
|
||||
| python3 -c "import json,sys;d=json.load(sys.stdin);r=d['data']['result'];print(r[0]['value'][1] if r else '')" 2>/dev/null
|
||||
}
|
||||
q() { # q 'expr' -> value or empty
|
||||
python3 - "$1" <<'PY'
|
||||
import sys, urllib.parse
|
||||
print(urllib.parse.quote(sys.argv[1], safe=""))
|
||||
PY
|
||||
}
|
||||
isnum() { [[ "$1" =~ ^-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$ ]]; }
|
||||
|
||||
echo "rdtc health check — window ${WINDOW} — $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo
|
||||
|
||||
# ---------------------------------------------------------------- Prometheus
|
||||
echo "1. What *arr saw at the edge (nginx, from Prometheus)"
|
||||
w="[${WINDOW}]"
|
||||
enc_w=$(q "$w")
|
||||
adds_ok=$(prom "sum(increase(debrid_nginx_add_requests_total%7Bcode%3D%22200%22%7D$enc_w))")
|
||||
adds_499=$(prom "sum(increase(debrid_nginx_add_requests_total%7Bcode%3D%22499%22%7D$enc_w))")
|
||||
adds_5xx=$(prom "sum(increase(debrid_nginx_add_requests_total%7Bcode%3D~%225.%2B%22%7D$enc_w))")
|
||||
p95=$(prom "histogram_quantile(0.95,sum(rate(debrid_nginx_add_seconds_bucket$enc_w))by(le))")
|
||||
shim_up=$(prom "debrid_shim_up")
|
||||
|
||||
note "adds 200=${adds_ok:-n/a} 499=${adds_499:-n/a} 5xx=${adds_5xx:-n/a} p95=${p95:+${p95}s} shim_up=${shim_up:-n/a}"
|
||||
[ "$shim_up" = "1" ] && pass "add front door is up" || fail "rdtc-async-add is not reporting (debrid_shim_up=${shim_up:-missing})"
|
||||
|
||||
if ! isnum "${adds_ok:-}"; then
|
||||
note "\033[2m no add requests in this window — *arr has not searched since the shim went in\033[0m"
|
||||
else
|
||||
if isnum "${adds_499:-}" && python3 -c "import sys;sys.exit(0 if float('$adds_499')>0 else 1)"; then
|
||||
warn "${adds_499} adds returned 499 — *arr gave up waiting (the duplicate-grab trigger)"
|
||||
else
|
||||
pass "no 499s: *arr never abandoned an add"
|
||||
fi
|
||||
if isnum "${adds_5xx:-}" && python3 -c "import sys;sys.exit(0 if float('$adds_5xx')>0 else 1)"; then
|
||||
warn "${adds_5xx} adds returned 5xx"
|
||||
else
|
||||
pass "no 5xx on adds"
|
||||
fi
|
||||
if isnum "${p95:-}"; then
|
||||
if python3 -c "import sys;sys.exit(0 if float('$p95')>30 else 1)"; then
|
||||
warn "add p95 is ${p95}s — above the 30s comfort line"
|
||||
else
|
||||
pass "add p95 is ${p95}s"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# ------------------------------------------------------------------ rdtc DB
|
||||
echo
|
||||
echo "2. rdtc queue (live, from its database)"
|
||||
db_report=$(ssh -o BatchMode=yes "$RDTC_HOST" "python3 - ${WINDOW}" <<'PY' 2>&1
|
||||
import sqlite3, sys, time
|
||||
hours = {"6h": 6, "12h": 12, "24h": 24}.get(sys.argv[1], 24)
|
||||
c = sqlite3.connect("file:/home/ziadarafat/.local/share/rdtc-fresh/db/rdtclient.db?mode=ro", uri=True, timeout=10)
|
||||
c.row_factory = sqlite3.Row
|
||||
rows = c.execute("select RdName, RdStatus, RdId, RdProgress, Added, Category from Torrents").fetchall()
|
||||
now = time.time()
|
||||
def age(r):
|
||||
try:
|
||||
return now - time.mktime(time.strptime(str(r["Added"])[:19], "%Y-%m-%d %H:%M:%S"))
|
||||
except Exception:
|
||||
return 0.0
|
||||
pending = [r for r in rows if (r["RdStatus"] or 0) in (0, 1)]
|
||||
no_provider = [r for r in pending if not r["RdId"]]
|
||||
stuck = [r for r in pending if age(r) > 900 and (r["RdProgress"] or 0) == 0]
|
||||
errors = [r for r in rows if (r["RdStatus"] or 0) == 3 and age(r) < hours * 3600]
|
||||
recent = [r for r in rows if age(r) < hours * 3600]
|
||||
groups = {}
|
||||
for r in recent:
|
||||
key = " ".join((r["RdName"] or "").lower().split()[:6])
|
||||
groups.setdefault(key, []).append(r["RdName"] or "")
|
||||
dupes = {k: v for k, v in groups.items() if len(v) > 1 and k}
|
||||
print(f"METRIC total={len(rows)} pending={len(pending)} no_provider={len(no_provider)} stuck={len(stuck)} errors={len(errors)} dupes={len(dupes)}")
|
||||
for r in no_provider[:4]:
|
||||
print(f"ROW {str(r['Added'])[:19]} {r['Category']} {str(r['RdName'])[:50]}")
|
||||
for k, v in list(dupes.items())[:4]:
|
||||
print(f"DUP x{len(v)} {v[0][:58]}")
|
||||
PY
|
||||
)
|
||||
note "$(echo "$db_report" | grep '^METRIC' | sed 's/^METRIC //')"
|
||||
echo "$db_report" | grep '^ROW' | sed 's/^ROW/ no-provider row:/' | sed 's/^/ /'
|
||||
echo "$db_report" | grep '^DUP' | sed 's/^DUP/ repeated release:/' | sed 's/^/ /'
|
||||
read -r m_total m_pending m_noprov m_stuck m_errors m_dupes < <(echo "$db_report" | grep '^METRIC' | sed 's/^METRIC //; s/ / /g; s/[a-z_]*=//g')
|
||||
[ "${m_noprov:-1}" = "0" ] && pass "no queued row is missing a provider id" \
|
||||
|| warn "${m_noprov} queued rows never reached the provider (the slot-jam symptom)"
|
||||
[ "${m_stuck:-1}" = "0" ] && pass "no torrent is stuck at 0%" \
|
||||
|| warn "${m_stuck} torrents stuck at 0% for over 15m"
|
||||
[ "${m_dupes:-1}" = "0" ] && pass "no repeated releases in ${WINDOW}" \
|
||||
|| warn "${m_dupes} release names repeat inside ${WINDOW} (check whether these are deliberate)"
|
||||
|
||||
# --------------------------------------------------------------- Radarr side
|
||||
echo
|
||||
echo "3. Radarr download-client failures"
|
||||
arr_out=$(ssh -o BatchMode=yes "$ARR_HOST" "sudo -n podman logs --timestamps --since ${WINDOW} radarreng 2>&1 | grep -aE \"Couldn.t add|Failed to connect to qBittorrent|Http request timed out\" | awk '{print \$1}' | tail -50" 2>/dev/null)
|
||||
arr_n=$(printf '%s\n' "$arr_out" | grep -c . || true)
|
||||
arr_last=$(printf '%s\n' "$arr_out" | tail -1 | cut -c1-19)
|
||||
note "matching log lines: ${arr_n}; most recent: ${arr_last:-never}"
|
||||
if [ "${arr_n}" = "0" ]; then
|
||||
pass "Radarr logged no download-client failures"
|
||||
else
|
||||
warn "Radarr logged ${arr_n} (most recent ${arr_last}) — if these all predate the shim, they are the incident, not a regression"
|
||||
fi
|
||||
|
||||
# --------------------------------------------------- rdtc log + provider errors
|
||||
echo
|
||||
echo "4. rdtc's own log and provider signals"
|
||||
rdtc_out=$(ssh -o BatchMode=yes "$RDTC_HOST" "python3 - ${WINDOW}" <<'PY' 2>&1
|
||||
import os, re, sys, time
|
||||
path = "/home/ziadarafat/.local/share/rdtc-fresh/db/rdtclient.log"
|
||||
hours = {"6h": 6, "12h": 12, "24h": 24}.get(sys.argv[1], 24)
|
||||
cutoff = time.time() - hours * 3600
|
||||
size = os.path.getsize(path)
|
||||
age = int(time.time() - os.path.getmtime(path))
|
||||
counts = {"ERR": 0, "PollyTimeout": 0, "RateLimit": 0, "Unhandled": 0}
|
||||
with open(path, errors="replace") as f:
|
||||
for line in f:
|
||||
m = re.match(r"^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)", line)
|
||||
if not m:
|
||||
continue
|
||||
try:
|
||||
ts = time.mktime(time.strptime(m.group(1), "%Y-%m-%d %H:%M:%S"))
|
||||
except ValueError:
|
||||
continue
|
||||
if ts < cutoff:
|
||||
continue
|
||||
if "[ERR]" in line:
|
||||
counts["ERR"] += 1
|
||||
if "OnTimeout" in line:
|
||||
counts["PollyTimeout"] += 1
|
||||
if "RATE_LIMIT" in line or "rate limit" in line.lower():
|
||||
counts["RateLimit"] += 1
|
||||
if "unhandled exception" in line.lower():
|
||||
counts["Unhandled"] += 1
|
||||
print(f"LOG size_kib={size // 1024} age_s={age} errs={counts['ERR']} polly_timeouts={counts['PollyTimeout']} rate_limit={counts['RateLimit']} unhandled={counts['Unhandled']}")
|
||||
PY
|
||||
)
|
||||
note "$(echo "$rdtc_out" | grep '^LOG' | sed 's/^LOG / /')"
|
||||
if echo "$rdtc_out" | grep -q 'age_s=[0-9]\{1,4\}$\|age_s=[0-9]\{1,3\} '; then
|
||||
:
|
||||
fi
|
||||
age_s=$(echo "$rdtc_out" | sed -n 's/.*age_s=\([0-9]*\).*/\1/p')
|
||||
if [ -n "${age_s:-}" ] && [ "${age_s:-99999}" -lt 3600 ]; then
|
||||
pass "rdtc log is fresh (last write ${age_s}s ago)"
|
||||
else
|
||||
fail "rdtc log looks stale (age ${age_s:-unknown}s) — we would be blind again"
|
||||
fi
|
||||
if [ "${age_s:-99999}" -lt 3600 ] && echo "$rdtc_out" | grep -q 'rate_limit=0'; then
|
||||
pass "no TorBox rate-limit errors in ${WINDOW}"
|
||||
elif echo "$rdtc_out" | grep -q 'rate_limit=0'; then
|
||||
pass "no TorBox rate-limit errors in ${WINDOW}"
|
||||
else
|
||||
warn "TorBox rate-limit errors present: $(echo "$rdtc_out" | sed -n 's/.*rate_limit=\([0-9]*\).*/\1/p')"
|
||||
fi
|
||||
|
||||
shim_journal=$(ssh -o BatchMode=yes "$RDTC_HOST" "journalctl --user -u rdtc-async-add --since -${WINDOW} --no-pager 2>/dev/null | grep -cE 'add ' || true" 2>/dev/null | head -1)
|
||||
shim_givenup=$(ssh -o BatchMode=yes "$RDTC_HOST" "journalctl --user -u rdtc-async-add --since -${WINDOW} --no-pager 2>/dev/null | grep -c 'given up' || true" 2>/dev/null | head -1)
|
||||
shim_lines=${shim_journal:-0}
|
||||
shim_givenup=${shim_givenup:-0}
|
||||
note "shim journal: ${shim_lines} add lines, ${shim_givenup} given up"
|
||||
[ "${shim_givenup:-0}" = "0" ] && pass "every accepted add was delivered" \
|
||||
|| warn "${shim_givenup} adds were abandoned after every retry"
|
||||
|
||||
echo
|
||||
if [ "$fails" -eq 0 ]; then
|
||||
printf 'Result: %s warning(s), 0 failures.\n' "$warns"
|
||||
exit 0
|
||||
fi
|
||||
printf 'Result: %s warning(s), %s FAILURE(S).\n' "$warns" "$fails"
|
||||
exit 1
|
||||
Reference in new issue
Block a user