"""SQLite storage under $DATA_DIR. One short-lived connection per unit of work.""" import os import sqlite3 from contextlib import contextmanager from pathlib import Path SCHEMA = """ CREATE TABLE IF NOT EXISTS probes ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, token TEXT NOT NULL UNIQUE, address TEXT, -- set by the hub from the report, or ADVERTISE_ADDR, or by hand address_locked INTEGER NOT NULL DEFAULT 0, port INTEGER, hostname TEXT, version TEXT, icmp INTEGER, -- 1/0: whether ICMP works on that probe created REAL NOT NULL, last_seen REAL, last_error TEXT ); CREATE TABLE IF NOT EXISTS measurements ( ts REAL NOT NULL, probe_id INTEGER NOT NULL, target TEXT NOT NULL, -- probe:, gateway, dns:, vps, web: label TEXT, kind TEXT NOT NULL, -- lan | wan method TEXT NOT NULL, -- icmp | http | dns | throughput ok INTEGER NOT NULL, latency REAL, -- ms loss REAL, -- 0..1 (icmp) mbps REAL, -- throughput error TEXT ); CREATE INDEX IF NOT EXISTS m_ts ON measurements(ts); CREATE INDEX IF NOT EXISTS m_series ON measurements(probe_id, target, method, ts); CREATE TABLE IF NOT EXISTS devices ( key TEXT PRIMARY KEY, -- MAC when known, else ip:
mac TEXT, ip TEXT, hostname TEXT, sources TEXT NOT NULL DEFAULT '', first_seen REAL NOT NULL, last_seen REAL, -- last activity (DNS query or ARP); NULL = only listed somewhere name TEXT, category TEXT, suspicious INTEGER NOT NULL DEFAULT 0, notes TEXT ); CREATE INDEX IF NOT EXISTS d_ip ON devices(ip); CREATE TABLE IF NOT EXISTS ip_mac ( ip TEXT PRIMARY KEY, mac TEXT NOT NULL, last_seen REAL NOT NULL ); """ def path() -> Path: return Path(os.environ.get("DATA_DIR", "data")) / "hub.sqlite3" def connect() -> sqlite3.Connection: con = sqlite3.connect(path(), timeout=15) con.row_factory = sqlite3.Row con.execute("PRAGMA journal_mode=WAL") con.execute("PRAGMA synchronous=NORMAL") return con @contextmanager def db(): """A connection whose work commits on success and rolls back on error.""" con = connect() try: with con: yield con finally: con.close() def init() -> None: path().parent.mkdir(parents=True, exist_ok=True) with db() as con: con.executescript(SCHEMA)