Probes log locally only while the hub is unreachable; the hub confirms silences with that log
Probe: no access log, nothing written while reports get through. When the hub can't be reached, failed reports go to data/outage.jsonl and unsent results to data/backlog.jsonl (survives restarts). The first report that gets through uploads both and they are deleted. Hub: a probe that misses reports gets a "Not reporting" incident. When it reports again, the runs from its outage log become confirmed "Hub unreachable" incidents; the rest of the silence (probe off or restarting) is dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
462525b1e2
commit
be727949c1
13 changed files with 449 additions and 32 deletions
101
app/probe/outage.py
Normal file
101
app/probe/outage.py
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
"""The probe's local outage log, in $DATA_DIR. Nothing is written while reports reach the hub.
|
||||
|
||||
When a report fails because the hub can't be reached (no connection, timeout, or a 5xx), the
|
||||
probe appends the failure to outage.jsonl and the measurements it couldn't send to backlog.jsonl,
|
||||
so a restart during the outage loses neither. The next report that gets through carries the
|
||||
failures, merged into runs, and the hub uses them to confirm or drop the "not reporting" incident
|
||||
it opened. A probe that was switched off has no runs to send, so the hub drops that incident."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
OUTAGE = "outage.jsonl"
|
||||
BACKLOG = "backlog.jsonl"
|
||||
|
||||
|
||||
def _dir() -> Path:
|
||||
return Path(os.environ.get("DATA_DIR", "data"))
|
||||
|
||||
|
||||
def is_outage(ex: Exception) -> bool:
|
||||
"""True when the hub didn't answer, as opposed to answering with a refusal (401, 422)."""
|
||||
if isinstance(ex, httpx.HTTPStatusError):
|
||||
return ex.response.status_code >= 500
|
||||
return isinstance(ex, httpx.TransportError)
|
||||
|
||||
|
||||
def active() -> bool:
|
||||
return (_dir() / OUTAGE).exists()
|
||||
|
||||
|
||||
def record_failure(error: str, ts: float | None = None) -> None:
|
||||
_append(OUTAGE, [{"ts": ts or time.time(), "error": error[:300]}])
|
||||
|
||||
|
||||
def runs(gap: float) -> list[dict]:
|
||||
"""Logged failures merged into runs: failures less than `gap` seconds apart belong together.
|
||||
A longer pause between failures means the probe wasn't running in between."""
|
||||
out: list[dict] = []
|
||||
for f in sorted(_read(OUTAGE), key=lambda f: f.get("ts", 0)):
|
||||
ts = f.get("ts")
|
||||
if not isinstance(ts, (int, float)):
|
||||
continue
|
||||
if out and ts - out[-1]["end"] <= gap:
|
||||
out[-1].update(end=ts, failures=out[-1]["failures"] + 1, error=f.get("error") or out[-1]["error"])
|
||||
else:
|
||||
out.append({"start": ts, "end": ts, "failures": 1, "error": f.get("error") or ""})
|
||||
return out[-1000:]
|
||||
|
||||
|
||||
def clear_failures() -> None:
|
||||
(_dir() / OUTAGE).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def append_backlog(items: list[dict]) -> None:
|
||||
if items:
|
||||
_append(BACKLOG, items)
|
||||
|
||||
|
||||
def load_backlog() -> list[dict]:
|
||||
return [m for m in _read(BACKLOG) if isinstance(m, dict)]
|
||||
|
||||
|
||||
def save_backlog(items) -> None:
|
||||
"""Rewrite the backlog as exactly `items`; no file when there is nothing left to send."""
|
||||
path = _dir() / BACKLOG
|
||||
if not items:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
try:
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text("".join(json.dumps(m) + "\n" for m in items))
|
||||
tmp.replace(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _append(name: str, rows: list[dict]) -> None:
|
||||
try:
|
||||
_dir().mkdir(parents=True, exist_ok=True)
|
||||
with open(_dir() / name, "a") as f:
|
||||
f.write("".join(json.dumps(r) + "\n" for r in rows))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _read(name: str) -> list:
|
||||
try:
|
||||
lines = (_dir() / name).read_text().splitlines()
|
||||
except OSError:
|
||||
return []
|
||||
out = []
|
||||
for line in lines:
|
||||
try:
|
||||
out.append(json.loads(line))
|
||||
except ValueError:
|
||||
continue # a line cut short by a power loss
|
||||
return out
|
||||
|
|
@ -16,7 +16,7 @@ import httpx
|
|||
from fastapi import FastAPI, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from app.probe import checks
|
||||
from app.probe import checks, outage
|
||||
from app.version import VERSION
|
||||
|
||||
log = logging.getLogger("probe")
|
||||
|
|
@ -25,7 +25,7 @@ SEND_BATCH = 2000
|
|||
|
||||
state = {
|
||||
"hub_url": "", "registered": None, "last_report": None, "last_error": None, "cycles": 0,
|
||||
"buffered": 0, "config": None, "started": time.time(),
|
||||
"buffered": 0, "config": None, "started": time.time(), "hub_unreachable_since": None,
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -69,20 +69,25 @@ def _hostport(host: str, port: int) -> str:
|
|||
return f"[{host}]:{port}" if ":" in host else f"{host}:{port}"
|
||||
|
||||
|
||||
async def report(client: httpx.AsyncClient, e: dict, buffer: deque, cycle: int) -> dict | None:
|
||||
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None."""
|
||||
async def report(client: httpx.AsyncClient, e: dict, buffer: deque, cycle: int, outages: list | None = None) -> dict | None:
|
||||
"""Send buffered measurements (oldest first, in batches). Returns the hub's config, or None.
|
||||
`outages` (the local outage log as runs) goes with the first batch; once the hub has taken
|
||||
it, the log is deleted."""
|
||||
config = None
|
||||
for _ in range(10):
|
||||
batch = [buffer[i] for i in range(min(SEND_BATCH, len(buffer)))]
|
||||
body = {"version": VERSION, "hostname": socket.gethostname(), "port": e["port"],
|
||||
"advertise_addr": e["advertise"] or None, "icmp": checks.ICMP_STATE["ok"],
|
||||
"measurements": batch, "neighbors": checks.neighbors() if cycle % 2 == 0 and config is None else []}
|
||||
"measurements": batch, "neighbors": checks.neighbors() if cycle % 2 == 0 and config is None else [],
|
||||
"outages": outages if config is None and outages else []}
|
||||
r = await client.post(f"{e['hub_url']}/api/probe/report", json=body, headers={"Authorization": f"Bearer {e['token']}"})
|
||||
if r.status_code == 401:
|
||||
state["registered"] = False
|
||||
raise RuntimeError("the hub doesn't know this probe's token (removed on the hub?)")
|
||||
r.raise_for_status()
|
||||
state["registered"] = True
|
||||
if config is None and outages:
|
||||
outage.clear_failures()
|
||||
config = r.json()
|
||||
for _ in batch:
|
||||
buffer.popleft()
|
||||
|
|
@ -118,35 +123,65 @@ def save_config(cfg: dict) -> None:
|
|||
|
||||
async def probe_loop() -> None:
|
||||
"""Measure, then report; the hub's reply says what to measure next time. The last reply is
|
||||
cached on disk so a probe that restarts while the hub is down keeps testing its peers."""
|
||||
cached on disk so a probe that restarts while the hub is down keeps testing its peers.
|
||||
While reports get through, nothing else is written. While the hub can't be reached, the
|
||||
failures and the unsent measurements go to the local outage log (see outage.py)."""
|
||||
e = env()
|
||||
state["hub_url"] = e["hub_url"]
|
||||
buffer: deque = deque(maxlen=BUFFER_MAX)
|
||||
buffer: deque = deque(outage.load_backlog(), maxlen=BUFFER_MAX)
|
||||
spooled = len(buffer) # measurements in backlog.jsonl
|
||||
unreachable = outage.active() # restarted during an outage
|
||||
cfg = load_config() or DEFAULT_CONFIG
|
||||
state["config"] = load_config()
|
||||
await asyncio.sleep(random.uniform(0, 5)) # spread probes out
|
||||
cycle = 0
|
||||
last_logged = None
|
||||
async with httpx.AsyncClient(timeout=10) as hub:
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
fresh: list[dict] = []
|
||||
try:
|
||||
buffer.extend(await run_checks(cfg, cycle))
|
||||
fresh = await run_checks(cfg, cycle)
|
||||
buffer.extend(fresh)
|
||||
except Exception as ex:
|
||||
log.exception("checks failed")
|
||||
state["last_error"] = f"checks failed: {ex}"
|
||||
try:
|
||||
new = await report(hub, e, buffer, cycle)
|
||||
runs = outage.runs(gap=cfg.get("interval", 30) * 2 + 15) if unreachable else []
|
||||
new = await report(hub, e, buffer, cycle, runs)
|
||||
if new:
|
||||
if new != state["config"]:
|
||||
if state["config"] is None:
|
||||
log.info("registered with %s as %r (probe %s)", e["hub_url"], new.get("name"), new.get("probe_id"))
|
||||
save_config(new)
|
||||
cfg = state["config"] = new
|
||||
if unreachable:
|
||||
log.info("the hub answers again; sent %d logged failed reports", sum(r["failures"] for r in runs))
|
||||
unreachable = False
|
||||
state["hub_unreachable_since"] = None
|
||||
if spooled:
|
||||
outage.save_backlog(buffer)
|
||||
spooled = len(buffer)
|
||||
state["last_report"] = time.time()
|
||||
state["last_error"] = None
|
||||
state["last_error"] = last_logged = None
|
||||
except (httpx.HTTPError, RuntimeError, ValueError) as ex:
|
||||
state["last_error"] = f"report to hub failed: {checks._err(ex)}"
|
||||
log.warning(state["last_error"])
|
||||
err = checks._err(ex)
|
||||
state["last_error"] = f"report to hub failed: {err}"
|
||||
if outage.is_outage(ex):
|
||||
outage.record_failure(err)
|
||||
if unreachable and spooled and spooled + len(fresh) <= BUFFER_MAX + SEND_BATCH:
|
||||
outage.append_backlog(fresh)
|
||||
spooled += len(fresh)
|
||||
else: # first failure, or the file outgrew the buffer: write what's unsent
|
||||
outage.save_backlog(buffer)
|
||||
spooled = len(buffer)
|
||||
if not unreachable:
|
||||
state["hub_unreachable_since"] = time.time()
|
||||
log.warning("can't reach the hub (%s); logging locally until it answers", err)
|
||||
unreachable = True
|
||||
elif state["last_error"] != last_logged:
|
||||
log.warning(state["last_error"])
|
||||
last_logged = state["last_error"]
|
||||
state["buffered"] = len(buffer)
|
||||
state["cycles"] = cycle = cycle + 1
|
||||
await asyncio.sleep(max(1.0, cfg.get("interval", 30) - (time.monotonic() - started)))
|
||||
|
|
@ -154,6 +189,9 @@ async def probe_loop() -> None:
|
|||
|
||||
@contextlib.asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
# Peers request /probe/ping every round; logging each request would write to disk
|
||||
# (journal, docker log, or service.log on macOS) all the time for no benefit.
|
||||
logging.getLogger("uvicorn.access").disabled = True
|
||||
task = None
|
||||
e = env()
|
||||
if e["hub_url"] and e["token"]:
|
||||
|
|
@ -206,5 +244,6 @@ def status() -> dict:
|
|||
"name": cfg.get("name"), "probe_id": cfg.get("probe_id"), "registered": state["registered"],
|
||||
"peers": len(cfg.get("peers", [])), "icmp": checks.ICMP_STATE["ok"], "gateway": checks.default_gateway(),
|
||||
"last_report": state["last_report"], "last_error": state["last_error"], "buffered": state["buffered"],
|
||||
"cycles": state["cycles"],
|
||||
"cycles": state["cycles"], "hub_unreachable_since": state["hub_unreachable_since"],
|
||||
"outage_log": outage.active(),
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue