Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.
Python ai-agentsaiopsdashboarddockerfastapihomelabincident-managementllmmonitoringopenaireactroot-cause-analysisself-hosteduptime-monitoring
feat(availability): HTTP(s), keyword and TCP checks run by the collectors
karloks2005e24b584c0f64
diff --git a/ODSTUPANJA.md b/ODSTUPANJA.mdindex e7d8c72..68869ab 100644--- a/ODSTUPANJA.md+++ b/ODSTUPANJA.md@@ -161,3 +161,25 @@ su anotacije dizajna i namjerno nisu ugrađeni.| Admin: „You'll get a push when it connects" | Nema | Nema push obavijesti | #50 || Alert rules: „+" za novo pravilo | Nema | Vlastita pravila ne postoje | – || Tablet: Agent skriva chat iza gumba | Na tabletu su popis, incident i chat jedan ispod drugoga | Tri stupca ostaju od 1200 px; ispod toga slažu se okomito | – |++## Availability (`10-availability.pdf`, `mobile/07-availability.pdf`)++Prvi dio milestonea: provjere HTTP(s), Keyword i TCP port, pokreću ih collectori od verzije 0.10.0.++| Dizajn | Implementacija | Razlog | Issue |+| --- | --- | --- | --- |+| Gumbi „Status page" i „Maintenance" | Prikazani, ali onemogućeni | Još nisu napravljeni | #143, #144 |+| Devet vrsta provjera | Rade HTTP(s), Keyword i TCP port; ostale su u mreži prikazane kao „later" i ne mogu se odabrati | Prvi dio | #133, #135, #136 |+| Tab „Find on this machine" u drawer-u New check | Samo ručno dodavanje | Prvi dio | #142 |+| Grupe po tagu redom kako ih je korisnik složio (Public prvi) | Abecedno, provjere bez taga na kraju | Nema spremljenog redoslijeda grupa | – |+| Detalj: izdavatelj certifikata („Let's Encrypt R11") | Samo broj dana do isteka | Collector šalje samo datum isteka | #140 |+| Detalj: graf za 30 d po serveru | 30 d je jedna linija za sve servere zajedno | Satni sažeci nisu po serveru; sirovi rezultati čuvaju se 7 dana | #140 |+| Detalj: događaj „Paused 20 min for maintenance" | Događaji su samo padovi i oporavci (iz incidenata) | Pauze i održavanje se još ne bilježe | #143 |+| Detalj: gumb „Clone" | Pause, Edit i Delete | Prvi dio | #140 |+| Down now: „alert sent to ntfy" i sažetak agenta | Razlog pada, s kojih servera i koliko puta zaredom; za novu provjeru „no alert yet" | Ne bilježi se slanje po kanalu; agent za provjere još ne postoji | #137, #145 |+| Down now: „Pause alerts" | „Pause" pauzira cijelu provjeru | Odvojeno pauziranje obavijesti nije napravljeno | #137 |+| New check: obavijesti po kanalu, „While down, remind every", „Alert on certificate expiry" | Pad otvara incident koji ide na iste kanale kao svi incidenti; bira se samo Critical/Warning | Obavijesti idu kroz postojeće incidente | #137 |+| New check: „Test passed · 200 OK" i „Test again" prije spremanja | Nema testa; nova provjera prvih 10 minuta ne šalje obavijesti | Prvi dio | #141 |+| New check: timeout fiksno 48 s | Timeout se sam smanji na 80 % intervala kad je interval kraći; greške se pokazuju uz polje i u podnožju | Zadani timeout inače blokira interval ispod 49 s | #141 |+| New check: tagovi kao čipovi | Tekstno polje, tagovi odvojeni zarezom | Jednostavnije | #141 |+| Mobitel: Availability kao zaseban tab | Availability je u More (s brojem palih provjera na tabu More); popis provjera je kompaktan, s trakom zadnjih 30 provjera | Tab bar ima mjesta za četiri stavke | #146 |diff --git a/docker/nginx.collector.conf b/docker/nginx.collector.confindex 863f8a9..dfd004c 100644--- a/docker/nginx.collector.conf+++ b/docker/nginx.collector.conf@@ -14,7 +14,7 @@ server {listen 8081;server_name _;- location ~ ^/api/monitoring/(collectors/register|collectors/register/poll|collectors/enroll|metrics/ingest)$ {+ location ~ ^/api/monitoring/(collectors/register|collectors/register/poll|collectors/enroll|metrics/ingest|metrics/checks)$ {rewrite ^/api/(.*)$ /$1 break;proxy_pass http://backend:8000;proxy_http_version 1.1;@@ -34,7 +34,7 @@ server {listen 8080;server_name _;- location ~ ^/api/monitoring/(collectors/register|collectors/register/poll|collectors/enroll|metrics/ingest)$ {+ location ~ ^/api/monitoring/(collectors/register|collectors/register/poll|collectors/enroll|metrics/ingest|metrics/checks)$ {rewrite ^/api/(.*)$ /$1 break;proxy_pass http://backend:8000;proxy_http_version 1.1;diff --git a/docker/nginx.strict.conf b/docker/nginx.strict.confindex f5a1179..a4ad700 100644--- a/docker/nginx.strict.conf+++ b/docker/nginx.strict.conf@@ -32,7 +32,7 @@ server {real_ip_header X-Forwarded-For;real_ip_recursive on;- location ~ ^/api/(collector\.py$|monitoring/(collectors|metrics/ingest)) {+ location ~ ^/api/(collector\.py$|monitoring/(collectors|metrics/)) {return 404;}diff --git a/src/backend/availability.py b/src/backend/availability.pynew file mode 100644index 0000000..fe4ff91--- /dev/null+++ b/src/backend/availability.py@@ -0,0 +1,466 @@+"""Availability checks: services that the collectors on your servers try every so often (Milestone 11).++The backend keeps the checks and decides; the collectors only run them (src/collector/collector.py) and report+each run. A check is given to the collectors of the servers it should run from, they report results on their+own endpoint, and here the results are combined:++- Per server, the check is down once its last ``retries + 1`` runs all failed, and up again on the first good run.+- Over the servers: with the rule ``all`` the check is down only when every server sees it down (the service is+ down); with ``any`` one is enough (one network path is broken).+- A check going down opens an incident (``check:<id>:down``) with the check's severity, so it shows up in Needs+ attention, the Agent page and notifications; coming back up resolves it. New checks stay quiet for their first+ 10 minutes, so a wrong path doesn't page anyone.++For the page, results are grouped into slots of one interval: a slot is up, slow, retrying (it failed, but not+often enough to count as down) or down. Uptime is the share of slots that weren't down. Completed hours are+summarised into check_rollups, which the 30-day, 1-year and 90-day views add up.+"""+from __future__ import annotations++import json+import re+import statistics+from collections import defaultdict+from datetime import datetime, timedelta, timezone+from urllib.parse import urlsplit++from .alerts import raise_alert, resolve_alerts+from .models import Check, CheckResult, CheckRollup, IncidentAlert, Server++TYPES = ("http", "keyword", "tcp")+RULES = ("all", "any")+SEVERITIES = ("CRITICAL", "WARNING")+MIN_INTERVAL, MAX_INTERVAL = 20, 86400+MAX_TIMEOUT = 48+MAX_RETRIES = 10+MAX_CHECKS_PER_SERVER = 50+MAX_RESULTS_PER_REPORT = 500+QUIET_FOR_NEW = timedelta(minutes=10)+RAW_KEPT = timedelta(days=7)+STRIP = 30+CHECK_RULE_PREFIX = "check:"+# Collectors that can run checks report at least this version.+MIN_COLLECTOR = (0, 10, 0)+_NAME = re.compile(r"[^\x00-\x1f\x7f]{1,120}")+_HOST = re.compile(r"[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\]")+_CODES = re.compile(r"[1-5]\d\d(-[1-5]\d\d)?")+++def _utc(moment: datetime | None) -> datetime | None:+ return None if moment is None else moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)+++def _version(text: str | None) -> tuple[int, ...]:+ try:+ return tuple(int(part) for part in (text or "").split(".")[:3])+ except ValueError:+ return ()+++def can_run_checks(server: Server) -> bool:+ try:+ info = json.loads(server.system_info or "{}")+ except ValueError:+ return False+ return _version(info.get("collector_version")) >= MIN_COLLECTOR+++# ---------- what a check is ----------++def validate(raw: dict, server_ids: set[int]) -> dict:+ """The fields of a check from the form, checked. Raises ValueError with a message for the person."""+ kind = raw.get("type")+ if kind not in TYPES:+ raise ValueError("Pick a check type: HTTP(s), Keyword or TCP port.")+ name = str(raw.get("name") or "").strip()+ if not _NAME.fullmatch(name):+ raise ValueError("Give the check a name of up to 120 characters.")+ target = str(raw.get("target") or "").strip()+ options: dict = {}+ if kind in ("http", "keyword"):+ parts = urlsplit(target)+ if parts.scheme not in ("http", "https") or not parts.hostname or len(target) > 2048 or any(char.isspace() for char in target):+ raise ValueError("The URL must start with http:// or https:// and name a host.")+ codes = raw.get("accepted_codes") or ["200-299"]+ if not isinstance(codes, list) or not 1 <= len(codes) <= 10 or not all(isinstance(code, str) and _CODES.fullmatch(code) for code in codes):+ raise ValueError("Accepted status codes are like 200-299 or 301, at most 10.")+ options.update(accepted_codes=codes, follow_redirects=raw.get("follow_redirects") is not False, ignore_tls=raw.get("ignore_tls") is True, method="HEAD" if raw.get("method") == "HEAD" and kind == "http" else "GET")+ if kind == "keyword":+ keyword = str(raw.get("keyword") or "")+ if not 1 <= len(keyword) <= 200:+ raise ValueError("Enter the text to look for, up to 200 characters.")+ options.update(keyword=keyword, case_sensitive=raw.get("case_sensitive") is True)+ else:+ host, _, port = target.rpartition(":")+ if not _HOST.fullmatch(host or "") or not port.isdigit() or not 1 <= int(port) <= 65535:+ raise ValueError("For a TCP port, enter host:port, like 10.0.0.12:3306.")+ options["upside_down"] = raw.get("upside_down") is True+ servers = raw.get("server_ids")+ if not isinstance(servers, list) or not servers or not all(isinstance(item, int) and not isinstance(item, bool) for item in servers) or not set(servers) <= server_ids:+ raise ValueError("Choose at least one server to check from.")+ numbers = {}+ for key, low, high, default in (("interval_seconds", MIN_INTERVAL, MAX_INTERVAL, 60), ("retries", 0, MAX_RETRIES, 2), ("retry_interval_seconds", MIN_INTERVAL, MAX_INTERVAL, 20), ("timeout_seconds", 1, MAX_TIMEOUT, 48)):+ value = raw.get(key, default)+ if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high:+ raise ValueError(f"{key.replace('_seconds', '').replace('_', ' ').capitalize()} must be a whole number from {low} to {high}.")+ numbers[key] = value+ if numbers["timeout_seconds"] >= numbers["interval_seconds"]:+ # A short interval with the default timeout: the timeout follows the interval, like in Uptime Kuma.+ numbers["timeout_seconds"] = max(1, min(MAX_TIMEOUT, numbers["interval_seconds"] * 4 // 5))+ tags = [tag.strip() for tag in raw.get("tags") or [] if isinstance(tag, str) and tag.strip()]+ if len(tags) > 5 or any(len(tag) > 40 or "," in tag for tag in tags):+ raise ValueError("At most 5 tags of up to 40 characters, without commas.")+ rule = raw.get("rule", "all")+ severity = raw.get("severity", "CRITICAL")+ if rule not in RULES or severity not in SEVERITIES:+ raise ValueError("Unknown rule or severity.")+ return {"name": name, "type": kind, "target": target, "options": json.dumps(options), "tags": ",".join(tags), "server_ids": json.dumps(sorted(set(servers))), "rule": rule, "severity": severity, **numbers}+++def servers_of(check: Check) -> list[int]:+ try:+ return [int(item) for item in json.loads(check.server_ids or "[]")]+ except (ValueError, TypeError):+ return []+++def options_of(check: Check) -> dict:+ try:+ return json.loads(check.options or "{}")+ except ValueError:+ return {}+++def for_collector(db, server: Server) -> list[dict]:+ """The checks this server's collector should run, in the exact shape the collector validates."""+ result = []+ for check in db.query(Check).filter(Check.paused.is_(False)).order_by(Check.id):+ if server.id in servers_of(check):+ result.append({"id": check.id, "type": check.type, "target": check.target, "interval": check.interval_seconds, "retry_interval": check.retry_interval_seconds,+ "timeout": check.timeout_seconds, **{key: value for key, value in options_of(check).items() if key != "upside_down"}})+ return result[:MAX_CHECKS_PER_SERVER]+++# ---------- results ----------++def store(db, server: Server, results: list, now: datetime | None = None) -> set[int]:+ """Keep the valid results this server's collector reported for its own checks. Returns the checks touched.+ Everything is untrusted: anything that isn't a well-formed result for a check of this server is dropped."""+ now = now or datetime.now(timezone.utc)+ mine = {check.id: check for check in db.query(Check).filter(Check.paused.is_(False)) if server.id in servers_of(check)}+ touched = set()+ for item in results[:MAX_RESULTS_PER_REPORT]:+ if not isinstance(item, dict) or item.get("check_id") not in mine or not isinstance(item.get("ok"), bool):+ continue+ try:+ moment = _utc(datetime.fromisoformat(str(item.get("time"))))+ except ValueError:+ continue+ if not now - timedelta(hours=1) <= moment <= now + timedelta(seconds=60):+ continue+ number = lambda key, low, high: item.get(key) if isinstance(item.get(key), int) and not isinstance(item.get(key), bool) and low <= item[key] <= high else None # noqa: E731+ detail = item.get("detail")+ detail = "".join(char for char in detail if char.isprintable())[:200] if isinstance(detail, str) else None+ db.add(CheckResult(check_id=item["check_id"], server_id=server.id, time=moment, ok=item["ok"], response_ms=number("response_ms", 0, 600_000),+ code=number("code", 100, 599), detail=detail or None, cert_days=number("cert_days", -10_000, 10_000)))+ touched.add(item["check_id"])+ db.flush()+ return touched+++def _effective(check: Check, result: CheckResult) -> bool:+ """A result's ok, turned around for upside-down checks (up means the service is unreachable)."""+ return (not result.ok) if options_of(check).get("upside_down") else result.ok+++def _results(db, check: Check, since: datetime, until: datetime | None = None) -> list[CheckResult]:+ query = db.query(CheckResult).filter(CheckResult.check_id == check.id, CheckResult.time >= since)+ if until is not None:+ query = query.filter(CheckResult.time < until)+ return query.order_by(CheckResult.time).limit(50_000).all()+++def slots(check: Check, results: list[CheckResult]) -> list[dict]:+ """The results grouped into slots of one interval, oldest first: {start, status, response_ms, failed_on}.+ status is up, slow, retrying or down; failed_on lists the servers whose last run in the slot failed."""+ interval = check.interval_seconds+ streak: dict[int, int] = defaultdict(int)+ grouped: dict[int, dict[int, tuple[bool, bool, int | None, str | None]]] = defaultdict(dict)+ for result in results:+ ok = _effective(check, result)+ streak[result.server_id] = 0 if ok else streak[result.server_id] + 1+ counted = streak[result.server_id] >= check.retries + 1+ grouped[int(_utc(result.time).timestamp()) // interval][result.server_id] = (ok, counted, result.response_ms, result.detail)+ times = [value[2] for slot in grouped.values() for value in slot.values() if value[0] and value[2] is not None]+ slow_after = max(1000, 3 * statistics.median(times)) if times else None+ output = []+ for key in sorted(grouped):+ per_server = grouped[key]+ failed = [server for server, value in per_server.items() if not value[0]]+ down_servers = [server for server, value in per_server.items() if not value[0] and value[1]]+ combined_failed = len(failed) == len(per_server) if check.rule == "all" else bool(failed)+ combined_down = (len(down_servers) == len(per_server)) if check.rule == "all" else bool(down_servers)+ response = [value[2] for value in per_server.values() if value[0] and value[2] is not None]+ average = round(sum(response) / len(response)) if response else None+ if combined_down:+ status = "down"+ elif combined_failed or failed:+ status = "retrying" if combined_failed else "up"+ else:+ status = "slow" if slow_after and average and average > slow_after else "up"+ details = [value[3] for value in per_server.values() if not value[0] and value[3]]+ output.append({"start": datetime.fromtimestamp(key * interval, timezone.utc).isoformat(), "status": status, "response_ms": average, "failed_on": sorted(failed), "detail": details[0] if details else None})+ return output+++def server_states(db, check: Check, now: datetime) -> dict[int, str]:+ """Each server's verdict on the check now: up, down, or unknown (no fresh result)."""+ fresh = now - timedelta(seconds=check.interval_seconds * 3 + check.timeout_seconds + 60)+ states = {}+ for server_id in servers_of(check):+ latest = db.query(CheckResult).filter(CheckResult.check_id == check.id, CheckResult.server_id == server_id).order_by(CheckResult.time.desc()).limit(check.retries + 1).all()+ if not latest or _utc(latest[0].time) < fresh:+ states[server_id] = "unknown"+ elif _effective(check, latest[0]):+ states[server_id] = "up"+ elif len(latest) == check.retries + 1 and not any(_effective(check, result) for result in latest):+ states[server_id] = "down"+ else:+ states[server_id] = "retrying"+ return states+++def _reporting(db, now: datetime) -> set[int]:+ """Servers whose collector is online and new enough to run checks."""+ return {server.id for server in db.query(Server).filter(Server.last_seen_at.isnot(None)) if can_run_checks(server)+ and now - _utc(server.last_seen_at) <= timedelta(seconds=max(server.check_interval_seconds or 60, 60) * 3)}+++def rule_key(check: Check) -> str:+ return f"{CHECK_RULE_PREFIX}{check.id}:down"+++def evaluate(db, check: Check, now: datetime | None = None, alerting: bool = True) -> str:+ """Bring the check's state up to date and open or resolve its incident. Returns the state.+ With ``alerting`` False (the rule is switched off in Admin › Rules) the state still changes, but no incident opens."""+ now = now or datetime.now(timezone.utc)+ if check.paused:+ new = "paused"+ else:+ states = server_states(db, check, now)+ known = {server: state for server, state in states.items() if state != "unknown"}+ if check.rule == "all":+ # A server that should be reporting but hasn't yet keeps the check from counting as down everywhere;+ # one that can't (offline, or a collector too old to run checks) doesn't hold it up.+ waiting = [server for server, state in states.items() if state == "unknown" and server in _reporting(db, now)]+ known.update({server: "retrying" for server in waiting})+ if not known:+ new = "pending" if check.state in ("pending", "paused") else check.state+ elif check.rule == "all":+ new = "down" if all(state == "down" for state in known.values()) else "up" if any(state == "up" for state in known.values()) else check.state if check.state in ("up", "down") else "pending"+ else:+ new = "down" if any(state == "down" for state in known.values()) else "up" if all(state == "up" for state in known.values()) else check.state if check.state in ("up", "down") else "pending"+ if new != check.state:+ check.state, check.state_since = new, now+ servers = servers_of(check)+ if new == "down" and alerting and servers and now - _utc(check.created_at or now) >= QUIET_FOR_NEW:+ latest = db.query(CheckResult).filter(CheckResult.check_id == check.id).order_by(CheckResult.time.desc()).first()+ names = dict(db.query(Server.id, Server.hostname).filter(Server.id.in_(servers)))+ failing = [names.get(server, f"server {server}") for server, state in server_states(db, check, now).items() if state == "down"]+ why = (latest.detail if latest and latest.detail else "No answer") + f" from {', '.join(failing) or 'its servers'}"+ raise_alert(db, servers[0], rule_key(check), check.severity, f"{check.name} is down"[:255],+ f"{why}. Failed {check.retries + 1} checks in a row. {check.target}"[:1000])+ elif servers:+ resolve_alerts(db, servers[0], [rule_key(check)], now)+ return new+++def forget_check(db, check: Check) -> None:+ """Delete a check with its history; its open incident is resolved, so the record of it stays."""+ servers = servers_of(check)+ if servers:+ resolve_alerts(db, servers[0], [rule_key(check)])+ db.query(CheckResult).filter(CheckResult.check_id == check.id).delete(synchronize_session=False)+ db.query(CheckRollup).filter(CheckRollup.check_id == check.id).delete(synchronize_session=False)+ db.delete(check)+++def forget_server(db, server_id: int) -> None:+ """A server is removed: its results go, and checks stop running from it (a check left with no server pauses)."""+ db.query(CheckResult).filter(CheckResult.server_id == server_id).delete(synchronize_session=False)+ for check in db.query(Check):+ servers = servers_of(check)+ if server_id in servers:+ remaining = [item for item in servers if item != server_id]+ check.server_ids = json.dumps(remaining)+ if not remaining:+ check.paused, check.state = True, "paused"+++# ---------- summaries for the page ----------++def _uptime(db, check: Check, since: datetime, now: datetime) -> float | None:+ """Share of slots since ``since`` that weren't down, in percent: completed hours from the rollups, the rest raw."""+ total = down = 0+ rolled = _utc(check.rolled_until) if check.rolled_until else None+ if rolled and rolled > since:+ for slots_count, down_count in db.query(CheckRollup.slots, CheckRollup.down_slots).filter(CheckRollup.check_id == check.id, CheckRollup.hour >= since, CheckRollup.hour < rolled):+ total += slots_count+ down += down_count+ raw_from = max(since, rolled or since)+ for slot in slots(check, _results(db, check, raw_from)):+ total += 1+ down += slot["status"] == "down"+ return round(100 * (total - down) / total, 2) if total else None+++def summary(db, check: Check, names: dict[int, str], now: datetime | None = None) -> dict:+ now = now or datetime.now(timezone.utc)+ recent = slots(check, _results(db, check, now - timedelta(seconds=check.interval_seconds * (STRIP + 2) + 3600)))[-STRIP:]+ latest = db.query(CheckResult).filter(CheckResult.check_id == check.id).order_by(CheckResult.time.desc()).first()+ cert = db.query(CheckResult.cert_days).filter(CheckResult.check_id == check.id, CheckResult.cert_days.isnot(None)).order_by(CheckResult.time.desc()).limit(1).scalar()+ options = options_of(check)+ return {+ "id": check.id, "name": check.name, "type": check.type, "target": check.target, "tags": [tag for tag in check.tags.split(",") if tag],+ "keyword": options.get("keyword"), "options": options, "rule": check.rule, "severity": check.severity, "paused": check.paused, "state": check.state,+ "state_since": _utc(check.state_since).isoformat() if check.state_since else None, "interval_seconds": check.interval_seconds, "retries": check.retries,+ "retry_interval_seconds": check.retry_interval_seconds, "timeout_seconds": check.timeout_seconds,+ "servers": [{"id": server, "hostname": names.get(server, f"server {server}")} for server in servers_of(check)],+ "strip": [{"status": "paused" if check.paused else slot["status"], "start": slot["start"], "response_ms": slot["response_ms"]} for slot in recent],+ "response_ms": next((slot["response_ms"] for slot in reversed(recent) if slot["response_ms"] is not None), None),+ "uptime_24h": _uptime(db, check, now - timedelta(hours=24), now), "uptime_30d": _uptime(db, check, now - timedelta(days=30), now),+ "cert_days": cert, "last_detail": latest.detail if latest else None, "last_result_at": _utc(latest.time).isoformat() if latest else None,+ "quiet_until": (_utc(check.created_at) + QUIET_FOR_NEW).isoformat() if now - _utc(check.created_at) < QUIET_FOR_NEW else None,+ "created_at": _utc(check.created_at).isoformat(),+ }+++def overview(db, now: datetime | None = None) -> dict:+ now = now or datetime.now(timezone.utc)+ names = dict(db.query(Server.id, Server.hostname).all())+ checks = [summary(db, check, names, now) for check in db.query(Check).order_by(Check.name)]+ month = [check["uptime_30d"] for check in checks if check["uptime_30d"] is not None and not check["paused"]]+ return {+ "checks": checks,+ "counts": {"up": sum(check["state"] == "up" for check in checks), "down": sum(check["state"] == "down" for check in checks), "paused": sum(check["paused"] for check in checks),+ "pending": sum(check["state"] == "pending" for check in checks), "total": len(checks)},+ "uptime_30d": round(sum(month) / len(month), 2) if month else None,+ "expiring": [{"name": check["name"], "days": check["cert_days"]} for check in checks if check["cert_days"] is not None and check["cert_days"] <= 21],+ "servers": [{"id": server.id, "hostname": server.hostname, "can_run_checks": can_run_checks(server)} for server in db.query(Server).order_by(Server.hostname)],+ }+++RANGES = {"1h": timedelta(hours=1), "24h": timedelta(hours=24), "7d": timedelta(days=7), "30d": timedelta(days=30)}+CHART_POINTS = 120+DAYS = 90+++def _response_series(db, check: Check, span: timedelta, now: datetime, names: dict[int, str]) -> list[dict]:+ """Average response time per server in up to CHART_POINTS buckets. Raw results cover a week; 30 days come from+ the hourly rollups, which are for all servers together."""+ since = now - span+ if span > RAW_KEPT:+ points = [{"time": _utc(hour).isoformat(), "ms": avg} for hour, avg in db.query(CheckRollup.hour, CheckRollup.avg_ms)+ .filter(CheckRollup.check_id == check.id, CheckRollup.hour >= since).order_by(CheckRollup.hour)]+ return [{"server_id": None, "hostname": "all servers", "points": points}] if points else []+ bucket = max(check.interval_seconds, int(span.total_seconds()) // CHART_POINTS)+ sums: dict[int, dict[int, list[int]]] = defaultdict(lambda: defaultdict(list))+ for result in _results(db, check, since):+ if result.ok and result.response_ms is not None:+ sums[result.server_id][int(_utc(result.time).timestamp()) // bucket].append(result.response_ms)+ return [{"server_id": server, "hostname": names.get(server, f"server {server}"),+ "points": [{"time": datetime.fromtimestamp(key * bucket, timezone.utc).isoformat(), "ms": round(sum(values) / len(values))} for key, values in sorted(buckets.items())]}+ for server, buckets in sorted(sums.items())]+++def _days(db, check: Check, now: datetime) -> list[dict]:+ """Uptime per day for the last DAYS days, oldest first; None for a day without results."""+ today = now.replace(hour=0, minute=0, second=0, microsecond=0)+ start = today - timedelta(days=DAYS - 1)+ totals: dict[str, list[int]] = defaultdict(lambda: [0, 0])+ for hour, slots_count, down_count in db.query(CheckRollup.hour, CheckRollup.slots, CheckRollup.down_slots).filter(CheckRollup.check_id == check.id, CheckRollup.hour >= start):+ totals[_utc(hour).date().isoformat()][0] += slots_count+ totals[_utc(hour).date().isoformat()][1] += down_count+ rolled = _utc(check.rolled_until) if check.rolled_until else None+ for slot in slots(check, _results(db, check, max(start, rolled or start))):+ day = datetime.fromisoformat(slot["start"]).date().isoformat()+ totals[day][0] += 1+ totals[day][1] += slot["status"] == "down"+ output = []+ for index in range(DAYS):+ day = (start + timedelta(days=index)).date().isoformat()+ total, down = totals.get(day, (0, 0))+ output.append({"day": day, "uptime": round(100 * (total - down) / total, 2) if total else None})+ return output+++def detail(db, check: Check, range_id: str, now: datetime | None = None) -> dict:+ """What the check's detail shows besides its row: the response chart, 90 days, uptime over a year, and the+ times it went down (from its incidents)."""+ now = now or datetime.now(timezone.utc)+ names = dict(db.query(Server.id, Server.hostname).all())+ span = RANGES.get(range_id, RANGES["24h"])+ downs = db.query(IncidentAlert).filter(IncidentAlert.rule_key == rule_key(check)).order_by(IncidentAlert.created_at.desc()).limit(10).all()+ events = []+ for incident in downs:+ if incident.resolved_at:+ events.append({"time": _utc(incident.resolved_at).isoformat(), "kind": "up", "text": f"Up again after {_duration(_utc(incident.resolved_at) - _utc(incident.created_at))}"})+ events.append({"time": _utc(incident.created_at).isoformat(), "kind": "down", "text": f"Down · {incident.description.split('. Failed')[0]}"})+ last = downs[0] if downs else None+ window = [result for result in _results(db, check, now - timedelta(hours=24)) if result.ok and result.response_ms is not None]+ return {+ "range": range_id if range_id in RANGES else "24h",+ "series": _response_series(db, check, span, now, names),+ "days": _days(db, check, now),+ "uptime_1y": _uptime(db, check, now - timedelta(days=365), now),+ "average_24h": round(sum(result.response_ms for result in window) / len(window)) if window else None,+ "last_down": {"at": _utc(last.created_at).isoformat(), "for": _duration((_utc(last.resolved_at) if last.resolved_at else now) - _utc(last.created_at)), "ongoing": last.resolved_at is None} if last else None,+ "events": events[:10],+ }+++def _duration(span: timedelta) -> str:+ seconds = max(0, int(span.total_seconds()))+ if seconds < 90:+ return f"{seconds} s"+ if seconds < 5400:+ return f"{round(seconds / 60)} min"+ if seconds < 172800:+ return f"{round(seconds / 3600)} h"+ return f"{round(seconds / 86400)} d"++# ---------- keeping the history small ----------++def roll(db, now: datetime | None = None) -> int:+ """Summarise every completed hour of every check into check_rollups. Returns how many hours were added."""+ now = now or datetime.now(timezone.utc)+ hour_now = now.replace(minute=0, second=0, microsecond=0)+ added = 0+ for check in db.query(Check):+ start = _utc(check.rolled_until) if check.rolled_until else None+ if start is None:+ first = db.query(CheckResult.time).filter(CheckResult.check_id == check.id).order_by(CheckResult.time).limit(1).scalar()+ if first is None:+ continue+ start = _utc(first).replace(minute=0, second=0, microsecond=0)+ hour = start+ while hour < hour_now:+ results = _results(db, check, hour, hour + timedelta(hours=1))+ if results:+ hour_slots = slots(check, results)+ times = [slot["response_ms"] for slot in hour_slots if slot["response_ms"] is not None]+ db.add(CheckRollup(check_id=check.id, hour=hour, slots=len(hour_slots), down_slots=sum(slot["status"] == "down" for slot in hour_slots),+ avg_ms=round(sum(times) / len(times), 1) if times else None, max_ms=max(times) if times else None))+ added += 1+ hour += timedelta(hours=1)+ check.rolled_until = hour_now+ db.commit()+ return added+++def purge(db, now: datetime | None = None) -> int:+ """Drop raw results older than a week; the hourly rollups keep the history. Returns how many went."""+ now = now or datetime.now(timezone.utc)+ removed = db.query(CheckResult).filter(CheckResult.time < now - RAW_KEPT).delete(synchronize_session=False)+ db.commit()+ return removeddiff --git a/src/backend/config.py b/src/backend/config.pyindex 8a2e637..e0d848b 100644--- a/src/backend/config.py+++ b/src/backend/config.py@@ -11,7 +11,7 @@ for _name, _value in dotenv_values(BASE_DIR / ".env").items():os.environ.setdefault(_name, _value)# Shown in the sidebar and compared with what each collector reports.-APP_VERSION = "0.9.2"+APP_VERSION = "0.10.0"DATABASE_URL = os.getenv("DATABASE_URL",diff --git a/src/backend/incidents.py b/src/backend/incidents.pyindex 282c203..f75b8e4 100644--- a/src/backend/incidents.py+++ b/src/backend/incidents.py@@ -38,6 +38,8 @@ def rule_kind(rule_key: str | None) -> str:return "trend:memory"if parts[0] in ("host", "system", "network") and len(parts) >= 2:return f"{parts[0]}:{parts[1]}"+ if parts[0] == "check" and len(parts) >= 3:+ return f"check:{parts[-1]}"return rule_keydiff --git a/src/backend/main.py b/src/backend/main.pyindex a1c0960..4644f33 100644--- a/src/backend/main.py+++ b/src/backend/main.py@@ -27,14 +27,14 @@ from sqlalchemy import case, func, inspect, textfrom .alerts import CONTAINER_RULE_PREFIX, CRITICAL, SERVER_OFFLINE_RULE, SEVERITIES, active_rule_keys, raise_alert, resolve_alerts, sync_alertsimport contextvars-from . import auth, dashboard, history as history_service, incidents, notify, rollups, secrets_box, stats, totp+from . import auth, availability, dashboard, history as history_service, incidents, notify, rollups, secrets_box, stats, totpfrom .auth import (STAGE_ENROLLMENT, STAGE_FULL, count_pending_attempt, create_pending_two_factor, create_session, delete_pending_two_factor, delete_session, get_recent_logs,get_session, get_user_from_session, hash_password, issue_recovery_codes, list_user_sessions, pending_two_factor_remember, read_pending_two_factor, session_lifetime, recovery_codes_left, record_audit_log,register_user, revoke_other_sessions, revoke_user_session, validate_password, verify_credentials, verify_password, verify_second_factor,)from .db import SessionLocal, check_database, get_db-from .models import ApiToken, Invite, NotificationChannel, AppSetting, AuditLog, Base, ChatMessage, ContainerMetric, ContainerRollup, Conversation, EnrollmentKey, FirewallState, HostMetric, HostRollup, IncidentAlert, JoinToken, ListenerState, MountMetric, MountRollup, PendingCollector, RecoveryCode, Server, SystemEvent, User+from .models import ApiToken, Invite, NotificationChannel, AppSetting, AuditLog, Base, ChatMessage, Check, ContainerMetric, ContainerRollup, Conversation, EnrollmentKey, FirewallState, HostMetric, HostRollup, IncidentAlert, JoinToken, ListenerState, MountMetric, MountRollup, PendingCollector, RecoveryCode, Server, SystemEvent, Userfrom .db import enginefrom .config import (@@ -1271,6 +1271,7 @@ def monitoring_overview(session_id: Annotated[str | None, Cookie(alias=SESSION_Ctotals[severity] = totals.get(severity, 0) + countreturn {"servers": result, "pending_collectors": pending, "alert_count": active_alerts.count(), "alerts_by_severity": totals,+ "checks_down": db.query(Check).filter(Check.state == "down", Check.paused.is_(False)).count(),"version": APP_VERSION, "instance_name": get_instance_name(db), "server_time": datetime.now(timezone.utc).isoformat(),# Only worked out when nothing needs attention, which is the only time the page shows it."quiet": dashboard.quiet_summary(db) if not (totals.get(CRITICAL) or totals.get("WARNING")) else None,@@ -1854,6 +1855,7 @@ def metrics_maintenance(db, purge_due: bool) -> bool:"""try:rollups.run_rollups(db)+ availability.roll(db)except Exception as exc:db.rollback()print(f"Rollups failed: {type(exc).__name__}: {exc}", flush=True)@@ -1861,6 +1863,7 @@ def metrics_maintenance(db, purge_due: bool) -> bool:if not purge_due:return Falsepurge_old_metrics(db)+ availability.purge(db)analyze_memory_trends(db)return True@@ -1912,6 +1915,7 @@ def delete_monitored_server(server_id: PathId, session_id: Annotated[str | None,db.query(FirewallState).filter(FirewallState.server_id == server.id).delete(synchronize_session=False)db.query(IncidentAlert).filter(IncidentAlert.server_id == server.id).delete(synchronize_session=False)db.query(PendingCollector).filter(PendingCollector.approved_server_id == server.id).delete(synchronize_session=False)+ availability.forget_server(db, server.id)db.delete(server)db.commit()return {"status": "deleted", "server_id": server_id}@@ -1930,6 +1934,84 @@ def update_check_interval(server_id: PathId, payload: dict, session_id: Annotatereturn {"id": server.id, "check_interval_seconds": server.check_interval_seconds}+# ---------- Availability (Milestone 11) ----------++def _check_or_404(db, check_id: int) -> Check:+ check = db.get(Check, check_id)+ if not check:+ raise HTTPException(status_code=404, detail="Check not found.")+ return check++[email protected]("/availability")+def get_availability(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ user = _current_user(session_id, db)+ return {**availability.overview(db), "can_edit": _is_admin(db, user["id"])}+++def _save_check(db, check: Check, payload: dict) -> dict:+ try:+ fields = availability.validate(payload, {server_id for (server_id,) in db.query(Server.id)})+ except ValueError as exc:+ print(f"Check not saved: {exc}", flush=True)+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ servers = json.loads(fields["server_ids"])+ for server_id in servers:+ others = sum(server_id in availability.servers_of(other) for other in db.query(Check).filter(Check.id != (check.id or 0)))+ if others >= availability.MAX_CHECKS_PER_SERVER:+ raise HTTPException(status_code=400, detail=f"A server can run at most {availability.MAX_CHECKS_PER_SERVER} checks.")+ old_servers = availability.servers_of(check) if check.id else []+ for key, value in fields.items():+ setattr(check, key, value)+ if check.id is None:+ db.add(check)+ elif old_servers and old_servers[0] != servers[0]:+ resolve_alerts(db, old_servers[0], [availability.rule_key(check)])+ db.flush()+ availability.evaluate(db, check)+ db.commit()+ return availability.summary(db, check, dict(db.query(Server.id, Server.hostname).all()))++[email protected]("/availability/checks/{check_id}")+def get_check(check_id: PathId, range: str = Query(default="24h"), session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ _current_user(session_id, db)+ return availability.detail(db, _check_or_404(db, check_id), range)++[email protected]("/availability/checks")+def create_check(payload: dict, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ _require_admin(session_id, db)+ return _save_check(db, Check(), payload)++[email protected]("/availability/checks/{check_id}")+def update_check(check_id: PathId, payload: dict, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ _require_admin(session_id, db)+ return _save_check(db, _check_or_404(db, check_id), payload)++[email protected]("/availability/checks/{check_id}/pause")+def pause_check(check_id: PathId, payload: dict, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ _require_admin(session_id, db)+ check = _check_or_404(db, check_id)+ check.paused = payload.get("paused") is True+ if not check.paused:+ check.state = "pending"+ availability.evaluate(db, check)+ db.commit()+ return availability.summary(db, check, dict(db.query(Server.id, Server.hostname).all()))++[email protected]("/availability/checks/{check_id}")+def delete_check(check_id: PathId, session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None, db=Depends(get_db)):+ _require_admin(session_id, db)+ check = _check_or_404(db, check_id)+ availability.forget_check(db, check)+ db.commit()+ return {"status": "deleted", "id": check_id}++MAX_HELPER_EVENTS_PER_CHECKIN = 20MAX_HELPER_EVENTS_PER_WEEK = 500HELPER_NOTICE_KIND = "helper_notice"@@ -2452,6 +2534,40 @@ def ingest_metrics(payload: MetricsIngestRequest, authorization: Annotated[str |db.commit()return {"status": "accepted", "interval_seconds": server.check_interval_seconds}+class CheckResultsRequest(BaseModel):+ server_id: int = Field(ge=1, le=2**31 - 1)+ results: list = Field(default=[], max_length=availability.MAX_RESULTS_PER_REPORT)+++def _enforce_report_spacing(server: Server) -> None:+ """At most one results report every couple of seconds per server (the collector sends one every 5 s at most)."""+ try:+ allowed = redis_client.set(f"infradeck:checks:{server.id}", "1", nx=True, ex=2)+ except Exception:+ return+ if not allowed:+ raise HTTPException(status_code=429, detail="Check results are arriving too often.", headers={"Retry-After": "2"})++[email protected]("/monitoring/metrics/checks", dependencies=[Depends(require_collector_listener)])+def report_check_results(payload: CheckResultsRequest, authorization: Annotated[str | None, Header()] = None, db=Depends(get_db)):+ """A collector reports the runs of its availability checks and gets back the checks it should run.+ Only the server's own collector token is accepted here."""+ server = db.query(Server).filter(Server.id == payload.server_id).first()+ token = authorization.removeprefix("Bearer ").strip() if authorization and authorization.startswith("Bearer ") else None+ if not server or not token or not server.collector_token_hash or not hmac.compare_digest(server.collector_token_hash, hashlib.sha256(token.encode()).hexdigest()):+ raise HTTPException(status_code=401, detail="Unknown collector.")+ _enforce_report_spacing(server)+ now = datetime.now(timezone.utc)+ alerting = "check:down" not in get_disabled_rules(db)+ for check_id in sorted(availability.store(db, server, payload.results, now)):+ check = db.get(Check, check_id)+ check.last_result_at = now+ availability.evaluate(db, check, now, alerting)+ db.commit()+ return {"checks": availability.for_collector(db, server), "report_every": 5}++@app.get("/dashboard/summary")def dashboard_summary(session_id: Annotated[str | None, Cookie(alias=SESSION_COOKIE_NAME)] = None,@@ -3261,6 +3377,7 @@ RULE_ROWS = [{"kind": "system:collect_slow", "when": "Collecting data takes > {collect_slow_pct}% of the check interval", "window": "{sustained_checks} check-ins", "severity": "WARNING", "edit": ["collect_slow_pct", "sustained_checks"]},{"kind": "system:ntp", "when": "The clock is not synchronized", "window": None, "severity": "WARNING", "edit": []},{"kind": "system:reboot_required", "when": "Reboot required for updates", "window": None, "severity": "INFO", "edit": []},+ {"kind": "check:down", "when": "An availability check fails its retries in a row", "window": None, "severity": "CRITICAL", "edit": []},]NOISY_FIRED = 20diff --git a/src/backend/models.py b/src/backend/models.pyindex a30da8e..82588ea 100644--- a/src/backend/models.py+++ b/src/backend/models.py@@ -545,3 +545,65 @@ class AgentReport(Base):evidence: Mapped[Optional[str]] = mapped_column(Text, nullable=True)error: Mapped[Optional[str]] = mapped_column(String(300), nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)+++class Check(Base):+ """An availability check: a service that one or more servers' collectors try every so often (see availability.py).++ ``options`` holds what depends on the type, as checked JSON: accepted status codes, keyword, redirects, TLS.+ ``state`` is the combined verdict over the servers it runs from: pending, up, down or paused."""++ __tablename__ = "checks"++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ name: Mapped[str] = mapped_column(String(120), nullable=False)+ type: Mapped[str] = mapped_column(String(16), nullable=False) # http | keyword | tcp+ target: Mapped[str] = mapped_column(String(2048), nullable=False) # a URL, or host:port for tcp+ options: Mapped[str] = mapped_column(Text, default="{}", nullable=False)+ tags: Mapped[str] = mapped_column(String(255), default="", nullable=False)+ server_ids: Mapped[str] = mapped_column(Text, default="[]", nullable=False) # JSON list+ rule: Mapped[str] = mapped_column(String(8), default="all", nullable=False) # all | any+ interval_seconds: Mapped[int] = mapped_column(Integer, default=60, nullable=False)+ retries: Mapped[int] = mapped_column(Integer, default=2, nullable=False)+ retry_interval_seconds: Mapped[int] = mapped_column(Integer, default=20, nullable=False)+ timeout_seconds: Mapped[int] = mapped_column(Integer, default=48, nullable=False)+ severity: Mapped[str] = mapped_column(String(16), default="CRITICAL", nullable=False)+ paused: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)+ state: Mapped[str] = mapped_column(String(16), default="pending", nullable=False)+ state_since: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ last_result_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ rolled_until: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(timezone.utc), nullable=False)+++class CheckResult(Base):+ """One run of a check by one server's collector."""++ __tablename__ = "check_results"+ __table_args__ = (Index("ix_check_results_check_time", "check_id", "time"),)++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ check_id: Mapped[int] = mapped_column(ForeignKey("checks.id", ondelete="CASCADE"), nullable=False)+ server_id: Mapped[int] = mapped_column(Integer, nullable=False)+ time: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ ok: Mapped[bool] = mapped_column(Boolean, nullable=False)+ response_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ code: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+ detail: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)+ cert_days: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)+++class CheckRollup(Base):+ """One check's hour: how many check slots there were, how many were down, and its response times. The 30-day,+ 1-year and 90-day views are added up from these; the current hour comes from the raw results."""++ __tablename__ = "check_rollups"+ __table_args__ = (UniqueConstraint("check_id", "hour"),)++ id: Mapped[int] = mapped_column(Integer, primary_key=True)+ check_id: Mapped[int] = mapped_column(ForeignKey("checks.id", ondelete="CASCADE"), index=True, nullable=False)+ hour: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)+ slots: Mapped[int] = mapped_column(Integer, default=0, nullable=False)+ down_slots: Mapped[int] = mapped_column(Integer, default=0, nullable=False)+ avg_ms: Mapped[Optional[float]] = mapped_column(Float, nullable=True)+ max_ms: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)diff --git a/src/collector/collector.py b/src/collector/collector.pyindex 28e4bba..d7114a2 100644--- a/src/collector/collector.py+++ b/src/collector/collector.py@@ -12,6 +12,8 @@ the socket is unavailable, host metrics continue to be sent."""from __future__ import annotations+import collections+import concurrent.futuresimport ctypesimport ctypes.utilimport hashlib@@ -22,11 +24,13 @@ import osimport platformimport reimport socket+import sslimport threadingimport timeimport urllib.error+import urllib.parseimport urllib.request-from datetime import datetime+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any@@ -507,7 +511,7 @@ def collect_system() -> dict[str, Any]:}-COLLECTOR_VERSION = "0.9.2"+COLLECTOR_VERSION = "0.10.0"MAX_INTERFACES = 16MAX_TEMPERATURES = 8_KERNEL_IMAGE = re.compile(r"vmlinuz-(\d[\w.+~-]*)")@@ -1177,6 +1181,265 @@ def _container_usage(socket_path: str, container_id: str) -> dict[str, Any]:return usage+# ---------- availability checks ----------+# The dashboard asks this collector to try services every so often (an HTTP(s) URL, a keyword in a page, a TCP port)+# and reports each run. Only what the dashboard sends is run, after checking it here as well: http/https URLs and+# host:port pairs, GET or HEAD without custom headers or body, at most 1 MiB of a response read and none of it sent+# back. No shell is involved.++CHECK_TYPES = ("http", "keyword", "tcp")+MAX_CHECKS = 50+MIN_CHECK_INTERVAL, MAX_CHECK_INTERVAL = 20, 86400+MAX_CHECK_TIMEOUT = 48+MAX_BODY_BYTES = 1024 * 1024+MAX_REDIRECTS = 10+MAX_PENDING_RESULTS = 500+CHECK_WORKERS = 8+IDLE_REPORT_SECONDS = 60+_CHECK_HOST = re.compile(r"[A-Za-z0-9]([A-Za-z0-9.-]{0,251}[A-Za-z0-9])?|\[[0-9A-Fa-f:.]+\]")+_CHECK_CODES = re.compile(r"[1-5]\d\d(-[1-5]\d\d)?")+++def _whole(value: Any, low: int, high: int) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) and low <= value <= high else None+++def validate_check(raw: Any) -> dict[str, Any] | None:+ """One check as the dashboard sent it, reduced to known fields of the right type and range; None if unusable."""+ if not isinstance(raw, dict) or raw.get("type") not in CHECK_TYPES or not isinstance(raw.get("target"), str):+ return None+ check_id = _whole(raw.get("id"), 1, 2**31 - 1)+ interval = _whole(raw.get("interval"), MIN_CHECK_INTERVAL, MAX_CHECK_INTERVAL)+ retry_interval = _whole(raw.get("retry_interval"), MIN_CHECK_INTERVAL, MAX_CHECK_INTERVAL)+ timeout = _whole(raw.get("timeout"), 1, MAX_CHECK_TIMEOUT)+ if None in (check_id, interval, retry_interval, timeout):+ return None+ check: dict[str, Any] = {"id": check_id, "type": raw["type"], "target": raw["target"], "interval": interval, "retry_interval": retry_interval, "timeout": timeout}+ target = raw["target"]+ if raw["type"] == "tcp":+ host, _, port = target.rpartition(":")+ if not _CHECK_HOST.fullmatch(host) or not port.isdigit() or not 1 <= int(port) <= 65535:+ return None+ check.update(host=host.strip("[]"), port=int(port))+ return check+ parts = urllib.parse.urlsplit(target)+ if parts.scheme not in ("http", "https") or not parts.hostname or len(target) > 2048 or any(char.isspace() or not char.isprintable() for char in target):+ return None+ codes = raw.get("accepted_codes")+ if not isinstance(codes, list) or not 1 <= len(codes) <= 10 or not all(isinstance(code, str) and _CHECK_CODES.fullmatch(code) for code in codes):+ return None+ check.update(accepted_codes=codes, follow_redirects=raw.get("follow_redirects") is True, ignore_tls=raw.get("ignore_tls") is True,+ method="HEAD" if raw.get("method") == "HEAD" and raw["type"] == "http" else "GET")+ if raw["type"] == "keyword":+ keyword = raw.get("keyword")+ if not isinstance(keyword, str) or not 1 <= len(keyword) <= 200:+ return None+ check.update(keyword=keyword, case_sensitive=raw.get("case_sensitive") is True)+ return check+++def _code_accepted(code: int, accepted: list[str]) -> bool:+ for item in accepted:+ low, _, high = item.partition("-")+ if int(low) <= code <= int(high or low):+ return True+ return False+++class _Redirects(urllib.request.HTTPRedirectHandler):+ """Follows at most MAX_REDIRECTS redirects, and only to http and https, or none at all."""+ max_redirections = MAX_REDIRECTS++ def __init__(self, follow: bool) -> None:+ self.follow = follow++ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001+ if not self.follow or urllib.parse.urlsplit(newurl).scheme not in ("http", "https"):+ return None # urllib then raises HTTPError with the 3xx code, which the accepted codes decide on+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def _cert_days(response: Any) -> int | None:+ """Days until the server's TLS certificate expires, when it was verified."""+ try:+ cert = response.fp.raw._sock.getpeercert()+ expires = ssl.cert_time_to_seconds(cert["notAfter"])+ except (AttributeError, KeyError, TypeError, ValueError, OSError):+ return None+ return int((expires - time.time()) // 86400)+++def _failure(exc: BaseException, timeout: int) -> str:+ reason = getattr(exc, "reason", exc)+ if isinstance(reason, (TimeoutError, socket.timeout)) or isinstance(exc, (TimeoutError, socket.timeout)):+ return f"Timed out after {timeout} s"+ if isinstance(reason, ssl.SSLCertVerificationError):+ return f"TLS certificate not valid: {reason.verify_message}"[:200]+ if isinstance(reason, ssl.SSLError):+ return "TLS handshake failed"+ if isinstance(reason, socket.gaierror):+ return "Host name not found"+ if isinstance(reason, ConnectionRefusedError):+ return "Connection refused"+ if isinstance(reason, ConnectionResetError):+ return "Connection reset"+ if isinstance(reason, OSError) and reason.strerror:+ return reason.strerror[:200]+ return type(reason).__name__+++def run_http(check: dict[str, Any]) -> dict[str, Any]:+ """One run of an HTTP(s) or keyword check: {ok, response_ms, code, detail, cert_days}."""+ context = ssl.create_default_context()+ if check["ignore_tls"]:+ context.check_hostname = False+ context.verify_mode = ssl.CERT_NONE+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=context), _Redirects(check["follow_redirects"]))+ request = urllib.request.Request(check["target"], method=check["method"], headers={"User-Agent": f"Infradeck-Check/{COLLECTOR_VERSION}", "Accept": "*/*"})+ started = time.monotonic()+ result: dict[str, Any] = {"ok": False, "response_ms": None, "code": None, "detail": None, "cert_days": None}+ body = b""+ try:+ with opener.open(request, timeout=check["timeout"]) as response:+ result["code"] = response.status+ if not check["ignore_tls"]:+ result["cert_days"] = _cert_days(response)+ if check["type"] == "keyword":+ deadline = started + check["timeout"]+ while len(body) < MAX_BODY_BYTES and time.monotonic() < deadline:+ chunk = response.read(min(65536, MAX_BODY_BYTES - len(body)))+ if not chunk:+ break+ body += chunk+ except urllib.error.HTTPError as exc:+ result["code"] = exc.code+ exc.close()+ except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:+ result["detail"] = _failure(exc, check["timeout"])+ return result+ result["response_ms"] = int((time.monotonic() - started) * 1000)+ if not _code_accepted(result["code"], check["accepted_codes"]):+ result["detail"] = f"HTTP {result['code']}"+ return result+ if check["type"] == "keyword":+ text = body.decode("utf-8", errors="replace")+ found = check["keyword"] in text if check["case_sensitive"] else check["keyword"].casefold() in text.casefold()+ if not found:+ result["detail"] = "Keyword not found"+ return result+ result["ok"] = True+ return result+++def run_tcp(check: dict[str, Any]) -> dict[str, Any]:+ started = time.monotonic()+ try:+ with socket.create_connection((check["host"], check["port"]), timeout=check["timeout"]):+ pass+ except OSError as exc:+ return {"ok": False, "response_ms": None, "code": None, "detail": _failure(exc, check["timeout"]), "cert_days": None}+ return {"ok": True, "response_ms": int((time.monotonic() - started) * 1000), "code": None, "detail": None, "cert_days": None}+++def run_check(check: dict[str, Any]) -> dict[str, Any]:+ try:+ outcome = run_tcp(check) if check["type"] == "tcp" else run_http(check)+ except Exception as exc: # one broken check must never stop the others+ outcome = {"ok": False, "response_ms": None, "code": None, "detail": f"Check failed: {type(exc).__name__}", "cert_days": None}+ return {"check_id": check["id"], "time": datetime.now(timezone.utc).isoformat(), **{key: value for key, value in outcome.items() if value is not None or key == "ok"}}+++def send_check_results(api_url: str, server_id: int, token: str, results: list[dict[str, Any]]) -> dict[str, Any]:+ request = urllib.request.Request(+ f"{api_url.rstrip('/')}/monitoring/metrics/checks",+ data=json.dumps({"server_id": server_id, "results": results}).encode(),+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {token}"},+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=15) as response:+ return json.loads(response.read(MAX_BODY_BYTES).decode())+++class CheckRunner(threading.Thread):+ """Runs the checks the dashboard gave this collector, each on its interval (the retry interval after a+ failure), and reports the results every few seconds; with nothing to report it asks for its checks once a+ minute. Results that couldn't be sent wait, up to the newest 500."""++ def __init__(self, api_url: str, credentials: tuple[int, str]) -> None:+ super().__init__(name="checks", daemon=True)+ self.api_url = api_url+ self.credentials = credentials # the main loop replaces this after joining again+ self.checks: dict[int, dict[str, Any]] = {}+ self.next_run: dict[int, float] = {}+ self.running: set[int] = set()+ self.pending: collections.deque = collections.deque(maxlen=MAX_PENDING_RESULTS)+ self.lock = threading.Lock()+ self.pool = concurrent.futures.ThreadPoolExecutor(max_workers=CHECK_WORKERS, thread_name_prefix="check")+ self.report_every = 5++ def set_checks(self, raw: Any) -> None:+ valid = [check for check in (validate_check(item) for item in (raw if isinstance(raw, list) else [])[:MAX_CHECKS]) if check]+ with self.lock:+ new = {check["id"]: check for check in valid}+ for check_id, check in new.items():+ if self.checks.get(check_id) != check:+ self.next_run[check_id] = time.monotonic() # new or changed: run it now+ self.checks = new+ for check_id in list(self.next_run):+ if check_id not in new:+ del self.next_run[check_id]++ def _done(self, check: dict[str, Any], future: concurrent.futures.Future) -> None:+ result = future.result()+ with self.lock:+ self.running.discard(check["id"])+ self.pending.append(result)+ if check["id"] in self.checks:+ self.next_run[check["id"]] = time.monotonic() + (check["interval"] if result["ok"] else check["retry_interval"])++ def run_due(self) -> None:+ now = time.monotonic()+ with self.lock:+ due = [check for check_id, check in self.checks.items() if self.next_run.get(check_id, 0) <= now and check_id not in self.running]+ self.running.update(check["id"] for check in due)+ for check in due:+ self.pool.submit(run_check, check).add_done_callback(lambda future, check=check: self._done(check, future))++ def report(self) -> bool:+ with self.lock:+ batch = list(self.pending)+ self.pending.clear()+ server_id, token = self.credentials+ try:+ response = send_check_results(self.api_url, server_id, token, batch)+ except urllib.error.HTTPError as exc:+ with self.lock:+ self.pending.extendleft(reversed(batch))+ if exc.code == 404:+ self.report_every = 300 # a dashboard without availability checks+ return False+ except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException):+ with self.lock:+ self.pending.extendleft(reversed(batch))+ return False+ self.set_checks(response.get("checks") if isinstance(response, dict) else None)+ every = _whole(response.get("report_every"), 2, 300) if isinstance(response, dict) else None+ self.report_every = every or 5+ if batch:+ print(f"Reported {len(batch)} check results", flush=True)+ return True++ def run(self) -> None:+ last_report = -IDLE_REPORT_SECONDS+ while True:+ self.run_due()+ since = time.monotonic() - last_report+ if since >= IDLE_REPORT_SECONDS or (self.pending and since >= self.report_every):+ self.report()+ last_report = time.monotonic()+ time.sleep(1)++def send_payload(api_url: str, server_id: int, token: str, payload: dict[str, Any]) -> dict[str, Any]:request = urllib.request.Request(f"{api_url.rstrip('/')}/monitoring/metrics/ingest",@@ -1338,6 +1601,8 @@ def run_collector() -> None:server_id, token = resolve_credentials(api_url)interval = max(15, int(os.getenv("INFRADECK_CHECK_INTERVAL_SECONDS", "60")))print(f"Collector started for server {server_id}; API={api_url}", flush=True)+ checks = CheckRunner(api_url, (server_id, token))+ checks.start()while True:started = time.monotonic()try:@@ -1357,6 +1622,7 @@ def run_collector() -> None:print(f"Backend no longer accepts server {server_id} (HTTP {exc.code}); requesting approval again", flush=True)_credentials_path().unlink(missing_ok=True)server_id, token = request_approval(api_url)+ checks.credentials = (server_id, token)try:save_credentials(server_id, token)except OSError:diff --git a/src/frontend/src/App.jsx b/src/frontend/src/App.jsxindex c28e72b..fa4ca4d 100644--- a/src/frontend/src/App.jsx+++ b/src/frontend/src/App.jsx@@ -4,6 +4,7 @@ import AccountPage from './account/AccountPage.jsx'import AdminPage from './admin/AdminPage.jsx'import MorePage from './more/MorePage.jsx'import AgentPage from './agent/AgentPage.jsx'+import AvailabilityPage from './availability/AvailabilityPage.jsx'import { apiRequest } from './api.js'import { LoginPage, RegisterPage } from './auth/AuthPages.jsx'import DashboardPage from './dashboard/DashboardPage.jsx'@@ -83,6 +84,7 @@ function App() {<Route path="/" element={page(<DashboardPage user={user} onLogout={handleLogout} />)} /><Route path="/dashboard" element={page(<Navigate to="/" replace />)} /><Route path="/statistics" element={page(<StatisticsPage user={user} onLogout={handleLogout} />)} />+ <Route path="/availability" element={page(<AvailabilityPage user={user} onLogout={handleLogout} />)} /><Route path="/agent" element={page(<AgentPage user={user} onLogout={handleLogout} />)} /><Route path="/reports" element={page(<Navigate to="/agent" replace />)} /><Route path="/logs" element={page(<Navigate to="/agent" replace />)} />diff --git a/src/frontend/src/availability/AvailabilityPage.jsx b/src/frontend/src/availability/AvailabilityPage.jsxnew file mode 100644index 0000000..3da3884--- /dev/null+++ b/src/frontend/src/availability/AvailabilityPage.jsx@@ -0,0 +1,429 @@+// Availability: checks that your services answer, run by the collectors on your own servers (Milestone 11).+// A summary strip, the checks that are down pulled out of the rack, one row per check grouped by tag with its+// last 30 results, and the selected check's details below the list. Admins add checks in the New check drawer.+import { Fragment, useEffect, useMemo, useState } from 'react'+import { Link, useSearchParams } from 'react-router-dom'+import { apiRequest } from '../api.js'+import { Icon } from '../icons.jsx'+import { AppShell, PhoneHeader } from '../shell.jsx'+import { Drawer, Notice, ago, useAction, usePhone } from '../ui.jsx'+import { SectionHeading } from '../dashboard/NeedsAttention.jsx'+import { CheckForm } from './CheckForm.jsx'++const REFRESH_SECONDS = 15+const TYPE_LABEL = { http: 'HTTP(s)', keyword: 'Keyword', tcp: 'TCP port' }+const SLOT_CLASS = { up: 'bg-ok/80', slow: 'bg-[#8a7a3e]', retrying: 'bg-warn', down: 'bg-signal', paused: 'bg-edge', empty: 'bg-line' }+const LEGEND = [['up', 'up'], ['slow', 'slow'], ['retrying', 'retrying'], ['down', 'down'], ['paused', 'paused']]+const FILTERS = [['all', 'All'], ['down', 'Down'], ['slow', 'Slow'], ['paused', 'Paused']]++const percent = (value) => (value == null ? '—' : `${value >= 99.995 ? 100 : value.toFixed(value >= 99 ? 2 : 1)}%`)+const every = (seconds) => (seconds % 86400 === 0 ? `${seconds / 86400} d` : seconds % 3600 === 0 ? `${seconds / 3600} h` : seconds % 60 === 0 && seconds >= 300 ? `${seconds / 60} min` : `${seconds} s`)+const isSlow = (check) => !check.paused && check.state !== 'down' && check.strip.slice(-3).some((slot) => slot.status === 'slow')+const shortTarget = (check) => (check.type === 'keyword' ? `${check.target} · expects “${check.keyword}”` : check.target)++function useAvailability() {+ const [state, setState] = useState({ data: null, error: '', loadedAt: 0 })+ const [version, setVersion] = useState(0)+ useEffect(() => {+ let active = true+ const load = () => apiRequest('/availability', { method: 'GET' })+ .then((data) => { if (active) setState({ data, error: '', loadedAt: Date.now() }) })+ .catch((error) => { if (active) setState((current) => ({ ...current, error: error.message || 'Could not load the checks.' })) })+ load()+ const timer = setInterval(load, REFRESH_SECONDS * 1000)+ return () => { active = false; clearInterval(timer) }+ }, [version])+ return { ...state, reload: () => setVersion((value) => value + 1) }+}++// The last 30 results, oldest on the left; missing slots (a new check) are drawn empty in front.+function Strip({ check, size = 'md' }) {+ const slots = check.strip.length >= 30 ? check.strip.slice(-30) : [...Array(30 - check.strip.length).fill(null), ...check.strip]+ const height = size === 'sm' ? 'h-4' : 'h-5'+ return (+ <span className="flex items-center gap-[2px]" role="img" aria-label={`Last ${check.strip.length} checks: ${check.strip.filter((slot) => slot.status === 'down').length} down`}>+ {slots.map((slot, index) => <span key={index} title={slot ? `${new Date(slot.start).toLocaleString()} · ${slot.status}${slot.response_ms != null ? ` · ${slot.response_ms} ms` : ''}` : 'no result yet'}+ className={`${height} w-[4px] shrink-0 rounded-[1px] ${SLOT_CLASS[check.paused ? 'paused' : slot ? slot.status : 'empty']}`} />)}+ </span>+ )+}++function Sparkline({ check }) {+ const values = check.strip.map((slot) => slot.response_ms).filter((value) => value != null)+ if (values.length < 2) return <span className="inline-block w-14" />+ const max = Math.max(...values), min = Math.min(...values)+ const points = values.map((value, index) => `${(index / (values.length - 1)) * 54},${14 - ((value - min) / (max - min || 1)) * 10}`).join(' ')+ return <svg width="56" height="16" aria-hidden="true" className={check.state === 'down' ? 'text-signal' : 'text-soft'}><polyline points={points} fill="none" stroke="currentColor" strokeWidth="1.2" /></svg>+}++function Summary({ data }) {+ const { counts, uptime_30d: uptime, expiring } = data+ const soonest = [...expiring].sort((a, b) => a.days - b.days)[0]+ const cells = [+ { label: 'Up', value: <>{counts.up}<span className="ml-1 text-xs font-normal text-muted">of {counts.total} checks</span></> },+ { label: 'Down', value: <span className={counts.down ? 'text-signal' : ''}>{counts.down}</span> },+ { label: 'Paused', value: counts.paused },+ { label: 'Uptime, all checks · 30 d', value: percent(uptime) },+ { label: 'Certificates expiring in 21 d', value: <><span className={expiring.length ? 'text-warn' : ''}>{expiring.length}</span>{soonest && <span className="ml-1.5 text-xs font-normal text-muted">{soonest.name}, {soonest.days} days</span>}</> },+ ]+ return (+ <div className="card grid grid-cols-2 divide-line overflow-hidden md:grid-cols-5 md:divide-x">+ {cells.map(({ label, value }, index) => (+ <div key={label} className={`min-w-0 px-[18px] py-3.5 ${index === 4 ? 'col-span-2 md:col-span-1' : ''} max-md:border-b max-md:border-line`}>+ <div className="truncate text-xs text-muted">{label}</div>+ <div className="mt-1.5 truncate text-[21px] font-semibold leading-7 text-paper">{value}</div>+ </div>+ ))}+ </div>+ )+}++function DownNow({ checks, canEdit, onOpen, onPause }) {+ if (!checks.length) return null+ return (+ <section aria-label="Down now">+ <SectionHeading title="Down now" detail={`${checks.length} ${checks.length === 1 ? 'check' : 'checks'}`} />+ <div className="rack">+ {checks.map((check) => {+ const critical = check.severity === 'CRITICAL'+ const failing = check.servers.map((server) => server.hostname).join(' and ')+ return (+ <div key={check.id} className={`drawer ${critical ? 'drawer-critical drawer-out' : 'drawer-alert'} grid-cols-[minmax(0,1fr)_auto] gap-x-4 py-2 md:grid-cols-[110px_minmax(0,1fr)_auto]`}>+ <span className={`col-span-2 text-[11px] font-bold tracking-[0.08em] md:col-span-1 ${critical ? 'text-bg' : 'text-warn'}`}>DOWN {ago(check.state_since).replace(' ago', '').toUpperCase()}</span>+ <span className="min-w-0">+ <span className={`block truncate text-[13px] font-semibold ${critical ? 'text-bg' : 'text-paper'}`}>{check.name} · {check.target.replace(/^https?:\/\//, '')}</span>+ <span className={`block truncate text-xs ${critical ? 'text-bg/80' : 'text-muted'}`}>{check.last_detail || 'No answer'} from {failing} · failed {check.retries + 1} {check.retries ? 'checks in a row' : 'check'}{check.quiet_until ? ' · new check, no alert yet' : ''}</span>+ </span>+ <span className="col-span-2 mt-2 flex gap-2 md:col-span-1 md:mt-0">+ <button type="button" onClick={() => onOpen(check)} className={`btn btn-sm ${critical ? 'border-[#160800] bg-[#160800] text-paper hover:!border-black hover:!bg-black' : ''}`}>Open check</button>+ {canEdit && <button type="button" onClick={() => onPause(check, true)} className={`btn btn-sm ${critical ? 'border-[#160800] bg-[#160800] text-paper hover:!border-black hover:!bg-black' : ''}`}>Pause</button>}+ </span>+ </div>+ )+ })}+ </div>+ </section>+ )+}++function CheckRow({ check, selected, onSelect }) {+ const down = check.state === 'down'+ const lowUptime = check.uptime_24h != null && check.uptime_24h < 99+ return (+ <tr onClick={() => onSelect(check)} className={`cursor-pointer border-t border-line hover:bg-raised/60 ${selected ? 'bg-raised/70' : ''}`}>+ <td className={`max-w-[260px] py-2.5 pl-[18px] pr-3 ${down ? 'shadow-[inset_3px_0_0_var(--color-signal)]' : selected ? 'shadow-[inset_3px_0_0_var(--color-paper)]' : ''}`}>+ <button type="button" onClick={(event) => { event.stopPropagation(); onSelect(check) }} className="block max-w-full truncate text-left text-[13px] font-medium text-paper">{check.name}</button>+ <span className="mono block truncate text-[11px] text-muted" title={check.target}>{check.target}</span>+ </td>+ <td className="px-3"><span className="chip">{TYPE_LABEL[check.type]}</span></td>+ <td className="px-3"><Strip check={check} /></td>+ <td className={`px-3 text-right text-[13px] tabular-nums ${check.paused ? 'text-muted' : lowUptime || down ? 'text-signal' : 'text-paper'}`}>{check.paused ? 'paused' : percent(check.uptime_24h)}</td>+ <td className="px-3 text-right text-[13px] tabular-nums text-paper">{check.paused ? '—' : percent(check.uptime_30d)}</td>+ <td className="px-3">+ <span className="flex items-center gap-2.5">{!check.paused && <Sparkline check={check} />}+ <span className={`text-[13px] tabular-nums ${down ? 'text-signal' : isSlow(check) ? 'text-warn' : 'text-paper'}`}>{check.paused ? '—' : down ? (check.last_detail?.replace(/^HTTP /, '') || 'down') : check.response_ms != null ? `${check.response_ms} ms` : '—'}</span>+ </span>+ </td>+ <td className={`px-3 text-[13px] ${check.cert_days != null && check.cert_days <= 21 ? 'text-warn' : 'text-paper'}`}>{check.cert_days != null ? `${check.cert_days} days` : check.target.startsWith('http://') ? <span className="text-muted">no TLS</span> : <span className="text-muted">—</span>}</td>+ <td className="px-3"><span className="flex flex-wrap gap-1">{check.servers.map((server) => <span key={server.id} className="chip mono">{server.hostname}</span>)}</span></td>+ <td className="pl-3 pr-[18px] text-right text-[13px] tabular-nums text-paper">{every(check.interval_seconds)}</td>+ </tr>+ )+}++function PhoneCheck({ check, onSelect }) {+ const down = check.state === 'down'+ return (+ <button type="button" onClick={() => onSelect(check)} className={`block w-full border-t border-line px-4 py-3 text-left ${down ? 'shadow-[inset_3px_0_0_var(--color-signal)]' : ''}`}>+ <span className="flex items-baseline gap-2">+ <span className="min-w-0 flex-1 truncate text-[15px] font-medium text-paper">{check.name}</span>+ <span className={`shrink-0 text-[13px] tabular-nums ${check.paused ? 'text-muted' : down ? 'text-signal' : 'text-paper'}`}>{check.paused ? 'paused' : down ? (check.last_detail || 'down') : percent(check.uptime_24h)}</span>+ </span>+ <span className="mono mt-0.5 block truncate text-[11px] text-muted">{TYPE_LABEL[check.type]} · {check.target}</span>+ <span className="mt-2 flex items-center justify-between gap-3"><Strip check={check} size="sm" /><span className="shrink-0 text-xs tabular-nums text-muted">{check.response_ms != null && !check.paused ? `${check.response_ms} ms` : ''}</span></span>+ </button>+ )+}++function ChecksTable({ checks, selectedId, onSelect, phone }) {+ const [query, setQuery] = useState('')+ const [filter, setFilter] = useState('all')+ const counts = { all: checks.length, down: checks.filter((check) => check.state === 'down').length, slow: checks.filter(isSlow).length, paused: checks.filter((check) => check.paused).length }+ const shown = checks.filter((check) => (filter === 'all' || (filter === 'down' && check.state === 'down') || (filter === 'slow' && isSlow(check)) || (filter === 'paused' && check.paused))+ && (!query || `${check.name} ${check.target}`.toLowerCase().includes(query.toLowerCase())))+ const groups = useMemo(() => {+ const byTag = new Map()+ for (const check of shown) {+ const tag = check.tags[0] || ''+ if (!byTag.has(tag)) byTag.set(tag, [])+ byTag.get(tag).push(check)+ }+ return [...byTag.entries()].sort(([a], [b]) => (a === '' ? 1 : b === '' ? -1 : a.localeCompare(b)))+ }, [shown])++ return (+ <section className="card overflow-hidden" aria-labelledby="checks-title">+ <div className="flex flex-wrap items-center gap-3 px-[18px] py-3.5">+ <h2 id="checks-title" className="m-0 text-sm font-semibold text-paper">Checks</h2>+ <span className="text-xs text-muted">{checks.length} · grouped by tag</span>+ <span className="flex w-full flex-wrap items-center gap-2 md:ml-auto md:w-auto">+ <label className="relative max-md:w-full"><span className="sr-only">Filter by name or address</span>+ <Icon name="search" size={13} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted" />+ <input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Filter by name or address" className="field h-8 pl-8 text-[13px] md:w-56" />+ </label>+ <span className="seg" role="group" aria-label="Show">+ {FILTERS.map(([id, label]) => <button key={id} type="button" aria-pressed={filter === id} onClick={() => setFilter(id)}>{label} {counts[id]}</button>)}+ </span>+ </span>+ </div>+ {phone ? <div>+ {groups.map(([tag, rows]) => (+ <Fragment key={tag || '-'}>+ <div className="border-t border-line px-4 py-2 text-[13px] font-semibold text-paper">{tag || 'No tag'} <span className="ml-1.5 text-xs font-normal text-muted">{rows.length}</span></div>+ {rows.map((check) => <PhoneCheck key={check.id} check={check} onSelect={onSelect} />)}+ </Fragment>+ ))}+ {!shown.length && <p className="m-0 border-t border-line px-4 py-6 text-center text-[13px] text-muted">No check matches.</p>}+ </div> : <div className="custom-scroll overflow-x-auto">+ <table className="w-full min-w-[1080px] border-collapse text-left">+ <thead><tr className="grid-head">+ <th className="py-2 pl-[18px] pr-3 font-medium">Check</th><th className="px-3 font-medium">Type</th><th className="px-3 font-medium">Last 30 checks</th>+ <th className="px-3 text-right font-medium">24 h</th><th className="px-3 text-right font-medium">30 d</th><th className="px-3 font-medium">Response</th>+ <th className="px-3 font-medium">Cert</th><th className="px-3 font-medium">Checked from</th><th className="pl-3 pr-[18px] text-right font-medium">Every</th>+ </tr></thead>+ <tbody>+ {groups.map(([tag, rows]) => (+ <Fragment key={tag || '-'}>+ <tr className="border-t border-line"><td colSpan={9} className="px-[18px] py-2 text-[13px] font-semibold text-paper">{tag || 'No tag'} <span className="ml-1.5 text-xs font-normal text-muted">{rows.length} {rows.length === 1 ? 'check' : 'checks'}</span></td></tr>+ {rows.map((check) => <CheckRow key={check.id} check={check} selected={check.id === selectedId} onSelect={onSelect} />)}+ </Fragment>+ ))}+ {!shown.length && <tr className="border-t border-line"><td colSpan={9} className="px-[18px] py-6 text-center text-[13px] text-muted">No check matches.</td></tr>}+ </tbody>+ </table>+ </div>}+ <div className="flex flex-wrap gap-4 border-t border-line px-[18px] py-2.5 text-[11px] text-muted">+ {LEGEND.map(([status, label]) => <span key={status} className="flex items-center gap-1.5"><span className={`h-2 w-2 rounded-[1px] ${SLOT_CLASS[status]}`} />{label}</span>)}+ </div>+ </section>+ )+}++const RANGE_LABELS = [['1h', '1 h'], ['24h', '24 h'], ['7d', '7 d'], ['30d', '30 d']]++// Response time per server: the first server a solid line, the others dashed.+function ResponseChart({ series, range, compact }) {+ const points = series.flatMap((line) => line.points)+ if (!points.length) return <p className="m-0 flex h-[150px] items-center justify-center text-xs text-muted">No answers in this range yet.</p>+ const times = points.map((point) => new Date(point.time).getTime())+ const spanMs = { '1h': 3600e3, '24h': 86400e3, '7d': 7 * 86400e3, '30d': 30 * 86400e3 }[range]+ // A check younger than the range starts where its data starts, rather than squeezed against the right edge.+ const end = Math.max(...times), start = Math.max(end - spanMs, Math.min(...times))+ const top = Math.max(...points.map((point) => point.ms), 1)+ const scale = top <= 10 ? 10 : 10 ** Math.floor(Math.log10(top)) * Math.ceil(top / 10 ** Math.floor(Math.log10(top)))+ // On a phone the drawing is narrower, so the labels keep a readable size.+ const width = compact ? 340 : 600, height = compact ? 120 : 140, left = 34+ const x = (time) => left + ((new Date(time).getTime() - start) / Math.max(1, end - start)) * (width - left)+ const y = (ms) => 6 + (1 - ms / scale) * (height - 12)+ const label = (time) => new Date(time).toLocaleString([], range === '1h' || range === '24h' ? { hour: '2-digit', minute: '2-digit' } : { day: 'numeric', month: 'short' })+ return (+ <div>+ <svg viewBox={`0 0 ${width} ${height + 16}`} className="h-auto w-full" role="img" aria-label="Response time per server">+ {[0, 0.5, 1].map((share) => <g key={share}>+ <line x1={left} x2={width} y1={y(scale * share)} y2={y(scale * share)} stroke="var(--color-line)" />+ <text x={left - 6} y={y(scale * share) + 3} textAnchor="end" fontSize="9" fill="var(--color-muted)">{Math.round(scale * share)}</text>+ </g>)}+ {series.map((line, index) => <polyline key={line.hostname} points={line.points.map((point) => `${x(point.time)},${y(point.ms)}`).join(' ')} fill="none"+ stroke={index === 0 ? 'var(--color-paper)' : 'var(--color-muted)'} strokeWidth="1.3" strokeDasharray={index === 0 ? undefined : '3 3'} strokeLinejoin="round" />)}+ <text x={left} y={height + 13} fontSize="9" fill="var(--color-muted)">{label(start)}</text>+ <text x={width} y={height + 13} fontSize="9" textAnchor="end" fill="var(--color-muted)">now</text>+ </svg>+ <div className="mt-1 flex flex-wrap gap-4 text-[11px] text-muted">+ {series.map((line, index) => <span key={line.hostname} className="flex items-center gap-1.5"><span className={`inline-block w-4 border-t ${index === 0 ? 'border-paper' : 'border-dashed border-muted'}`} />from {line.hostname}</span>)}+ </div>+ </div>+ )+}++function Days({ days }) {+ const known = days.filter((day) => day.uptime != null)+ const tone = (uptime) => (uptime == null ? 'bg-line' : uptime >= 99.9 ? 'bg-ok/80' : uptime >= 99 ? 'bg-warn' : 'bg-signal')+ return (+ <div>+ <div className="flex items-baseline justify-between gap-3">+ <h3 className="m-0 text-[13px] font-semibold text-paper">Last 90 days <span className="ml-1.5 text-xs font-normal text-muted">one bar per day</span></h3>+ <span className="text-xs tabular-nums text-muted">{known.length ? percent(known.reduce((sum, day) => sum + day.uptime, 0) / known.length) : '—'}</span>+ </div>+ <div className="mt-2.5 flex h-6 items-stretch gap-[2px]">+ {days.map((day) => <span key={day.day} title={`${new Date(day.day).toLocaleDateString([], { day: 'numeric', month: 'short' })} · ${day.uptime == null ? 'no data' : percent(day.uptime)}`} className={`min-w-0 flex-1 rounded-[1px] ${tone(day.uptime)}`} />)}+ </div>+ <div className="mt-1 flex justify-between text-[11px] text-muted"><span>{new Date(days[0].day).toLocaleDateString([], { day: 'numeric', month: 'short' })}</span><span>today</span></div>+ </div>+ )+}++function useCheckDetail(checkId, range, refreshedAt) {+ const [detail, setDetail] = useState(null)+ useEffect(() => {+ let active = true+ apiRequest(`/availability/checks/${checkId}?range=${range}`, { method: 'GET' }).then((data) => { if (active) setDetail(data) }).catch(() => {})+ return () => { active = false }+ }, [checkId, range, refreshedAt])+ return detail?.range === range ? detail : detail && { ...detail, series: null }+}++function Detail({ check, canEdit, onEdit, onPause, onDelete, refreshedAt }) {+ const phone = usePhone()+ const [range, setRange] = useState('24h')+ const detail = useCheckDetail(check.id, range, refreshedAt)+ const options = check.options || {}+ const settings = [+ ['Checked from', `${check.servers.map((server) => server.hostname).join(', ')}${check.servers.length > 1 ? ` · down when ${check.rule === 'all' ? 'all fail' : 'any fails'}` : ''}`],+ ['Every', `${every(check.interval_seconds)} · ${check.retries} ${check.retries === 1 ? 'retry' : 'retries'}${check.retries ? `, ${every(check.retry_interval_seconds)} apart` : ''}`],+ ['Timeout', `${check.timeout_seconds} s`],+ ...(check.type !== 'tcp' ? [['Accepts', (options.accepted_codes || []).join(', ')], ['Redirects', options.follow_redirects ? 'followed, up to 10' : 'not followed'], ['TLS', options.ignore_tls ? 'errors ignored' : 'must be valid']] : []),+ ...(options.upside_down ? [['Upside down', 'up means the service is unreachable']] : []),+ ['Severity', check.severity === 'CRITICAL' ? 'Critical' : 'Warning'],+ ['Tags', check.tags.join(', ') || '—'],+ ]+ const ms = (value) => (value != null ? <>{value}<span className="ml-1 text-xs font-normal text-muted">ms</span></> : '—')+ const stats = [+ { label: 'Response now', value: ms(check.state !== 'down' && !check.paused ? check.response_ms : null) },+ { label: 'Average · 24 h', value: ms(detail?.average_24h) },+ { label: 'Uptime 24 h · 30 d · 1 y', value: <>{percent(check.uptime_24h)}<span className="ml-1.5 text-xs font-normal text-muted">{percent(check.uptime_30d)} · {percent(detail?.uptime_1y)}</span></> },+ { label: 'Certificate', value: check.cert_days != null ? `${check.cert_days} days` : '—' },+ { label: 'Last down', value: detail?.last_down ? <>{detail.last_down.ongoing ? 'now' : ago(detail.last_down.at)}<span className="ml-1.5 text-xs font-normal text-muted">for {detail.last_down.for}</span></> : detail ? 'never' : '—' },+ ]+ return (+ <section className="card overflow-hidden" aria-labelledby="check-detail-title">+ <header className="flex flex-wrap items-center gap-3 border-b border-line px-[18px] py-3.5">+ <span className={`dot ${check.paused ? '' : check.state === 'down' ? 'dot-signal' : check.state === 'up' ? 'dot-ok' : 'dot-warn'}`} />+ <h2 id="check-detail-title" className="m-0 text-[17px] font-semibold text-paper">{check.name}</h2>+ <span className="chip">{TYPE_LABEL[check.type]}</span>+ <span className="mono min-w-0 flex-1 truncate text-xs text-muted">{shortTarget(check)}</span>+ {canEdit && <span className="flex gap-2">+ <button type="button" className="btn btn-sm" onClick={() => onPause(check, !check.paused)}>{check.paused ? 'Resume' : 'Pause'}</button>+ <button type="button" className="btn btn-sm" onClick={() => onEdit(check)}>Edit</button>+ <button type="button" className="btn btn-sm" onClick={() => onDelete(check)}>Delete</button>+ </span>}+ </header>+ <div className="grid grid-cols-2 divide-line border-b border-line md:grid-cols-5 md:divide-x">+ {stats.map(({ label, value }, index) => (+ <div key={label} className={`min-w-0 px-[18px] py-3.5 max-md:border-b max-md:border-line ${index === 4 ? 'max-md:col-span-2' : ''}`}><div className="truncate text-xs text-muted">{label}</div><div className="mt-1.5 text-[19px] font-semibold text-paper md:truncate">{value}</div></div>+ ))}+ </div>+ <div className="grid lg:grid-cols-[minmax(0,1fr)_320px]">+ <div className="space-y-6 px-[18px] py-4">+ <div>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h3 className="m-0 text-[13px] font-semibold text-paper">Response time <span className="ml-1.5 text-xs font-normal text-muted">ms · per server</span></h3>+ <span className="seg" role="group" aria-label="Range">{RANGE_LABELS.map(([id, label]) => <button key={id} type="button" aria-pressed={range === id} onClick={() => setRange(id)}>{label}</button>)}</span>+ </div>+ <div className="mt-3">{detail?.series ? <ResponseChart series={detail.series} range={range} compact={phone} /> : <div className="h-[150px]" />}</div>+ </div>+ {detail?.days && <Days days={detail.days} />}+ <div>+ <h3 className="m-0 text-[13px] font-semibold text-paper">Last 30 checks</h3>+ <div className="mt-2.5"><Strip check={check} /></div>+ <p className="mb-0 mt-2.5 text-xs text-muted">+ {check.paused ? 'Paused: no checks run and no alerts are sent.' : check.state === 'pending' ? 'Waiting for the first results from its servers.' : `${check.state === 'down' ? 'Down' : 'Up'} since ${check.state_since ? new Date(check.state_since).toLocaleString() : '—'}.`}+ {check.last_result_at && ` Last result ${ago(check.last_result_at)}${check.last_detail ? `: ${check.last_detail}` : ''}.`}+ {check.quiet_until && ` New check: it alerts from ${new Date(check.quiet_until).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}, so a wrong address doesn't page anyone.`}+ </p>+ </div>+ </div>+ <div className="space-y-6 border-line px-[18px] py-4 lg:border-l max-lg:border-t">+ <div>+ <h3 className="m-0 text-[13px] font-semibold text-paper">Events</h3>+ {detail?.events?.length ? <ul className="m-0 mt-3 list-none divide-y divide-line p-0">+ {detail.events.map((event) => <li key={`${event.kind}-${event.time}`} className="grid grid-cols-[64px_10px_minmax(0,1fr)] items-start gap-2.5 py-2 text-xs">+ <span className="text-muted">{ago(event.time)}</span><span className={`mt-1 h-2 w-2 rounded-[1px] ${event.kind === 'down' ? 'bg-signal' : 'bg-ok'}`} /><span className="text-paper">{event.text}</span>+ </li>)}+ </ul> : <p className="mb-0 mt-2 text-xs text-muted">{detail ? 'It hasn’t gone down yet.' : ''}</p>}+ </div>+ <div>+ <h3 className="m-0 text-[13px] font-semibold text-paper">Settings</h3>+ <dl className="mb-0 mt-3 grid grid-cols-[100px_minmax(0,1fr)] gap-x-3 gap-y-2 text-xs">+ {settings.map(([label, value]) => <Fragment key={label}><dt className="text-muted">{label}</dt><dd className="m-0 text-paper">{value}</dd></Fragment>)}+ </dl>+ </div>+ </div>+ </div>+ </section>+ )+}++function EmptyChecks({ canEdit, onNew }) {+ return (+ <div className="card px-[18px] py-10 text-center">+ <p className="m-0 text-sm font-medium text-paper">No checks yet.</p>+ <p className="mx-auto mb-0 mt-2 max-w-[520px] text-[13px] text-muted">A check tries a website or a port every minute or so from the servers you pick, and opens an incident when it stops answering.</p>+ {canEdit && <button type="button" className="btn btn-primary mt-4" onClick={onNew}><Icon name="plus" size={14} />New check</button>}+ </div>+ )+}++export default function AvailabilityPage({ user, onLogout }) {+ const phone = usePhone()+ const { data, error, reload, loadedAt } = useAvailability()+ const [params, setParams] = useSearchParams()+ const [editing, setEditing] = useState(null) // null, 'new', or a check+ const [action, run] = useAction()+ const checks = data?.checks || []+ const selected = checks.find((check) => String(check.id) === params.get('check')) || null+ const canEdit = Boolean(data?.can_edit)++ const select = (check) => {+ const next = new URLSearchParams(params)+ if (selected?.id === check.id) next.delete('check'); else next.set('check', String(check.id))+ setParams(next, { replace: true })+ if (selected?.id !== check.id) requestAnimationFrame(() => document.getElementById('check-detail')?.scrollIntoView({ behavior: 'smooth', block: 'start' }))+ }+ const pause = (check, paused) => run(async () => { await apiRequest(`/availability/checks/${check.id}/pause`, { method: 'POST', body: JSON.stringify({ paused }) }); reload() })+ const remove = (check) => {+ if (!window.confirm(`Delete the check “${check.name}” and its history?`)) return+ run(async () => { await apiRequest(`/availability/checks/${check.id}`, { method: 'DELETE' }); const next = new URLSearchParams(params); next.delete('check'); setParams(next, { replace: true }); reload() })+ }+ const saved = (check) => { setEditing(null); reload(); const next = new URLSearchParams(params); next.set('check', String(check.id)); setParams(next, { replace: true }) }+ const down = checks.filter((check) => check.state === 'down' && !check.paused)+ const unable = (data?.servers || []).filter((server) => !server.can_run_checks)++ const body = (+ <div className="space-y-6">+ {!phone && <header className="flex flex-wrap items-start justify-between gap-4">+ <div>+ <h1 className="m-0 text-[21px] font-semibold leading-7 text-paper">Availability</h1>+ <p className="mb-0 mt-1.5 max-w-[680px] text-[13px] leading-5 text-soft">Checks that your services answer, run from your own servers. Like Uptime Kuma, but every check knows which machine it ran from.</p>+ </div>+ <span className="flex flex-wrap gap-2">+ <button type="button" className="btn" disabled title="Coming in a later step">Status page</button>+ <button type="button" className="btn" disabled title="Coming in a later step">Maintenance</button>+ {canEdit && <button type="button" className="btn btn-primary" onClick={() => setEditing('new')}><Icon name="plus" size={14} />New check</button>}+ </span>+ </header>}+ {error && !data && <Notice>{error}</Notice>}+ <Notice>{action.error}</Notice>+ {data && <>+ {checks.length > 0 && <Summary data={data} />}+ <DownNow checks={down} canEdit={canEdit} onOpen={select} onPause={pause} />+ {checks.length ? <ChecksTable checks={checks} selectedId={selected?.id} onSelect={select} phone={phone} /> : <EmptyChecks canEdit={canEdit} onNew={() => setEditing('new')} />}+ {selected && <div id="check-detail" className="scroll-mt-20"><Detail key={selected.id} check={selected} refreshedAt={loadedAt} canEdit={canEdit} onEdit={setEditing} onPause={pause} onDelete={remove} /></div>}+ {unable.length > 0 && checks.length > 0 && <p className="m-0 text-xs text-muted">{unable.map((server) => server.hostname).join(', ')} {unable.length === 1 ? 'has' : 'have'} a collector older than 0.10.0 or {unable.length === 1 ? 'hasn’t' : 'haven’t'} reported yet, so {unable.length === 1 ? 'it' : 'they'} can’t run checks. <Link to="/admin#servers" className="link">Update the collector</Link>.</p>}+ </>}+ <Drawer open={editing !== null} title={editing && editing !== 'new' ? `Edit ${editing.name}` : 'New check'} description="Track a service you run. The servers you pick try it on every interval and report each result." onClose={() => setEditing(null)} width={680}>+ {editing !== null && <CheckForm check={editing === 'new' ? null : editing} servers={data?.servers || []} onSaved={saved} onCancel={() => setEditing(null)} />}+ </Drawer>+ </div>+ )++ if (phone) {+ return (+ <AppShell user={user} onLogout={onLogout} crumbs={[{ label: 'Availability' }]} bare phoneHeader>+ <PhoneHeader title="Availability" back={{ label: 'More', to: '/more' }} action={canEdit ? <button type="button" aria-label="New check" onClick={() => setEditing('new')} className="flex h-11 w-11 items-center justify-center text-paper"><Icon name="plus" size={18} /></button> : <span />} />+ <div className="px-4 pt-3">{body}</div>+ </AppShell>+ )+ }+ return <AppShell user={user} onLogout={onLogout} bare><div className="px-3 pb-8 pt-5 sm:px-4 lg:px-7 lg:pt-7">{body}</div></AppShell>+}+diff --git a/src/frontend/src/availability/CheckForm.jsx b/src/frontend/src/availability/CheckForm.jsxnew file mode 100644index 0000000..f426f60--- /dev/null+++ b/src/frontend/src/availability/CheckForm.jsx@@ -0,0 +1,196 @@+// The New check / Edit form in the drawer: the type, what to check, from which servers, the timing in numbers+// with one sentence saying what they mean together, what counts as up, and how bad it is when it's down.+import { useState } from 'react'+import { Link } from 'react-router-dom'+import { apiRequest } from '../api.js'+import { Check, Field, Switch, useAction } from '../ui.jsx'++// Every type of the design; the ones not built yet are shown, but can't be picked.+const TYPES = [+ ['http', 'HTTP(s)', 'Status code of a URL'], ['keyword', 'Keyword', 'Text on the page'], ['json', 'JSON query', 'A value in a JSON reply'],+ ['tcp', 'TCP port', 'Port accepts connections'], ['ping', 'Ping', 'Host answers ICMP'], ['dns', 'DNS', 'Record resolves as expected'],+ ['docker', 'Docker container', 'Running and healthy'], ['tls', 'TLS certificate', 'Valid and not expiring'], ['push', 'Push', 'A job pings Infradeck'],+]+const READY = new Set(['http', 'keyword', 'tcp'])++const initial = (check, servers) => {+ const options = check?.options || {}+ const first = servers.find((server) => server.can_run_checks) || servers[0]+ return {+ type: check?.type || 'http', name: check?.name || '', tags: (check?.tags || []).join(', '), target: check?.target || '',+ keyword: options.keyword || '', case_sensitive: Boolean(options.case_sensitive),+ server_ids: check ? check.servers.map((server) => server.id) : first ? [first.id] : [], rule: check?.rule || 'all',+ interval_seconds: String(check?.interval_seconds ?? 60), retries: String(check?.retries ?? 2), retry_interval_seconds: String(check?.retry_interval_seconds ?? 20), timeout_seconds: String(check?.timeout_seconds ?? 48),+ accepted_codes: (options.accepted_codes || ['200-299']).join(', '), follow_redirects: options.follow_redirects ?? true, ignore_tls: Boolean(options.ignore_tls), upside_down: Boolean(options.upside_down),+ severity: check?.severity || 'CRITICAL',+ }+}++// What the backend would refuse, said next to the field before saving.+function problems(form, web) {+ const found = {}+ const target = form.target.trim()+ if (web && target && !/^https?:\/\/[^\s/:?#]+/i.test(target)) found.target = /^[\w.-]+(:\d+)?(\/|$)/.test(target) ? `Add http:// or https:// in front, like http://${target}` : 'The URL must start with http:// or https://.'+ if (!web && target && !/^([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\]):\d{1,5}$/.test(target)) found.target = /^[A-Za-z0-9.-]+$/.test(target) ? `Add the port, like ${target}:22` : 'Enter host:port, like 10.0.0.12:3306.'+ if (form.type === 'keyword' && !form.keyword) found.keyword = 'Enter the text to look for.'+ const whole = (value, low, high) => /^\d+$/.test(String(value).trim()) && Number(value) >= low && Number(value) <= high+ if (!whole(form.interval_seconds, 20, 86400)) found.interval_seconds = 'From 20 s to 24 h.'+ if (!whole(form.retries, 0, 10)) found.retries = 'From 0 to 10.'+ if (!whole(form.retry_interval_seconds, 20, 86400)) found.retry_interval_seconds = 'At least 20 s.'+ if (!whole(form.timeout_seconds, 1, 48)) found.timeout_seconds = 'From 1 to 48 s.'+ else if (whole(form.interval_seconds, 20, 86400) && Number(form.timeout_seconds) >= Number(form.interval_seconds)) found.timeout_seconds = 'Shorter than the interval.'+ if (web && !form.accepted_codes.split(',').map((code) => code.trim()).filter(Boolean).every((code) => /^[1-5]\d\d(-[1-5]\d\d)?$/.test(code))) found.accepted_codes = 'Codes or ranges like 200-299, 301.'+ if (!form.server_ids.length) found.server_ids = 'Pick at least one server.'+ return found+}++const duration = (seconds) => (seconds < 90 ? `${Math.round(seconds)} seconds` : seconds < 5400 ? `${Math.round(seconds / 60)} ${Math.round(seconds / 60) === 1 ? 'minute' : 'minutes'}` : `${Math.round(seconds / 3600)} hours`)++// "Marked down after 3 failed checks in a row, so about 1 minute after it breaks."+function TimingSentence({ form }) {+ const interval = Number(form.interval_seconds), retries = Number(form.retries), retry = Number(form.retry_interval_seconds)+ if (![interval, retries, retry].every(Number.isFinite) || interval <= 0) return null+ const failures = retries + 1+ // The first failure comes on average half an interval after it breaks; the retries follow at the retry interval.+ const after = interval / 2 + retries * retry+ return (+ <p className="m-0 rounded-md border border-line bg-ink px-3.5 py-2.5 text-xs leading-5 text-soft">+ Marked <b className="font-semibold text-paper">down</b> after <b className="font-semibold text-paper">{failures} failed {failures === 1 ? 'check' : 'checks in a row'}</b>, so about <b className="font-semibold text-paper">{duration(after)}</b> after it breaks. Up again on the first good check.+ </p>+ )+}++function Heading({ children, detail }) {+ return <h3 className="m-0 border-t border-line pt-5 text-[11px] font-semibold uppercase tracking-[0.1em] text-muted first:border-t-0 first:pt-0">{children}{detail && <span className="ml-2 font-normal normal-case tracking-normal text-dim">{detail}</span>}</h3>+}++function Toggle({ checked, onChange, title, detail }) {+ return (+ <label className="flex cursor-pointer items-start gap-3">+ <span className="pt-0.5"><Switch checked={checked} onChange={onChange} label={title} /></span>+ <span><span className="block text-[13px] text-paper">{title}</span><span className="mt-0.5 block text-xs text-muted">{detail}</span></span>+ </label>+ )+}++export function CheckForm({ check, servers, onSaved, onCancel }) {+ const [form, setForm] = useState(() => initial(check, servers))+ const [state, run] = useAction()+ const [tried, setTried] = useState(false)+ const set = (changes) => setForm((current) => {+ const next = { ...current, ...changes }+ // A shorter interval takes the timeout down with it, so the default 48 s doesn't block a 30 s interval.+ if ('interval_seconds' in changes && /^\d+$/.test(changes.interval_seconds) && Number(next.timeout_seconds) >= Number(changes.interval_seconds)) {+ next.timeout_seconds = String(Math.max(1, Math.min(48, Math.floor(Number(changes.interval_seconds) * 0.8))))+ }+ return next+ })+ const web = form.type !== 'tcp'+ const issues = problems(form, web)+ const shown = (key) => (tried || (key === 'target' ? form.target.trim() : true)) && issues[key]+ const hint = (key) => shown(key) && <span className="mt-1.5 block text-[11px] leading-4 text-warn">{issues[key]}</span>+ const toggleServer = (id, on) => set({ server_ids: on ? [...form.server_ids, id] : form.server_ids.filter((item) => item !== id) })++ const save = (event) => {+ event.preventDefault()+ setTried(true)+ if (Object.keys(issues).length) return+ const whole = (value) => (/^\d+$/.test(String(value).trim()) ? Number(value) : value)+ const body = {+ type: form.type, name: form.name.trim(), target: form.target.trim(), tags: form.tags.split(',').map((tag) => tag.trim()).filter(Boolean),+ server_ids: form.server_ids, rule: form.rule, severity: form.severity, upside_down: form.upside_down,+ interval_seconds: whole(form.interval_seconds), retries: whole(form.retries), retry_interval_seconds: whole(form.retry_interval_seconds), timeout_seconds: whole(form.timeout_seconds),+ ...(web ? { accepted_codes: form.accepted_codes.split(',').map((code) => code.trim()).filter(Boolean), follow_redirects: form.follow_redirects, ignore_tls: form.ignore_tls } : {}),+ ...(form.type === 'keyword' ? { keyword: form.keyword, case_sensitive: form.case_sensitive } : {}),+ }+ run(async () => {+ const result = await apiRequest(check ? `/availability/checks/${check.id}` : '/availability/checks', { method: check ? 'PATCH' : 'POST', body: JSON.stringify(body) })+ onSaved(result)+ })+ }++ const number = (key, label, unit) => (+ <Field label={label}>+ <span className="relative block"><input inputMode="numeric" value={form[key]} onChange={(event) => set({ [key]: event.target.value })} aria-invalid={Boolean(shown(key))} className={`field h-9 pr-7 text-[13px] tabular-nums ${shown(key) ? '!border-warn' : ''}`} />+ {unit && <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[11px] text-muted">{unit}</span>}</span>+ {hint(key)}+ </Field>+ )++ return (+ <form onSubmit={save} className="space-y-5">+ <Heading>Type</Heading>+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3" role="radiogroup" aria-label="Check type">+ {TYPES.map(([id, label, detail]) => {+ const ready = READY.has(id)+ const chosen = form.type === id+ return (+ <button key={id} type="button" role="radio" aria-checked={chosen} disabled={!ready || Boolean(check)} title={ready ? undefined : 'Coming in a later step'} onClick={() => set({ type: id })}+ className={`rounded-md border px-3 py-2.5 text-left transition-colors ${chosen ? 'border-paper bg-raised' : 'border-edge bg-ink hover:bg-raised'} disabled:cursor-not-allowed ${ready ? '' : 'opacity-40'}`}>+ <span className="block text-[13px] font-medium text-paper">{label}</span><span className="mt-0.5 block text-[11px] text-muted">{ready ? detail : 'later'}</span>+ </button>+ )+ })}+ </div>++ <Heading>Target</Heading>+ <div className="grid gap-4 sm:grid-cols-2">+ <Field label="Name"><input value={form.name} onChange={(event) => set({ name: event.target.value })} placeholder="Home Assistant" maxLength={120} className="field h-9 text-[13px]" required /></Field>+ <Field label="Tags" hint="Optional, comma-separated. The list is grouped by the first one."><input value={form.tags} onChange={(event) => set({ tags: event.target.value })} placeholder="Home services" className="field h-9 text-[13px]" /></Field>+ </div>+ {web ? <Field label="URL"><input value={form.target} onChange={(event) => set({ target: event.target.value })} placeholder="https://ha.home.lan/api/" aria-invalid={Boolean(shown('target'))} className={`field mono h-9 text-[13px] ${shown('target') ? '!border-warn' : ''}`} required />{hint('target')}</Field>+ : <Field label="Host and port" hint={shown('target') ? null : "Seen from the servers that run the check: localhost is the collector's own container."}><input value={form.target} onChange={(event) => set({ target: event.target.value })} placeholder="10.0.0.12:3306" aria-invalid={Boolean(shown('target'))} className={`field mono h-9 text-[13px] ${shown('target') ? '!border-warn' : ''}`} required />{hint('target')}</Field>}+ {form.type === 'keyword' && <div className="grid items-end gap-4 sm:grid-cols-[minmax(0,1fr)_auto]">+ <Field label="Text to look for" hint="In the first 1 MiB of the page. The page itself is never stored or sent anywhere."><input value={form.keyword} onChange={(event) => set({ keyword: event.target.value })} maxLength={200} className="field h-9 text-[13px]" required /></Field>+ <label className="flex items-center gap-2 pb-6 text-xs text-soft"><Check checked={form.case_sensitive} onChange={(value) => set({ case_sensitive: value })} label="Case sensitive" />Case sensitive</label>+ </div>}++ <Heading detail="any server with a collector">Check from</Heading>+ <div className="flex flex-wrap gap-2">+ {servers.map((server) => {+ const on = form.server_ids.includes(server.id)+ return (+ <label key={server.id} className={`flex h-9 cursor-pointer items-center gap-2.5 rounded-md border px-3 text-[13px] ${on ? 'border-paper bg-raised text-paper' : 'border-edge text-soft'}`} title={server.can_run_checks ? undefined : 'Its collector is older than 0.10.0 or hasn’t reported yet, so it can’t run checks until it is updated.'}>+ <Check checked={on} onChange={(value) => toggleServer(server.id, value)} label={server.hostname} />{server.hostname}{!server.can_run_checks && <span className="text-[11px] text-warn">update collector</span>}+ </label>+ )+ })}+ </div>+ {hint('server_ids')}+ {form.server_ids.length > 1 && <span className="seg" role="group" aria-label="When is it down">+ <button type="button" aria-pressed={form.rule === 'all'} onClick={() => set({ rule: 'all' })}>Down when all fail</button>+ <button type="button" aria-pressed={form.rule === 'any'} onClick={() => set({ rule: 'any' })}>Down when any fails</button>+ </span>}++ <Heading>Timing</Heading>+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ {number('interval_seconds', 'Every', 's')}{number('retries', 'Retries')}{number('retry_interval_seconds', 'Retry every', 's')}{number('timeout_seconds', 'Timeout', 's')}+ </div>+ <TimingSentence form={form} />++ <Heading>What counts as up</Heading>+ {web && <Field label="Accepted status codes" hint="Comma-separated codes or ranges, like 200-299, 301."><input value={form.accepted_codes} onChange={(event) => set({ accepted_codes: event.target.value })} className={`field mono h-9 text-[13px] ${shown('accepted_codes') ? '!border-warn' : ''}`} />{hint('accepted_codes')}</Field>}+ <div className="grid gap-4 sm:grid-cols-2">+ {web && <Toggle checked={form.follow_redirects} onChange={(value) => set({ follow_redirects: value })} title="Follow redirects" detail="up to 10, only to http and https" />}+ {web && <Toggle checked={form.ignore_tls} onChange={(value) => set({ ignore_tls: value })} title="Ignore TLS errors" detail="for self-signed certificates" />}+ <Toggle checked={form.upside_down} onChange={(value) => set({ upside_down: value })} title="Upside down" detail="up means the service is unreachable" />+ </div>+ {web && <p className="m-0 text-xs text-muted">Request: GET · no headers · no body · no auth</p>}++ <Heading detail="channels from Account › Notifications">Notify</Heading>+ <p className="m-0 text-xs leading-5 text-soft">A check that goes down opens an incident, which goes to the same channels as every other incident (<Link to="/account#notifications" className="link">your notification channels</Link>). New checks stay quiet for their first 10 minutes.</p>+ <Field label="Severity">+ <span className="seg" role="group" aria-label="Severity">+ <button type="button" aria-pressed={form.severity === 'CRITICAL'} onClick={() => set({ severity: 'CRITICAL' })}>Critical</button>+ <button type="button" aria-pressed={form.severity === 'WARNING'} onClick={() => set({ severity: 'WARNING' })}>Warning</button>+ </span>+ </Field>++ <div className="sticky -bottom-5 -mx-6 -mb-5 flex items-center justify-end gap-2 border-t border-line bg-bg px-6 py-3">+ <p role="alert" className="m-0 mr-auto min-w-0 text-xs leading-4 text-warn">{state.error || (tried && Object.keys(issues).length ? `Fix ${Object.keys(issues).length === 1 ? 'the field' : `${Object.keys(issues).length} fields`} marked above.` : '')}</p>+ <button type="button" className="btn" onClick={onCancel}>Cancel</button>+ <button type="submit" className="btn btn-primary" disabled={state.busy}>{state.busy ? 'Saving…' : 'Save check'}</button>+ </div>+ </form>+ )+}diff --git a/src/frontend/src/icons.jsx b/src/frontend/src/icons.jsxindex a75f84b..f6bb222 100644--- a/src/frontend/src/icons.jsx+++ b/src/frontend/src/icons.jsx@@ -4,6 +4,7 @@ const base = { width: 16, height: 16, viewBox: '0 0 16 16', fill: 'none', strokeconst paths = {overview: <><rect x="2.5" y="2.5" width="11" height="4" rx="0.8" /><rect x="2.5" y="9.5" width="11" height="4" rx="0.8" /><path d="M5 4.5h.01M5 11.5h.01" /></>,statistics: <><path d="M2.5 13.5h11" /><path d="M3 10l3-3.5 2.5 2L13 4" /></>,+ availability: <path d="M1.5 8.5h3l1.5-4 3 8 1.5-4h4" />,agent: <><path d="M2.5 3.5h11v7.5H7l-3 2.5V11H2.5z" /><path d="M5.5 6.5h5M5.5 8.5h3" /></>,account: <><circle cx="8" cy="5.5" r="2.5" /><path d="M3 13.5c.6-2.3 2.5-3.5 5-3.5s4.4 1.2 5 3.5" /></>,admin: <><path d="M2.5 5h7M12.5 5h1M2.5 11h1M6.5 11h7" /><circle cx="11" cy="5" r="1.5" /><circle cx="5" cy="11" r="1.5" /></>,diff --git a/src/frontend/src/more/MorePage.jsx b/src/frontend/src/more/MorePage.jsxindex d122318..b1c6e05 100644--- a/src/frontend/src/more/MorePage.jsx+++ b/src/frontend/src/more/MorePage.jsx@@ -69,6 +69,10 @@ export default function MorePage({ user, onLogout }) {<Icon name="chevron" size={14} className="shrink-0 text-muted" /></Link>}+ <Group title="Monitoring">+ <Item to="/availability" icon="availability" title="Availability" value={overview?.checks_down ? `${overview.checks_down} down` : null} tone="warn" />+ </Group>+{servers.length > 0 && <Group title="Fleet">{servers.map((server) => <Item key={server.id} to={serverLink(server.id)} dot={STATE_DOT[serverState(server)]} title={server.hostname} detail={detail(server)} />)}</Group>}diff --git a/src/frontend/src/shell.jsx b/src/frontend/src/shell.jsxindex 06b4d5c..06ce053 100644--- a/src/frontend/src/shell.jsx+++ b/src/frontend/src/shell.jsx@@ -17,13 +17,14 @@ const staleAfter = () => Math.max(30, liveRefreshSeconds(LIVE_REFRESH_SECONDS) *const primaryNav = [{ label: 'Overview', to: '/', icon: 'overview', keys: 'O' },{ label: 'Statistics', to: '/statistics', icon: 'statistics', keys: 'S' },+ { label: 'Availability', to: '/availability', icon: 'availability', keys: 'U' },{ label: 'Agent', to: '/agent', icon: 'agent', keys: 'A' },]const secondaryNav = [{ label: 'Account', to: '/account', icon: 'account' },{ label: 'Admin', to: '/admin', icon: 'admin', adminOnly: true },]-const pageTitles = { '/': 'Overview', '/statistics': 'Statistics', '/agent': 'Agent', '/account': 'Account', '/admin': 'Admin' }+const pageTitles = { '/': 'Overview', '/statistics': 'Statistics', '/availability': 'Availability', '/agent': 'Agent', '/account': 'Account', '/admin': 'Admin' }export const serverLink = (serverId, tab) => `/?server=${serverId}${tab && tab !== 'overview' ? `&tab=${tab}` : ''}`@@ -64,7 +65,7 @@ function NavItem({ item, badge }) {{isActive && <span aria-hidden="true" className="absolute -left-3.5 top-0 h-full w-[3px] rounded-r-sm bg-signal" />}<Icon name={item.icon} className={isActive ? 'text-paper' : 'text-muted'} /><span className="flex-1">{item.label}</span>- {badge ? <span className="flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-signal px-1 text-[11px] font-semibold text-bg" aria-label={`${badge} open incidents`}>{badge}</span>+ {badge ? <span className="flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-signal px-1 text-[11px] font-semibold text-bg" aria-label={item.to === '/availability' ? `${badge} checks down` : `${badge} open incidents`}>{badge}</span>: item.keys && <span aria-hidden="true" className="mono text-[10px] tracking-[0.25em] text-dim">G {item.keys}</span>}</>}</NavLink>@@ -105,7 +106,7 @@ function Sidebar({ user, onLogout, overview, error }) {<div className="mt-2 truncate px-2 text-[11px] text-muted">{overview?.instance_name || instanceName(user)}{overview?.version ? ` · v${overview.version}` : ''}</div><nav aria-label="Main" className="mt-6 space-y-0.5">- {primaryNav.map((item) => <NavItem key={item.to} item={item} badge={item.to === '/agent' ? open : 0} />)}+ {primaryNav.map((item) => <NavItem key={item.to} item={item} badge={item.to === '/agent' ? open : item.to === '/availability' ? overview?.checks_down || 0 : 0} />)}</nav><div className="mt-6 flex items-center justify-between px-2 text-[11px] text-muted"><span>Fleet</span><span>{servers.length}</span></div>@@ -156,7 +157,7 @@ function Rail({ user, onLogout, overview }) {{({ isActive }) => <>{isActive && <span aria-hidden="true" className="absolute -left-3 top-1 h-8 w-[3px] rounded-r-sm bg-signal" />}<Icon name={item.icon} size={17} />- {item.to === '/agent' && open > 0 && <span className="absolute right-0.5 top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-signal px-0.5 text-[9px] font-semibold text-bg">{open}</span>}+ {(() => { const badge = item.to === '/agent' ? open : item.to === '/availability' ? overview?.checks_down || 0 : 0; return badge > 0 && <span className="absolute right-0.5 top-0.5 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-signal px-0.5 text-[9px] font-semibold text-bg">{badge}</span> })()}</>}</NavLink>))}@@ -185,7 +186,7 @@ function LiveStatus({ overview, loadedAt, error }) {function paletteItems(overview, isAdmin) {const items = [- { kind: 'Page', label: 'Overview', to: '/' }, { kind: 'Page', label: 'Statistics', to: '/statistics' }, { kind: 'Page', label: 'Agent', to: '/agent' }, { kind: 'Page', label: 'Account', to: '/account' },+ { kind: 'Page', label: 'Overview', to: '/' }, { kind: 'Page', label: 'Statistics', to: '/statistics' }, { kind: 'Page', label: 'Availability', to: '/availability' }, { kind: 'Page', label: 'Agent', to: '/agent' }, { kind: 'Page', label: 'Account', to: '/account' },...(isAdmin ? [{ kind: 'Page', label: 'Admin', to: '/admin' }] : []),]for (const server of overview?.servers || []) {@@ -308,10 +309,10 @@ export function PhoneHeader({ title, back, subtitle, action, live = !back, mark)}-function MobileTabBar({ open }) {+function MobileTabBar({ open, checksDown = 0 }) {const location = useLocation()- // More holds Account and Admin, so it stays lit on their pages.- const inMore = ['/more', '/account', '/admin'].includes(location.pathname)+ // More holds Availability, Account and Admin, so it stays lit on their pages.+ const inMore = ['/more', '/account', '/admin', '/availability'].includes(location.pathname)const tab = (active, icon, label, badge) => <><span className="relative"><Icon name={icon} size={20} />{badge > 0 && <span className="absolute -right-2.5 -top-1.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-signal px-1 text-[10px] font-semibold text-bg">{badge}</span>}</span><span className={active ? 'text-paper' : ''}>{label}</span>@@ -319,12 +320,12 @@ function MobileTabBar({ open }) {return (<nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-bg pb-[env(safe-area-inset-bottom)] md:hidden"><div className="mx-auto grid max-w-md grid-cols-4">- {primaryNav.map((item) => (+ {primaryNav.filter((item) => item.to !== '/availability').map((item) => (<NavLink key={item.to} to={item.to} end={item.to === '/'} className={({ isActive }) => `flex h-[60px] flex-col items-center justify-center gap-1 text-[11px] font-medium ${isActive ? 'text-paper' : 'text-muted'}`}>{({ isActive }) => tab(isActive, item.icon, item.label, item.to === '/agent' ? open : 0)}</NavLink>))}- <Link to="/more" aria-current={inMore ? 'page' : undefined} className={`flex h-[60px] flex-col items-center justify-center gap-1 text-[11px] font-medium ${inMore ? 'text-paper' : 'text-muted'}`}>{tab(inMore, 'more', 'More', 0)}</Link>+ <Link to="/more" aria-current={inMore ? 'page' : undefined} className={`flex h-[60px] flex-col items-center justify-center gap-1 text-[11px] font-medium ${inMore ? 'text-paper' : 'text-muted'}`}>{tab(inMore, 'more', 'More', checksDown)}</Link></div></nav>)@@ -342,7 +343,7 @@ export function AppShell({ children, user, onLogout, fitViewport = false, crumbsconst trail = crumbs || [{ label: pageTitles[location.pathname] || 'Infradeck' }]const open = (overview?.alerts_by_severity?.CRITICAL || 0) + (overview?.alerts_by_severity?.WARNING || 0)- // ⌘K / Ctrl+K opens the palette; G then O, S or A jumps between the main pages.+ // ⌘K / Ctrl+K opens the palette; G then O, S, U or A jumps between the main pages.useEffect(() => {let armed = 0const onKeyDown = (event) => {@@ -350,7 +351,7 @@ export function AppShell({ children, user, onLogout, fitViewport = false, crumbsif (event.metaKey || event.ctrlKey || event.altKey || isTyping(event.target)) returnconst key = event.key.toLowerCase()if (key === 'g') { armed = Date.now(); return }- const target = { o: '/', s: '/statistics', a: '/agent' }[key]+ const target = { o: '/', s: '/statistics', u: '/availability', a: '/agent' }[key]if (target && Date.now() - armed < 1200) { event.preventDefault(); navigate(target) }armed = 0}@@ -372,7 +373,7 @@ export function AppShell({ children, user, onLogout, fitViewport = false, crumbs{!phoneHeader && <PhoneHeader title={last?.label || 'Infradeck'} back={parent ? { label: parent.label, to: parent.to } : null} />}<main className={`${fitViewport ? 'xl:min-h-0 xl:flex-1' : ''} min-w-0 ${bare ? '' : 'px-4 pt-4 md:px-7 md:pt-6'} ${phoneTabs ? 'pb-[calc(5.5rem+env(safe-area-inset-bottom))]' : ''} md:pb-7`}>{children}</main></div>- {phoneTabs && <MobileTabBar open={open} />}+ {phoneTabs && <MobileTabBar open={open} checksDown={overview?.checks_down || 0} />}{paletteOpen && <CommandPalette overview={overview} isAdmin={user?.role === 'admin'} onClose={() => setPaletteOpen(false)} />}</div></ShellContext.Provider>diff --git a/tests/collectors/test_collector_checks.py b/tests/collectors/test_collector_checks.pynew file mode 100644index 0000000..39ed525--- /dev/null+++ b/tests/collectors/test_collector_checks.py@@ -0,0 +1,153 @@+"""The collector runs availability checks: only well-formed checks from the dashboard, against a real local HTTP+server and TCP port here, and the results it reports never contain a response body."""+import http.server+import socket+import threading+import time+import urllib.error++import pytest++from src.collector import collector++GOOD = {"id": 1, "type": "http", "target": "http://127.0.0.1:1/", "interval": 60, "retry_interval": 20, "timeout": 5, "accepted_codes": ["200-299"], "follow_redirects": True, "ignore_tls": False, "method": "GET"}+++class _Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/redirect":+ self.send_response(302)+ self.send_header("Location", "/ok")+ self.end_headers()+ return+ if self.path == "/away":+ self.send_response(302)+ self.send_header("Location", "file:///etc/passwd")+ self.end_headers()+ return+ status = 503 if self.path == "/broken" else 200+ body = b"<html>Welcome to Gitea, secret=hunter2</html>"+ self.send_response(status)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ do_HEAD = do_GET++ def log_message(self, *args):+ pass++[email protected](scope="module")+def site():+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ yield f"http://127.0.0.1:{server.server_address[1]}"+ server.shutdown()+++def check(**changes):+ return collector.validate_check({**GOOD, **changes})++[email protected]("changes", [+ {"type": "ping"}, {"id": 0}, {"id": True}, {"interval": 5}, {"retry_interval": 10**6}, {"timeout": 49}, {"target": "file:///etc/passwd"},+ {"target": "ftp://example.com/"}, {"target": "http://exa mple.com/"}, {"target": "http://a\x00b/"}, {"accepted_codes": []}, {"accepted_codes": ["2xx"]},+ {"type": "keyword"}, {"type": "keyword", "keyword": ""}, {"type": "tcp", "target": "host"}, {"type": "tcp", "target": "h;id:22"}, {"type": "tcp", "target": "h:0"},+])+def test_a_check_that_isnt_well_formed_is_not_run(changes):+ assert check(**changes) is None+++def test_an_accepted_status_is_up_with_a_response_time(site):+ result = collector.run_http(check(target=f"{site}/ok"))++ assert result["ok"] is True and result["code"] == 200 and result["response_ms"] >= 0 and result["detail"] is None+++def test_a_status_outside_the_accepted_codes_is_down_with_the_code(site):+ result = collector.run_http(check(target=f"{site}/broken"))++ assert (result["ok"], result["code"], result["detail"]) == (False, 503, "HTTP 503")+ assert collector.run_http(check(target=f"{site}/broken", accepted_codes=["200-299", "503"]))["ok"] is True+++def test_redirects_are_followed_only_when_asked_and_only_to_http(site):+ assert collector.run_http(check(target=f"{site}/redirect"))["code"] == 200+ assert collector.run_http(check(target=f"{site}/redirect", follow_redirects=False))["detail"] == "HTTP 302"+ assert collector.run_http(check(target=f"{site}/away"))["detail"] == "HTTP 302"+++def test_a_keyword_check_looks_in_the_page_but_reports_none_of_it(site):+ found = collector.run_check(check(type="keyword", target=f"{site}/ok", keyword="welcome TO gitea"))+ exact = collector.run_check(check(type="keyword", target=f"{site}/ok", keyword="welcome TO gitea", case_sensitive=True))++ assert found["ok"] is True+ assert (exact["ok"], exact["detail"]) == (False, "Keyword not found")+ assert "hunter2" not in str(found) + str(exact)+++def test_head_is_used_only_for_plain_http_checks():+ assert check(method="HEAD")["method"] == "HEAD"+ assert check(type="keyword", keyword="x", method="HEAD")["method"] == "GET"+++def test_an_unreachable_service_is_down_with_a_short_reason():+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ port = sock.getsockname()[1]+ assert collector.run_http(check(target=f"http://127.0.0.1:{port}/"))["detail"] == "Connection refused"+ assert collector.run_tcp(check(type="tcp", target=f"127.0.0.1:{port}"))["detail"] == "Connection refused"+++def test_an_open_tcp_port_is_up(site):+ port = site.rsplit(":", 1)[1]++ result = collector.run_tcp(check(type="tcp", target=f"127.0.0.1:{port}"))++ assert result["ok"] is True and result["response_ms"] >= 0+++def test_the_runner_runs_due_checks_and_reports_them(monkeypatch, site):+ sent = []++ def fake_send(api_url, server_id, token, results):+ sent.append(list(results))+ return {"checks": [{**GOOD, "target": f"{site}/ok"}], "report_every": 5}++ monkeypatch.setattr(collector, "send_check_results", fake_send)+ runner = collector.CheckRunner("http://dashboard/api", (3, "token"))++ assert runner.report() is True # the first report has nothing in it and fetches the checks+ runner.run_due()+ deadline = time.monotonic() + 5+ while not runner.pending and time.monotonic() < deadline:+ time.sleep(0.05)+ runner.report()++ assert sent[0] == [] and len(sent[1]) == 1+ assert sent[1][0]["check_id"] == 1 and sent[1][0]["ok"] is True and set(sent[1][0]) <= {"check_id", "time", "ok", "response_ms", "code", "detail", "cert_days"}+ assert runner.next_run[1] > time.monotonic() + 50 # next run after the interval+++def test_results_that_couldnt_be_sent_wait_for_the_next_report(monkeypatch):+ runner = collector.CheckRunner("http://dashboard/api", (3, "token"))+ runner.pending.extend([{"check_id": 1, "ok": True, "time": "t"}] * 3)++ def failing(*args):+ raise urllib.error.URLError("down")++ monkeypatch.setattr(collector, "send_check_results", failing)++ assert runner.report() is False+ assert len(runner.pending) == 3+++def test_checks_from_the_dashboard_are_validated_and_capped():+ runner = collector.CheckRunner("http://dashboard/api", (3, "token"))++ runner.set_checks([{**GOOD, "id": index} for index in range(1, 80)] + [{**GOOD, "id": 999, "target": "file:///etc/shadow"}, "junk"])++ assert len(runner.checks) == collector.MAX_CHECKS and 999 not in runner.checks+ runner.set_checks(None)+ assert runner.checks == {} and runner.next_run == {}diff --git a/tests/monitoring/test_availability.py b/tests/monitoring/test_availability.pynew file mode 100644index 0000000..a065bb0--- /dev/null+++ b/tests/monitoring/test_availability.py@@ -0,0 +1,399 @@+"""Availability checks: what a check may be, how results from the collectors are taken in and combined, when an+incident opens and resolves, and the uptime and heartbeat the page shows."""+import json+import os+from datetime import datetime, timedelta, timezone++os.environ.setdefault("DATABASE_URL", "sqlite://")+os.environ.setdefault("REDIS_URL", "redis://localhost:6379/0")++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from src.backend import availability, incidents, main+from src.backend.models import AppSetting, Base, Check, CheckResult, CheckRollup, IncidentAlert, Server, User+from tests.fakes import FakeRedis++TOKENS = {1: "token-one", 2: "token-two"}+NEW_CHECK = {"type": "http", "name": "Gitea", "target": "https://git.example.com/", "server_ids": [1, 2], "interval_seconds": 60, "retries": 2, "retry_interval_seconds": 20, "timeout_seconds": 10}+++def app(monkeypatch):+ engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)+ Base.metadata.create_all(engine)+ Session = sessionmaker(bind=engine)+ with Session() as seed:+ seed.add(User(id=1, name="Owner", email="[email protected]", password_hash="x", role="admin", is_active=True))+ seed.add(User(id=2, name="Member", email="[email protected]", password_hash="x", role="member", is_active=True))+ for server_id, name in ((1, "alpha"), (2, "bravo")):+ seed.add(Server(id=server_id, owner_id=1, hostname=name, check_interval_seconds=60, collector_token_hash=main._hash_secret(TOKENS[server_id]),+ machine_id=f"machine-{server_id}", system_info=json.dumps({"collector_version": "0.10.0" if server_id == 1 else "0.9.2"})))+ seed.commit()++ def get_db():+ session = Session()+ try:+ yield session+ finally:+ session.close()++ main.app.dependency_overrides[main.get_db] = get_db+ monkeypatch.setattr(main, "redis_client", FakeRedis())+ monkeypatch.setattr(main, "_enforce_report_spacing", lambda server: None)+ user = {"id": 1, "role": "admin"}+ monkeypatch.setattr(main, "_current_user", lambda session_id, db: user)+ client = TestClient(main.app, raise_server_exceptions=False)+ client.Session = Session+ client.user = user+ yield client+ main.app.dependency_overrides.clear()+++def create(client, **changes):+ response = client.post("/availability/checks", json={**NEW_CHECK, **changes})+ assert response.status_code == 200, response.text+ return response.json()+++def age(client, check_id, minutes=30):+ """Make a check older than the quiet period for new checks."""+ with client.Session() as db:+ db.get(Check, check_id).created_at = datetime.now(timezone.utc) - timedelta(minutes=minutes)+ db.commit()+++def report(client, server_id, results, token=None):+ return client.post("/monitoring/metrics/checks", json={"server_id": server_id, "results": results}, headers={"Authorization": f"Bearer {token or TOKENS[server_id]}"})+++def run(check_id, ok, seconds_ago=0, **extra):+ return {"check_id": check_id, "time": (datetime.now(timezone.utc) - timedelta(seconds=seconds_ago)).isoformat(), "ok": ok, **extra}+++def runs(check_id, oks, step=20, ago=0):+ """Several runs, oldest first, ``step`` seconds apart and ending ``ago`` seconds ago."""+ return [run(check_id, ok, ago + (len(oks) - 1 - index) * step) for index, ok in enumerate(oks)]+++def incident(client, check_id):+ with client.Session() as db:+ return db.query(IncidentAlert).filter(IncidentAlert.rule_key == f"check:{check_id}:down").order_by(IncidentAlert.id.desc()).first()+++def check_row(client, check_id):+ with client.Session() as db:+ return db.get(Check, check_id)+++# --- what a check may be ----------------------------------------------------------------------------+[email protected]("changes", [+ {"type": "ping"}, {"name": ""}, {"name": "x" * 121}, {"target": "ftp://example.com/"}, {"target": "file:///etc/passwd"}, {"target": "https://"},+ {"target": "https://exa mple.com/"}, {"server_ids": []}, {"server_ids": [99]}, {"server_ids": [True]}, {"interval_seconds": 5}, {"timeout_seconds": 60},+ {"retries": 11}, {"retries": "2"}, {"accepted_codes": ["2xx"]}, {"accepted_codes": ["200-299"] * 11},+ {"rule": "most"}, {"severity": "INFO"}, {"tags": ["a,b"]}, {"type": "keyword"}, {"type": "keyword", "keyword": "x" * 201},+ {"type": "tcp", "target": "db.example.com"}, {"type": "tcp", "target": "db.example.com:70000"}, {"type": "tcp", "target": "db;rm -rf /:22"},+])+def test_a_check_that_isnt_well_formed_is_refused_with_a_reason(app, changes):+ response = app.post("/availability/checks", json={**NEW_CHECK, **changes})++ assert response.status_code == 400+ assert response.json()["detail"]+++def test_a_short_interval_brings_the_timeout_down_with_it(app):+ check = create(app, interval_seconds=30, timeout_seconds=48)++ assert (check["interval_seconds"], check["timeout_seconds"]) == (30, 24)+++def test_only_admins_add_change_pause_or_delete_checks(app):+ check = create(app)+ app.user.update(id=2, role="member")++ assert app.post("/availability/checks", json=NEW_CHECK).status_code == 403+ assert app.patch(f"/availability/checks/{check['id']}", json=NEW_CHECK).status_code == 403+ assert app.post(f"/availability/checks/{check['id']}/pause", json={"paused": True}).status_code == 403+ assert app.delete(f"/availability/checks/{check['id']}").status_code == 403+ page = app.get("/availability").json()+ assert page["can_edit"] is False and [item["name"] for item in page["checks"]] == ["Gitea"]+++def test_a_collector_gets_only_the_checks_of_its_own_server(app):+ create(app, name="Both")+ create(app, name="Only bravo", server_ids=[2], type="tcp", target="10.0.0.12:3306")+ paused = create(app, name="Paused", server_ids=[1])+ app.post(f"/availability/checks/{paused['id']}/pause", json={"paused": True})++ alpha = report(app, 1, []).json()+ bravo = report(app, 2, []).json()++ assert [check["target"] for check in alpha["checks"]] == ["https://git.example.com/"]+ assert [check["target"] for check in bravo["checks"]] == ["https://git.example.com/", "10.0.0.12:3306"]+ assert set(alpha["checks"][0]) == {"id", "type", "target", "interval", "retry_interval", "timeout", "accepted_codes", "follow_redirects", "ignore_tls", "method"}+++def test_check_results_need_the_servers_own_collector_token(app):+ assert report(app, 1, [], token="token-two").status_code == 401+ assert report(app, 1, [], token="nope").status_code == 401+ assert app.post("/monitoring/metrics/checks", json={"server_id": 1, "results": []}).status_code == 401+ assert report(app, 1, [{}] * 501).status_code == 422+++def test_results_a_collector_has_no_business_reporting_are_dropped(app):+ mine = create(app, server_ids=[1])+ theirs = create(app, name="Other", server_ids=[2])++ response = report(app, 1, [+ run(theirs["id"], False), # not this server's check+ run(mine["id"], "yes"), # ok isn't a boolean+ run(mine["id"], True, seconds_ago=2 * 3600), # too old+ run(mine["id"], True, seconds_ago=-600), # from the future+ {"check_id": mine["id"], "time": "yesterday", "ok": True},+ "junk",+ run(mine["id"], True, response_ms=10**9, code=99, detail="a\x00b" + "x" * 500, cert_days="soon"),+ ])++ assert response.status_code == 200+ with app.Session() as db:+ stored = db.query(CheckResult).all()+ assert len(stored) == 1+ assert (stored[0].check_id, stored[0].response_ms, stored[0].code, stored[0].cert_days, len(stored[0].detail)) == (mine["id"], None, None, None, 200)+ assert "\x00" not in stored[0].detail+++# --- up and down --------------------------------------------------------------------------------------++def online(client, *server_ids):+ with client.Session() as db:+ for server_id in server_ids:+ server = db.get(Server, server_id)+ server.system_info, server.last_seen_at = json.dumps({"collector_version": "0.10.0"}), datetime.now(timezone.utc)+ db.commit()+++def test_with_rule_all_one_server_failing_is_not_down_but_both_is(app):+ check = create(app)+ age(app, check["id"])+ online(app, 1, 2)++ report(app, 1, runs(check["id"], [False, False, False]))+ report(app, 2, runs(check["id"], [True, True, True], ago=60))+ assert check_row(app, check["id"]).state == "up"+ assert incident(app, check["id"]) is None++ report(app, 2, runs(check["id"], [False, False, False]))+ assert check_row(app, check["id"]).state == "down"+ alert = incident(app, check["id"])+ assert alert.status == "active" and alert.severity == "CRITICAL" and alert.title == "Gitea is down"+ assert "alpha" in alert.description and "bravo" in alert.description+++def test_with_rule_all_a_server_yet_to_report_holds_off_down_but_an_offline_one_does_not(app):+ check = create(app)+ age(app, check["id"])+ online(app, 1, 2)++ report(app, 1, runs(check["id"], [False, False, False]))+ assert check_row(app, check["id"]).state != "down"++ with app.Session() as db:+ db.get(Server, 2).last_seen_at = datetime.now(timezone.utc) - timedelta(hours=1)+ db.commit()+ report(app, 1, [run(check["id"], False)])+ assert check_row(app, check["id"]).state == "down"+++def test_retries_must_all_fail_before_a_check_counts_as_down(app):+ check = create(app, server_ids=[1], retries=2)+ age(app, check["id"])++ report(app, 1, runs(check["id"], [True, False, False], ago=20))+ assert check_row(app, check["id"]).state == "pending" # failing, but not yet as often as the retries allow++ report(app, 1, [run(check["id"], False, detail="HTTP 503")])+ assert check_row(app, check["id"]).state == "down"+ assert incident(app, check["id"]).description.startswith("HTTP 503 from alpha")+++def test_with_rule_any_one_server_failing_is_enough(app):+ check = create(app, rule="any", severity="WARNING")+ age(app, check["id"])++ report(app, 1, runs(check["id"], [False, False, False]))+ report(app, 2, runs(check["id"], [True, True, True]))++ assert check_row(app, check["id"]).state == "down"+ assert incident(app, check["id"]).severity == "WARNING"+++def test_coming_back_up_resolves_the_incident(app):+ check = create(app, server_ids=[1])+ age(app, check["id"])+ report(app, 1, runs(check["id"], [False, False, False]))++ report(app, 1, [run(check["id"], True)])++ assert check_row(app, check["id"]).state == "up"+ assert incident(app, check["id"]).status == "resolved"+++def test_a_new_check_stays_quiet_for_ten_minutes(app):+ check = create(app, server_ids=[1])++ report(app, 1, runs(check["id"], [False, False, False]))++ assert check_row(app, check["id"]).state == "down"+ assert incident(app, check["id"]) is None+ assert app.get("/availability").json()["checks"][0]["quiet_until"]+++def test_switching_the_rule_off_keeps_the_state_but_opens_no_incident(app):+ check = create(app, server_ids=[1])+ age(app, check["id"])+ with app.Session() as db:+ db.add(AppSetting(key=main.DISABLED_RULES_KEY, value=json.dumps(["check:down"])))+ db.commit()++ report(app, 1, runs(check["id"], [False, False, False]))++ assert check_row(app, check["id"]).state == "down"+ assert incident(app, check["id"]) is None+++def test_an_upside_down_check_is_up_while_the_service_is_unreachable(app):+ check = create(app, server_ids=[1], type="tcp", target="10.0.0.5:23", upside_down=True)+ age(app, check["id"])++ report(app, 1, runs(check["id"], [False, False, False], ago=60))+ assert check_row(app, check["id"]).state == "up"++ report(app, 1, runs(check["id"], [True, True, True]))+ assert check_row(app, check["id"]).state == "down"+++def test_pausing_resolves_the_incident_and_resuming_starts_over(app):+ check = create(app, server_ids=[1])+ age(app, check["id"])+ report(app, 1, runs(check["id"], [False, False, False]))++ paused = app.post(f"/availability/checks/{check['id']}/pause", json={"paused": True}).json()+ assert paused["state"] == "paused" and incident(app, check["id"]).status == "resolved"+ assert report(app, 1, []).json()["checks"] == []++ resumed = app.post(f"/availability/checks/{check['id']}/pause", json={"paused": False}).json()+ assert resumed["paused"] is False+++def test_deleting_a_check_resolves_its_incident_and_removes_its_history(app):+ check = create(app, server_ids=[1])+ age(app, check["id"])+ report(app, 1, runs(check["id"], [False, False, False]))++ assert app.delete(f"/availability/checks/{check['id']}").status_code == 200++ assert incident(app, check["id"]).status == "resolved"+ with app.Session() as db:+ assert db.query(CheckResult).count() == 0 and db.query(Check).count() == 0+++def test_removing_a_server_takes_it_out_of_its_checks(app):+ both = create(app)+ only = create(app, name="Only alpha", server_ids=[1])++ assert app.delete("/monitoring/servers/1").status_code == 200++ assert availability.servers_of(check_row(app, both["id"])) == [2]+ assert check_row(app, only["id"]).paused is True+++def test_an_incident_from_a_check_has_its_own_rule_kind():+ assert incidents.rule_kind("check:12:down") == "check:down"+ assert any(row["kind"] == "check:down" for row in main.RULE_ROWS)+++# --- what the page shows ---------------------------------------------------------------------------++def test_the_page_shows_the_heartbeat_uptime_and_counts(app):+ check = create(app, server_ids=[1], interval_seconds=60, retries=0)+ age(app, check["id"], minutes=120)+ results = [run(check["id"], index not in (3, 4), seconds_ago=(9 - index) * 60, response_ms=40 + index) for index in range(10)]+ report(app, 1, results)++ page = app.get("/availability").json()+ row = page["checks"][0]++ assert [slot["status"] for slot in row["strip"]][-10:] == ["up", "up", "up", "down", "down", "up", "up", "up", "up", "up"]+ assert row["uptime_24h"] == 80.0+ assert row["response_ms"] == 49+ assert page["counts"] == {"up": 1, "down": 0, "paused": 0, "pending": 0, "total": 1}+ assert {server["hostname"]: server["can_run_checks"] for server in page["servers"]} == {"alpha": True, "bravo": False}+++def test_a_failure_within_the_retries_shows_as_retrying(app):+ check = create(app, server_ids=[1], interval_seconds=60, retries=2)+ report(app, 1, [run(check["id"], True, 120), run(check["id"], False, 60), run(check["id"], True, 0)])++ strip = app.get("/availability").json()["checks"][0]["strip"]++ assert [slot["status"] for slot in strip][-3:] == ["up", "retrying", "up"]+++def test_a_certificate_close_to_expiring_is_listed(app):+ check = create(app, server_ids=[1])+ report(app, 1, [run(check["id"], True, cert_days=9)])++ page = app.get("/availability").json()++ assert page["expiring"] == [{"name": "Gitea", "days": 9}]+++def test_completed_hours_are_rolled_up_and_old_raw_results_dropped(app):+ check = create(app, server_ids=[1], interval_seconds=60, retries=0)+ now = datetime.now(timezone.utc).replace(minute=30, second=0, microsecond=0)+ two_hours_ago = now.replace(minute=0) - timedelta(hours=2)+ with app.Session() as db:+ for minute in range(60):+ db.add(CheckResult(check_id=check["id"], server_id=1, time=two_hours_ago + timedelta(minutes=minute), ok=minute >= 6, response_ms=50))+ db.commit()++ assert availability.roll(db, now) == 1+ rollup = db.query(CheckRollup).one()+ assert (rollup.slots, rollup.down_slots, rollup.avg_ms) == (60, 6, 50.0)+ assert availability.roll(db, now) == 0 # nothing new to summarise++ db.add(CheckResult(check_id=check["id"], server_id=1, time=now - timedelta(days=8), ok=True))+ db.commit()+ assert availability.purge(db, now) == 1+ assert availability._uptime(db, db.get(Check, check["id"]), now - timedelta(days=30), now) == 90.0+++def test_the_detail_has_the_response_per_server_ninety_days_and_the_times_it_went_down(app):+ check = create(app, interval_seconds=60, retries=0)+ age(app, check["id"], minutes=120)+ report(app, 1, [run(check["id"], True, 120, response_ms=40), run(check["id"], False, 60, detail="HTTP 503"), run(check["id"], True, 0, response_ms=60)])+ report(app, 2, [run(check["id"], True, 60, response_ms=90)])++ detail = app.get(f"/availability/checks/{check['id']}?range=1h").json()++ assert {series["hostname"]: [point["ms"] for point in series["points"]] for series in detail["series"]} == {"alpha": [40, 60], "bravo": [90]}+ assert len(detail["days"]) == 90 and detail["days"][-1]["uptime"] == 100.0 and detail["days"][0]["uptime"] is None+ assert detail["average_24h"] == 63+ assert app.get("/availability/checks/999").status_code == 404+++def test_the_detail_lists_when_a_check_went_down_and_came_back(app):+ check = create(app, server_ids=[1])+ age(app, check["id"])+ report(app, 1, runs(check["id"], [False, False, False], ago=60))+ report(app, 1, [run(check["id"], True)])++ detail = app.get(f"/availability/checks/{check['id']}").json()++ assert [event["kind"] for event in detail["events"]] == ["up", "down"]+ assert detail["events"][1]["text"].startswith("Down · No answer from alpha")+ assert detail["last_down"]["ongoing"] is False