Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI): - Network health: live probe/target matrix, status strips, incidents - Probes: add (with install command), rename, remove, latency and throughput charts - Clients merged from AdGuard, DHCP, query log and probe ARP tables; names, categories, suspicious flag, notes, per-client DNS requests - Query log, domain detail (clients, related subdomains), blocked domains via the AdGuard Home /control API Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS, internet URLs and an optional VPS; buffers results while the hub is down. Gateway and ARP from /proc/net on Linux, route/arp on macOS. Install: install.sh (hub) and install-probe.sh (generated from it), each in docker mode (compose; default on Linux hosts) or native mode (venv + systemd or launchd; default on macOS and in LXC). Both modes deploy with an update command that checks the new commit and rolls back on failure. CLAUDE.md carries shared context for Claude Code sessions on each machine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
54a765510a
63 changed files with 6464 additions and 0 deletions
20
tests/conftest.py
Normal file
20
tests/conftest.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DATA_DIR", str(tmp_path))
|
||||
for k in ("ADGUARD_URL", "ADGUARD_USERNAME", "ADGUARD_PASSWORD", "UI_PASSWORD", "VPS_URL", "ROLE"):
|
||||
monkeypatch.delenv(k, raising=False)
|
||||
from app.hub import adguard
|
||||
adguard._stats_cache.update(at=0.0, data=None)
|
||||
monkeypatch.setattr(adguard, "TRANSPORT", None)
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hub():
|
||||
from app.hub.server import app
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
31
tests/test_app.py
Normal file
31
tests/test_app.py
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def test_main_defaults_to_hub():
|
||||
from app.main import app
|
||||
with TestClient(app) as client:
|
||||
r = client.get("/healthz")
|
||||
assert r.status_code == 200 and r.json()["role"] == "hub"
|
||||
|
||||
|
||||
def test_index_assets_and_spa_fallback(hub):
|
||||
page = hub.get("/")
|
||||
assert page.status_code == 200 and "network monitor" in page.text.lower()
|
||||
css = hub.get("/static/css/app.css")
|
||||
assert css.status_code == 200 and css.headers["cache-control"] == "no-cache"
|
||||
assert hub.get("/clients/aa:bb:cc:dd:ee:ff").status_code == 200 # client-side route
|
||||
assert hub.get("/api/nope").status_code == 404
|
||||
|
||||
|
||||
def test_info(hub):
|
||||
j = hub.get("/api/info").json()
|
||||
assert j["role"] == "hub" and j["adguard"] is False
|
||||
|
||||
|
||||
def test_password(hub, monkeypatch):
|
||||
monkeypatch.setenv("UI_PASSWORD", "s3cret")
|
||||
assert hub.get("/api/info").status_code == 401
|
||||
assert hub.get("/api/info", auth=("admin", "wrong")).status_code == 401
|
||||
assert hub.get("/api/info", auth=("admin", "s3cret")).status_code == 200
|
||||
assert hub.get("/healthz").status_code == 200
|
||||
assert hub.post("/api/probe/report", json={}).status_code in (401, 422) # token auth, not the password
|
||||
157
tests/test_dns.py
Normal file
157
tests/test_dns.py
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
"""AdGuard-backed endpoints, against a fake AdGuard Home."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.hub import adguard, dns
|
||||
from app.hub.db import db
|
||||
|
||||
NOW = datetime.now(UTC)
|
||||
|
||||
|
||||
def row(i, client, domain, blocked=False):
|
||||
t = (NOW - timedelta(minutes=i)).isoformat().replace("+00:00", "123Z") # nanosecond-ish like AdGuard
|
||||
return {
|
||||
"time": t, "client": client, "client_info": {"name": f"host-{client.split('.')[-1]}"},
|
||||
"question": {"name": domain, "type": "A", "class": "IN"}, "status": "NOERROR",
|
||||
"reason": "FilteredBlackList" if blocked else "NotFilteredNotFound", "elapsedMs": "1.5",
|
||||
"rules": [{"text": f"||{domain}^", "filter_list_id": 1}] if blocked else [], "upstream": "https://1.1.1.1/dns-query",
|
||||
}
|
||||
|
||||
|
||||
LOG = (
|
||||
[row(i, "192.168.1.5", "api.example.com") for i in range(0, 600)]
|
||||
+ [row(i, "192.168.1.50", "www.example.com") for i in range(600, 700)]
|
||||
+ [row(i, "192.168.1.5", "ads.tracker.net", blocked=True) for i in range(700, 760)]
|
||||
+ [row(i, "192.168.1.51", "cdn.example.co.uk") for i in range(760, 770)]
|
||||
)
|
||||
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.headers.get("authorization", "").startswith("Basic ")
|
||||
p = request.url.path
|
||||
q = request.url.params
|
||||
if p == "/control/status":
|
||||
return httpx.Response(200, json={"version": "v0.107.99", "running": True, "protection_enabled": True})
|
||||
if p == "/control/querylog":
|
||||
rows = LOG
|
||||
if q.get("search"):
|
||||
rows = [r for r in rows if q["search"] in r["question"]["name"] or q["search"] in r["client"]]
|
||||
if q.get("response_status") == "blocked":
|
||||
rows = [r for r in rows if r["reason"] == "FilteredBlackList"]
|
||||
if q.get("older_than"):
|
||||
cut = adguard.parse_time(q["older_than"])
|
||||
rows = [r for r in rows if adguard.parse_time(r["time"]) < cut]
|
||||
page = rows[: int(q.get("limit", 500))]
|
||||
return httpx.Response(200, json={"data": page, "oldest": page[-1]["time"] if page else ""})
|
||||
if p == "/control/stats":
|
||||
return httpx.Response(200, json={
|
||||
"num_dns_queries": 770, "num_blocked_filtering": 60, "time_units": "hours",
|
||||
"top_queried_domains": [{"api.example.com": 600}, {"www.example.com": 100}],
|
||||
"top_blocked_domains": [{"ads.tracker.net": 60}],
|
||||
"top_clients": [{"192.168.1.5": 660}, {"192.168.1.50": 100}],
|
||||
})
|
||||
if p == "/control/clients":
|
||||
return httpx.Response(200, json={
|
||||
"clients": [{"name": "Neil's laptop", "ids": ["192.168.1.5", "AA:BB:CC:DD:EE:01"]}],
|
||||
"auto_clients": [{"ip": "192.168.1.50", "name": "tv.lan", "source": "rDNS"}],
|
||||
})
|
||||
if p == "/control/dhcp/status":
|
||||
return httpx.Response(200, json={"enabled": True, "leases": [{"mac": "aa:bb:cc:dd:ee:02", "ip": "192.168.1.51", "hostname": "plug"}]})
|
||||
return httpx.Response(404, json={})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ag(monkeypatch):
|
||||
monkeypatch.setenv("ADGUARD_URL", "http://adguard.test")
|
||||
monkeypatch.setenv("ADGUARD_USERNAME", "admin")
|
||||
monkeypatch.setenv("ADGUARD_PASSWORD", "pw")
|
||||
monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def test_not_configured(hub):
|
||||
assert hub.get("/api/dns/status").json()["configured"] is False
|
||||
r = hub.get("/api/dns/queries")
|
||||
assert r.status_code == 503 and "ADGUARD_URL" in r.json()["detail"]
|
||||
|
||||
|
||||
def test_status_and_unreachable(hub, ag, monkeypatch):
|
||||
assert hub.get("/api/dns/status").json()["version"] == "v0.107.99"
|
||||
monkeypatch.setattr(adguard, "TRANSPORT", httpx.MockTransport(lambda r: httpx.Response(401)))
|
||||
j = hub.get("/api/dns/status").json()
|
||||
assert j["ok"] is False and "rejected the login" in j["message"]
|
||||
|
||||
|
||||
def test_discovery_merges_sources(hub, ag):
|
||||
asyncio.run(dns.discover_once())
|
||||
clients = {c["key"]: c for c in hub.get("/api/clients").json()["clients"]}
|
||||
laptop = clients["aa:bb:cc:dd:ee:01"]
|
||||
assert laptop["ip"] == "192.168.1.5" and laptop["hostname"] in ("Neil's laptop", "host-5")
|
||||
assert laptop["online"] and laptop["queries"] == 660 and "adguard" in laptop["sources"]
|
||||
assert not laptop["new"] # found on the first day: not flagged as new
|
||||
assert clients["aa:bb:cc:dd:ee:02"]["hostname"] == "plug"
|
||||
assert "ip:192.168.1.50" in clients # no MAC known for the TV
|
||||
assert "ip:192.168.1.5" not in clients # folded into the MAC entry
|
||||
|
||||
|
||||
def test_ip_entry_folds_into_mac_and_keeps_labels(hub, ag):
|
||||
asyncio.run(dns.discover_once())
|
||||
hub.put("/api/clients/ip:192.168.1.50", json={"name": "Living room TV", "category": "Media", "suspicious": True})
|
||||
with db() as con:
|
||||
from app.hub import devices
|
||||
devices.sighting(con, ip="192.168.1.50", mac="aa:bb:cc:dd:ee:50", source="arp")
|
||||
c = hub.get("/api/clients/aa:bb:cc:dd:ee:50").json()
|
||||
assert c["name"] == "Living room TV" and c["category"] == "Media" and c["suspicious"]
|
||||
assert hub.get("/api/clients/ip:192.168.1.50").status_code == 404
|
||||
|
||||
|
||||
def test_queries_filters_and_paging(hub, ag):
|
||||
asyncio.run(dns.discover_once())
|
||||
r = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50}).json()
|
||||
assert len(r["rows"]) == 50 and {x["client"] for x in r["rows"]} == {"192.168.1.5"}
|
||||
assert r["rows"][0]["device"]["key"] == "aa:bb:cc:dd:ee:01"
|
||||
more = hub.get("/api/dns/queries", params={"client": "aa:bb:cc:dd:ee:01", "limit": 50, "older_than": r["oldest"]}).json()
|
||||
assert more["rows"][0]["ts"] < r["rows"][-1]["ts"]
|
||||
blocked = hub.get("/api/dns/queries", params={"status": "blocked"}).json()["rows"]
|
||||
assert blocked and all(x["blocked"] for x in blocked)
|
||||
allowed = hub.get("/api/dns/queries", params={"status": "allowed", "search": "tracker"}).json()
|
||||
assert allowed["rows"] == [] and allowed["done"]
|
||||
|
||||
|
||||
def test_client_summary(hub, ag):
|
||||
asyncio.run(dns.discover_once())
|
||||
s = hub.get("/api/clients/aa:bb:cc:dd:ee:01/summary").json()
|
||||
assert s["top"][0]["domain"] == "api.example.com" and s["blocked"] == 60
|
||||
|
||||
|
||||
def test_domain_detail(hub, ag):
|
||||
d = hub.get("/api/domains/www.example.com").json()
|
||||
assert d["base"] == "example.com" and d["count"] == 100
|
||||
assert d["clients"][0]["ip"] == "192.168.1.50"
|
||||
assert {"domain": "api.example.com", "count": 600, "blocked": 0} in d["related"]
|
||||
assert d["stats_count"] == 100
|
||||
uk = hub.get("/api/domains/cdn.example.co.uk").json()
|
||||
assert uk["base"] == "example.co.uk" and uk["count"] == 10
|
||||
|
||||
|
||||
def test_blocked_and_top(hub, ag):
|
||||
b = hub.get("/api/dns/blocked").json()
|
||||
assert b["top"] == [{"domain": "ads.tracker.net", "count": 60}]
|
||||
assert b["recent"][0]["domain"] == "ads.tracker.net" and b["recent"][0]["rule"] == "||ads.tracker.net^"
|
||||
t = hub.get("/api/domains").json()
|
||||
assert t["top_queried"][0] == {"domain": "api.example.com", "count": 600}
|
||||
|
||||
|
||||
def test_base_domain():
|
||||
assert adguard.base_domain("a.b.c.example.com") == "example.com"
|
||||
assert adguard.base_domain("x.bbc.co.uk") == "bbc.co.uk"
|
||||
assert adguard.base_domain("localhost") == "localhost"
|
||||
assert adguard.base_domain("1.2.3.4") == "1.2.3.4"
|
||||
|
||||
|
||||
def test_parse_time_nanoseconds():
|
||||
assert adguard.parse_time("2026-11-04T10:00:00.123456789+02:00") == datetime(2026, 11, 4, 8, 0, 0, 123456, UTC).timestamp()
|
||||
60
tests/test_installers.py
Normal file
60
tests/test_installers.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"""The installers: generated probe installer in sync, and .env handling per mode."""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def bash(script: str, **env) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(["bash", "-c", script], capture_output=True, text=True, cwd=ROOT,
|
||||
env={**os.environ, **env}, timeout=30)
|
||||
|
||||
|
||||
def test_probe_installer_is_generated_from_install_sh():
|
||||
r = bash("bash scripts/build-installers.sh --check")
|
||||
assert r.returncode == 0, r.stderr
|
||||
for f in ("install.sh", "install-probe.sh", "native/setup.sh", "native/update.sh", "native/run.sh", "native/lib.sh"):
|
||||
assert bash(f"bash -n {f}").returncode == 0, f
|
||||
|
||||
|
||||
# Load the installer's functions without running main (its last line).
|
||||
FUNCS = "source <(sed '$d' \"$INSTALLER\"); set -euo pipefail; OS=Linux; SUDO=; "
|
||||
|
||||
|
||||
def test_write_env_new_and_rerun(tmp_path):
|
||||
d = tmp_path / "opt"
|
||||
d.mkdir()
|
||||
(d / ".env.probe.example").write_text((ROOT / ".env.probe.example").read_text())
|
||||
setup = FUNCS + f'''NETMON_ROLE=probe; ROLE=probe; INSTALL_DIR={d}; ENV_EXAMPLE=.env.probe.example; MODE=native
|
||||
KEYS="REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY INSTALL_MODE HUB_URL PROBE_TOKEN PROBE_PORT ADVERTISE_ADDR"
|
||||
install() {{ cp "${{@: -2:1}}" "${{@: -1}}"; }} # no chown in tests
|
||||
'''
|
||||
r = bash(setup + 'PASSED=" "; REPO_URL=git://x/r.git; REPO_REF=main; HUB_URL=http://hub:8000; PROBE_TOKEN=abc; PROBE_PORT=8765; INSTALL_MODE=native; write_env',
|
||||
INSTALLER="install-probe.sh")
|
||||
assert r.returncode == 0, r.stderr
|
||||
env = (d / ".env").read_text()
|
||||
for line in ("REPO_URL=git://x/r.git", "HUB_URL=http://hub:8000", "PROBE_TOKEN=abc", "INSTALL_MODE=native", "PROBE_PORT=8765"):
|
||||
assert line + "\n" in env
|
||||
# Re-run passing one key: the rest is kept, comments too.
|
||||
r = bash(setup + 'PASSED=" ADVERTISE_ADDR "; ADVERTISE_ADDR=10.0.0.9; write_env', INSTALLER="install-probe.sh")
|
||||
assert r.returncode == 0, r.stderr
|
||||
env2 = (d / ".env").read_text()
|
||||
assert "ADVERTISE_ADDR=10.0.0.9\n" in env2 and "PROBE_TOKEN=abc\n" in env2 and "# The hub this probe reports to" in env2
|
||||
# And load_existing_env reads the saved mode back.
|
||||
r = bash(setup + 'INSTALL_MODE=; HUB_URL=; load_existing_env >/dev/null; echo "$INSTALL_MODE $HUB_URL"', INSTALLER="install-probe.sh")
|
||||
assert r.stdout.strip() == "native http://hub:8000", r.stderr
|
||||
|
||||
|
||||
def test_choose_mode(tmp_path):
|
||||
base = FUNCS + 'KEYS="INSTALL_MODE"; PASSED=" "; log() { :; }; is_lxc() { return 1; }; '
|
||||
run = lambda s: bash(base + s, INSTALLER="install.sh")
|
||||
assert run('INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "docker"
|
||||
assert run('is_lxc() { return 0; }; id() { echo 0; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
|
||||
assert run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=; choose_mode; echo $MODE').stdout.strip() == "native"
|
||||
r = run('OS=Darwin; id() { echo 501; }; INSTALL_MODE=docker; choose_mode')
|
||||
assert r.returncode != 0 and "INSTALL_MODE=native" in r.stderr
|
||||
r = run('id() { echo 1000; }; INSTALL_MODE=native; choose_mode')
|
||||
assert r.returncode != 0 and "run as root" in r.stderr
|
||||
assert run('INSTALL_MODE=bogus; choose_mode').returncode != 0
|
||||
132
tests/test_probe.py
Normal file
132
tests/test_probe.py
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
"""The probe role: its endpoints, its checks and its report loop."""
|
||||
|
||||
import asyncio
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.probe import checks
|
||||
|
||||
|
||||
def test_probe_endpoints(monkeypatch):
|
||||
monkeypatch.setenv("ROLE", "probe")
|
||||
from app.probe.server import app
|
||||
with TestClient(app) as c:
|
||||
assert c.get("/healthz").json()["role"] == "probe"
|
||||
assert c.get("/probe/ping").json()["ok"]
|
||||
blob = c.get("/probe/blob?bytes=200000")
|
||||
assert len(blob.content) == 200000
|
||||
assert c.get("/").json()["mode"] == "serve only"
|
||||
assert c.get("/probe/blob?bytes=999999999").status_code == 422
|
||||
|
||||
|
||||
def fake_dns_server(rcode=0, answers=1):
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.bind(("127.0.0.1", 0))
|
||||
|
||||
def serve():
|
||||
data, addr = s.recvfrom(512)
|
||||
qid = struct.unpack("!H", data[:2])[0]
|
||||
s.sendto(struct.pack("!HHHHHH", qid, 0x8180 | rcode, 1, answers, 0, 0) + data[12:], addr)
|
||||
s.close()
|
||||
threading.Thread(target=serve, daemon=True).start()
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def test_dns_check():
|
||||
for rcode, answers, ok, err in [(0, 1, True, None), (3, 0, False, "NXDOMAIN"), (0, 0, False, "empty answer")]:
|
||||
port = fake_dns_server(rcode, answers)
|
||||
r = asyncio.run(checks.dns("127.0.0.1", "example.com", "dns:x", "x", "lan", port=port))
|
||||
assert r["ok"] is ok and r["error"] == err and r["method"] == "dns"
|
||||
|
||||
|
||||
def test_dns_timeout():
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.bind(("127.0.0.1", 0)) # bound but silent
|
||||
r = asyncio.run(checks.dns("127.0.0.1", "example.com", "dns:x", "x", "lan", timeout=0.3, port=s.getsockname()[1]))
|
||||
s.close()
|
||||
assert not r["ok"] and r["error"] == "timeout"
|
||||
|
||||
|
||||
def test_proc_net_parsing(tmp_path, monkeypatch):
|
||||
(tmp_path / "route").write_text(
|
||||
"Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n"
|
||||
"eth0\t00000000\t0101A8C0\t0003\t0\t0\t100\t00000000\t0\t0\t0\n"
|
||||
"eth0\t0001A8C0\t00000000\t0001\t0\t0\t100\t00FFFFFF\t0\t0\t0\n")
|
||||
(tmp_path / "arp").write_text(
|
||||
"IP address HW type Flags HW address Mask Device\n"
|
||||
"192.168.1.1 0x1 0x2 AA:bb:cc:dd:ee:ff * eth0\n"
|
||||
"192.168.1.77 0x1 0x0 00:00:00:00:00:00 * eth0\n"
|
||||
"172.18.0.2 0x1 0x2 02:42:ac:12:00:02 * br-1a2b3c\n"
|
||||
"172.17.0.3 0x1 0x2 02:42:ac:11:00:03 * docker0\n")
|
||||
monkeypatch.setattr(checks, "PROC_NET", str(tmp_path))
|
||||
assert checks.default_gateway() == "192.168.1.1"
|
||||
assert checks.neighbors() == [{"ip": "192.168.1.1", "mac": "aa:bb:cc:dd:ee:ff"}]
|
||||
|
||||
|
||||
def test_probe_reports_to_hub(hub, monkeypatch):
|
||||
"""One real cycle: the probe loop measures (with the network stubbed) and reports to the hub."""
|
||||
import httpx
|
||||
|
||||
from app.probe import server as probe
|
||||
|
||||
pid = hub.post("/api/probes", json={"name": "Kitchen"}).json()
|
||||
monkeypatch.setenv("HUB_URL", "http://hub.test")
|
||||
monkeypatch.setenv("PROBE_TOKEN", pid["token"])
|
||||
|
||||
async def no_icmp(*a, **k):
|
||||
return None
|
||||
|
||||
async def fake_dns(server, name, target, label, kind, **kw):
|
||||
return checks.m(target, label, kind, "dns", True, latency=12.0)
|
||||
monkeypatch.setattr(checks, "icmp", no_icmp)
|
||||
monkeypatch.setattr(checks, "dns", fake_dns)
|
||||
monkeypatch.setattr(checks, "default_gateway", lambda: None)
|
||||
|
||||
def via_hub(request: httpx.Request):
|
||||
r = hub.request(request.method, request.url.path, content=request.content, headers=dict(request.headers))
|
||||
return httpx.Response(r.status_code, content=r.content, headers={"content-type": "application/json"})
|
||||
real_client = httpx.AsyncClient
|
||||
monkeypatch.setattr(probe.httpx, "AsyncClient", lambda **kw: real_client(transport=httpx.MockTransport(via_hub), **kw))
|
||||
|
||||
async def one_cycle():
|
||||
sleeps = []
|
||||
|
||||
async def fake_sleep(s):
|
||||
sleeps.append(s)
|
||||
if len(sleeps) > 2:
|
||||
raise asyncio.CancelledError
|
||||
monkeypatch.setattr(probe.asyncio, "sleep", fake_sleep)
|
||||
try:
|
||||
await probe.probe_loop()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
asyncio.run(one_cycle())
|
||||
assert probe.state["registered"] is True and probe.state["config"]["name"] == "Kitchen"
|
||||
mx = hub.get("/api/health/matrix").json()
|
||||
assert any(c["target"] == "dns:1.1.1.1" and c["status"] == "ok" for c in mx["cells"])
|
||||
|
||||
|
||||
def test_macos_parsers():
|
||||
route = """ route to: default
|
||||
destination: default
|
||||
mask: default
|
||||
gateway: 192.168.68.1
|
||||
interface: en0
|
||||
flags: <UP,GATEWAY,DONE,STATIC,PRCLONING,GLOBAL>
|
||||
"""
|
||||
assert checks.parse_route_get(route) == "192.168.68.1"
|
||||
assert checks.parse_route_get("route: writing to routing socket: not in table\n") is None
|
||||
arp = """? (192.168.68.1) at 0:ef:15:97:fc:1e on en0 ifscope [ethernet]
|
||||
? (192.168.68.20) at e0:51:d8:1c:5f:96 on en0 ifscope [ethernet]
|
||||
? (192.168.68.77) at (incomplete) on en0 ifscope [ethernet]
|
||||
? (192.168.68.255) at ff:ff:ff:ff:ff:ff on en0 ifscope [ethernet]
|
||||
? (192.168.64.2) at 2a:1:3:4:5:6 on bridge100 ifscope [bridge]
|
||||
? (224.0.0.251) at 1:0:5e:0:0:fb on en0 ifscope permanent [ethernet]
|
||||
"""
|
||||
assert checks.parse_arp_an(arp) == [
|
||||
{"ip": "192.168.68.1", "mac": "00:ef:15:97:fc:1e"},
|
||||
{"ip": "192.168.68.20", "mac": "e0:51:d8:1c:5f:96"},
|
||||
]
|
||||
88
tests/test_probes.py
Normal file
88
tests/test_probes.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
import time
|
||||
|
||||
|
||||
def add(hub, name):
|
||||
r = hub.post("/api/probes", json={"name": name})
|
||||
assert r.status_code == 201
|
||||
return r.json()
|
||||
|
||||
|
||||
def send(hub, token, measurements=(), **extra):
|
||||
return hub.post("/api/probe/report", json={"port": 8765, "measurements": list(measurements), **extra},
|
||||
headers={"Authorization": f"Bearer {token}"})
|
||||
|
||||
|
||||
def meas(target, method="icmp", ok=True, latency=5.0, ts=None, kind="lan", **kw):
|
||||
return {"ts": ts or time.time(), "target": target, "label": target, "kind": kind, "method": method,
|
||||
"ok": ok, "latency": latency if ok else None, **kw}
|
||||
|
||||
|
||||
def test_register_report_and_peers(hub):
|
||||
a, b = add(hub, "Office"), add(hub, "Garage")
|
||||
assert send(hub, "bogus").status_code == 401
|
||||
r = send(hub, a["token"], advertise_addr="192.168.1.10")
|
||||
assert r.status_code == 200
|
||||
assert r.json()["peers"] == [] # Garage hasn't reported an address yet
|
||||
r = send(hub, b["token"], advertise_addr="192.168.1.20")
|
||||
peers = r.json()["peers"]
|
||||
assert peers == [{"id": a["id"], "name": "Office", "host": "192.168.1.10", "port": 8765}]
|
||||
probes = {p["name"]: p for p in hub.get("/api/probes").json()["probes"]}
|
||||
assert probes["Office"]["online"] and probes["Garage"]["address"] == "192.168.1.20"
|
||||
assert "token" not in probes["Office"]
|
||||
|
||||
|
||||
def test_address_override_and_delete(hub):
|
||||
a = add(hub, "Attic")
|
||||
hub.patch(f"/api/probes/{a['id']}", json={"address": "10.0.0.5"})
|
||||
send(hub, a["token"], advertise_addr="192.168.1.99")
|
||||
assert hub.get(f"/api/probes/{a['id']}").json()["address"] == "10.0.0.5" # locked by hand
|
||||
assert hub.delete(f"/api/probes/{a['id']}").status_code == 204
|
||||
assert send(hub, a["token"]).status_code == 401
|
||||
|
||||
|
||||
def test_health_views(hub):
|
||||
a, b = add(hub, "Office"), add(hub, "Garage")
|
||||
send(hub, b["token"], advertise_addr="192.168.1.20")
|
||||
now = time.time()
|
||||
rows = []
|
||||
for i in range(20): # 10 minutes at 30s
|
||||
ts = now - 600 + i * 30
|
||||
down = 8 <= i <= 11
|
||||
rows.append(meas(f"probe:{b['id']}", "icmp", ok=not down, ts=ts, loss=1.0 if down else 0.0))
|
||||
rows.append(meas(f"probe:{b['id']}", "http", ok=not down, ts=ts, latency=12))
|
||||
rows.append(meas("dns:1.1.1.1", "dns", ts=ts, kind="wan", latency=900 if i >= 17 else 20))
|
||||
rows.append(meas(f"probe:{b['id']}", "throughput", ts=ts, mbps=80.0))
|
||||
assert send(hub, a["token"], rows).status_code == 200
|
||||
|
||||
inc = hub.get("/api/health/incidents?range=1h").json()["incidents"]
|
||||
kinds = {(i["label"], i["type"]) for i in inc}
|
||||
assert ("Garage", "down") in kinds and ("dns:1.1.1.1", "degraded") in kinds
|
||||
down = next(i for i in inc if i["type"] == "down")
|
||||
assert down["methods"] == ["http", "icmp"] and down["failed"] == 8
|
||||
|
||||
strips = hub.get("/api/health/strips?range=1h").json()
|
||||
garage = next(s for s in strips["series"] if s["target"] == f"probe:{b['id']}")
|
||||
assert garage["label"] == "Garage" and len(garage["buckets"]) == 60
|
||||
assert "down" in {x["s"] for x in garage["buckets"] if x}
|
||||
assert 0 < garage["uptime"] < 100
|
||||
|
||||
mx = hub.get("/api/health/matrix?window=120").json()
|
||||
cell = next(c for c in mx["cells"] if c["target"] == "dns:1.1.1.1")
|
||||
assert cell["status"] == "down" or cell["status"] == "degraded"
|
||||
assert [t["target"] for t in mx["targets"]][0] == f"probe:{b['id']}" # peers first
|
||||
|
||||
ser = hub.get(f"/api/health/series?probe={a['id']}&range=1h").json()
|
||||
t = next(t for t in ser["targets"] if t["target"] == f"probe:{b['id']}")
|
||||
assert set(t["methods"]) == {"icmp", "http", "throughput"}
|
||||
assert any(x and x["mbps"] == 80.0 for x in t["methods"]["throughput"])
|
||||
|
||||
|
||||
def test_bad_range(hub):
|
||||
assert hub.get("/api/health/strips?range=2y").status_code == 400
|
||||
|
||||
|
||||
def test_arp_neighbors_become_clients(hub):
|
||||
a = add(hub, "Office")
|
||||
send(hub, a["token"], neighbors=[{"ip": "192.168.1.50", "mac": "AA:BB:CC:00:11:22"}])
|
||||
clients = hub.get("/api/clients").json()["clients"]
|
||||
assert clients[0]["key"] == "aa:bb:cc:00:11:22" and clients[0]["online"] and clients[0]["sources"] == ["arp"]
|
||||
Loading…
Add table
Add a link
Reference in a new issue