wifi_spool/wifi_spool.py

439 lines
15 KiB
Python

"""Collect selected Wi-Fi scan results from mosquitto_sub into PostgreSQL."""
from __future__ import annotations
import argparse
import json
import logging
import re
import subprocess
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from datetime import UTC, datetime
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
from uuid import uuid4
from settings import SETTINGS, Settings
LOGGER = logging.getLogger("wifi_spool")
ACCESS_POINT_COORDINATES_FILE = Path(__file__).with_name("access_point_coordinates.csv")
SCHEMA_STATEMENTS = (
"""
CREATE TABLE IF NOT EXISTS bssids (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
bssid TEXT NOT NULL UNIQUE
)
""",
"""
CREATE TABLE IF NOT EXISTS access_point_coordinates (
bssid_id BIGINT PRIMARY KEY,
location_x NUMERIC,
location_y NUMERIC,
FOREIGN KEY (bssid_id) REFERENCES bssids(id),
CHECK ((location_x IS NULL) = (location_y IS NULL))
)
""",
"""
CREATE TABLE IF NOT EXISTS agents (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
agent_name TEXT NOT NULL UNIQUE
)
""",
"""
CREATE TABLE IF NOT EXISTS scan_results (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
bssid_id BIGINT NOT NULL,
location_x INTEGER NOT NULL,
location_y INTEGER NOT NULL,
signal_level INTEGER NOT NULL,
agent_id BIGINT NOT NULL,
collected_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (bssid_id) REFERENCES bssids(id),
FOREIGN KEY (agent_id) REFERENCES agents(id)
)
""",
"""
ALTER TABLE scan_results
ADD COLUMN IF NOT EXISTS collected_at TIMESTAMPTZ
NOT NULL DEFAULT CURRENT_TIMESTAMP
""",
"""
DO $$
DECLARE
current_agent_type TEXT;
BEGIN
SELECT data_type INTO current_agent_type
FROM information_schema.columns
WHERE table_schema = current_schema()
AND table_name = 'scan_results'
AND column_name = 'agent_id';
IF current_agent_type IN ('text', 'character varying') THEN
INSERT INTO agents (agent_name)
SELECT DISTINCT agent_id::TEXT FROM scan_results
ON CONFLICT (agent_name) DO NOTHING;
ALTER TABLE scan_results
ADD COLUMN agent_ref_id BIGINT REFERENCES agents(id);
UPDATE scan_results AS scan
SET agent_ref_id = agent.id
FROM agents AS agent
WHERE agent.agent_name = scan.agent_id::TEXT;
ALTER TABLE scan_results ALTER COLUMN agent_ref_id SET NOT NULL;
ALTER TABLE scan_results DROP COLUMN agent_id;
ALTER TABLE scan_results RENAME COLUMN agent_ref_id TO agent_id;
END IF;
END $$
""",
"""
DO $$
BEGIN
-- Some scan agents append a truncated "(on" marker to an otherwise valid
-- MAC address. Repoint existing samples before removing duplicate BSSIDs.
WITH malformed AS (
SELECT id,
regexp_replace(bssid, '\\(on\\)?$', '', 'i') AS canonical_bssid
FROM bssids
WHERE bssid ~* '^([0-9a-f]{2}:){5}[0-9a-f]{2}\\(on\\)?$'
), duplicates AS (
SELECT malformed.id AS malformed_id, canonical.id AS canonical_id
FROM malformed
JOIN bssids AS canonical
ON lower(canonical.bssid) = lower(malformed.canonical_bssid)
AND canonical.id <> malformed.id
)
UPDATE scan_results AS scan
SET bssid_id = duplicates.canonical_id
FROM duplicates
WHERE scan.bssid_id = duplicates.malformed_id;
DELETE FROM bssids AS malformed
USING bssids AS canonical
WHERE malformed.bssid ~* '^([0-9a-f]{2}:){5}[0-9a-f]{2}\\(on\\)?$'
AND lower(canonical.bssid) = lower(
regexp_replace(malformed.bssid, '\\(on\\)?$', '', 'i')
)
AND canonical.id <> malformed.id;
UPDATE bssids
SET bssid = lower(regexp_replace(bssid, '\\(on\\)?$', '', 'i'))
WHERE bssid ~* '^([0-9a-f]{2}:){5}[0-9a-f]{2}\\(on\\)?$';
END $$
""",
"""
CREATE INDEX IF NOT EXISTS idx_scan_results_bssid_id
ON scan_results(bssid_id)
""",
"""
CREATE INDEX IF NOT EXISTS idx_scan_results_agent_id
ON scan_results(agent_id)
""",
)
SCHEMA = "\n;\n".join(statement.strip() for statement in SCHEMA_STATEMENTS)
@dataclass(frozen=True)
class ScanResult:
bssid: str
location_x: int
location_y: int
signal_level: int
agent_id: str
@dataclass(frozen=True)
class AccessPointCoordinate:
bssid: str
location_x: Decimal | None
location_y: Decimal | None
_BSSID_WITH_OPTIONAL_ON_SUFFIX = re.compile(
r"^((?:[0-9a-f]{2}:){5}[0-9a-f]{2})(?:\(on\)?)?$", re.IGNORECASE
)
def normalize_bssid(value: Any) -> str:
"""Return a canonical MAC, removing the scan agent's stray ``(on`` marker."""
text = str(value).strip()
match = _BSSID_WITH_OPTIONAL_ON_SUFFIX.fullmatch(text)
return match.group(1).lower() if match else text
def load_access_point_coordinates(path: Path) -> list[AccessPointCoordinate]:
"""Read semicolon-separated BSSID coordinates shipped with the service."""
coordinates: list[AccessPointCoordinate] = []
seen: set[str] = set()
with path.open(encoding="utf-8") as source:
for line_number, raw_line in enumerate(source, 1):
line = raw_line.strip()
if not line:
continue
fields = [field.strip() for field in line.split(";")]
if len(fields) != 3:
raise ValueError(f"{path}:{line_number}: expected 3 fields")
bssid = normalize_bssid(fields[0])
if _BSSID_WITH_OPTIONAL_ON_SUFFIX.fullmatch(bssid) is None:
raise ValueError(f"{path}:{line_number}: invalid BSSID")
if bssid in seen:
raise ValueError(f"{path}:{line_number}: duplicate BSSID {bssid}")
if bool(fields[1]) != bool(fields[2]):
raise ValueError(
f"{path}:{line_number}: both coordinates must be set or empty"
)
try:
location_x = Decimal(fields[1]) if fields[1] else None
location_y = Decimal(fields[2]) if fields[2] else None
except InvalidOperation as error:
raise ValueError(
f"{path}:{line_number}: invalid coordinate"
) from error
coordinates.append(AccessPointCoordinate(bssid, location_x, location_y))
seen.add(bssid)
return coordinates
def _integer_location(value: Any) -> int:
"""Convert a numeric coordinate to the nearest integer."""
if isinstance(value, bool):
raise ValueError("boolean is not a coordinate")
return round(float(value))
def parse_message(line: str, target_ssid: str) -> list[ScanResult]:
"""Parse one `mosquitto_sub -v` line and return matching scan rows."""
try:
_topic, raw_message = line.strip().split(maxsplit=1)
envelope = json.loads(raw_message)
data = envelope.get("data", envelope)
if isinstance(data, str):
data = json.loads(data)
if data.get("message_kind") != "scan_results":
return []
payload = data["payload"]
location = payload["location"]
agent_id = str(data["agent_id"])
location_x = _integer_location(location["x"])
location_y = _integer_location(location["y"])
except (AttributeError, KeyError, TypeError, ValueError, json.JSONDecodeError) as error:
raise ValueError(f"invalid MQTT message: {error}") from error
results: list[ScanResult] = []
for item in payload.get("scan_results", []):
if item.get("ssid") != target_ssid:
continue
try:
results.append(
ScanResult(
bssid=normalize_bssid(item["bssid"]),
location_x=location_x,
location_y=location_y,
signal_level=int(item["signal_level"]),
agent_id=agent_id,
)
)
except (KeyError, TypeError, ValueError) as error:
LOGGER.warning("Skipping malformed scan result: %s", error)
return results
def is_scan_results_message(line: str) -> bool:
"""Return whether a raw mosquitto line contains a scan_results message."""
try:
_topic, raw_message = line.strip().split(maxsplit=1)
envelope = json.loads(raw_message)
data = envelope.get("data", envelope)
if isinstance(data, str):
data = json.loads(data)
return isinstance(data, dict) and data.get("message_kind") == "scan_results"
except (AttributeError, TypeError, ValueError, json.JSONDecodeError):
return False
class RawScanArchive:
"""Store every raw scan_results MQTT line in its own file."""
def __init__(self, directory: str) -> None:
self.directory = Path(directory)
def save(self, line: str) -> Path:
self.directory.mkdir(parents=True, exist_ok=True)
timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S.%fZ")
path = self.directory / f"scan_results-{timestamp}-{uuid4().hex}.txt"
with path.open("x", encoding="utf-8") as output:
output.write(line)
if line and not line.endswith("\n"):
output.write("\n")
return path
class Repository:
def __init__(self, settings: Settings, connection: Any = None) -> None:
if connection is None:
try:
import psycopg
except ImportError as error:
raise RuntimeError(
"PostgreSQL driver is not installed; run: "
"python3 -m pip install -r requirements.txt"
) from error
connection = psycopg.connect(
host=settings.postgres_host,
port=settings.postgres_port,
dbname=settings.postgres_database,
user=settings.postgres_user,
password=settings.postgres_password,
connect_timeout=settings.postgres_connect_timeout,
)
self.connection = connection
with self.connection.transaction():
for statement in SCHEMA_STATEMENTS:
self.connection.execute(statement)
self._import_access_point_coordinates(ACCESS_POINT_COORDINATES_FILE)
def _import_access_point_coordinates(self, path: Path) -> None:
for coordinate in load_access_point_coordinates(path):
bssid_row = self.connection.execute(
"""INSERT INTO bssids (bssid) VALUES (%s)
ON CONFLICT (bssid) DO UPDATE SET bssid = EXCLUDED.bssid
RETURNING id""",
(coordinate.bssid,),
).fetchone()
if bssid_row is None: # pragma: no cover - database invariant
raise RuntimeError("failed to resolve coordinate bssid id")
self.connection.execute(
"""INSERT INTO access_point_coordinates
(bssid_id, location_x, location_y) VALUES (%s, %s, %s)
ON CONFLICT (bssid_id) DO UPDATE SET
location_x = EXCLUDED.location_x,
location_y = EXCLUDED.location_y""",
(bssid_row[0], coordinate.location_x, coordinate.location_y),
)
def close(self) -> None:
self.connection.close()
def save(self, results: Iterable[ScanResult]) -> int:
saved = 0
with self.connection.transaction():
for result in results:
bssid_row = self.connection.execute(
"""INSERT INTO bssids (bssid) VALUES (%s)
ON CONFLICT (bssid) DO UPDATE SET bssid = EXCLUDED.bssid
RETURNING id""",
(result.bssid,),
).fetchone()
if bssid_row is None: # pragma: no cover - database invariant
raise RuntimeError("failed to resolve bssid id")
agent_row = self.connection.execute(
"""INSERT INTO agents (agent_name) VALUES (%s)
ON CONFLICT (agent_name)
DO UPDATE SET agent_name = EXCLUDED.agent_name
RETURNING id""",
(result.agent_id,),
).fetchone()
if agent_row is None: # pragma: no cover - database invariant
raise RuntimeError("failed to resolve agent id")
self.connection.execute(
"""INSERT INTO scan_results
(bssid_id, location_x, location_y, signal_level, agent_id)
VALUES (%s, %s, %s, %s, %s)""",
(
bssid_row[0],
result.location_x,
result.location_y,
result.signal_level,
agent_row[0],
),
)
saved += 1
return saved
def mosquitto_command(settings: Settings) -> list[str]:
return [
settings.mosquitto_sub_bin,
"-h", settings.mqtt_host,
"-p", str(settings.mqtt_port),
"-k", str(settings.mqtt_keepalive_seconds),
"-t", settings.mqtt_topic,
"-u", settings.mqtt_username,
"-P", settings.mqtt_password,
"-v",
]
def collect(
lines: Iterable[str],
repository: Repository,
settings: Settings,
raw_archive: RawScanArchive | None = None,
) -> None:
for line in lines:
if raw_archive is not None and is_scan_results_message(line):
raw_archive.save(line)
try:
saved = repository.save(parse_message(line, settings.target_ssid))
if saved:
LOGGER.info("Saved %d scan result(s)", saved)
except ValueError as error:
LOGGER.warning("Skipping message: %s", error)
def subscribe(settings: Settings) -> Iterator[str]:
command = mosquitto_command(settings)
LOGGER.info("Subscribing to %s on %s", settings.mqtt_topic, settings.mqtt_host)
with subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=None,
text=True,
bufsize=1,
) as process:
if process.stdout is None: # pragma: no cover - defensive check
raise RuntimeError("mosquitto_sub stdout is unavailable")
yield from process.stdout
if process.returncode not in (None, 0):
raise RuntimeError(f"mosquitto_sub exited with code {process.returncode}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--stdin",
action="store_true",
help="read mosquitto_sub formatted messages from stdin",
)
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
repository = Repository(SETTINGS)
raw_archive = (
RawScanArchive(SETTINGS.raw_scan_results_dir)
if SETTINGS.save_raw_scan_results
else None
)
try:
if args.stdin:
import sys
collect(sys.stdin, repository, SETTINGS, raw_archive)
else:
collect(subscribe(SETTINGS), repository, SETTINGS, raw_archive)
except KeyboardInterrupt:
LOGGER.info("Stopped")
finally:
repository.close()
if __name__ == "__main__":
main()