"""Shared VPS hosts, durable pull cursors and independent tracker positions.""" import base64 import http.client import json import logging import secrets import sqlite3 import threading import time from collections.abc import Iterator from contextlib import contextmanager, suppress from pathlib import Path from k1link.device_plugins.arnavi_b2 import sim_access from k1link.device_plugins.arnavi_b2.cellular import parse_telemetry_package as parse_package from k1link.device_plugins.arnavi_b2.sim_network import merge as merge_sim_identity from k1link.device_plugins.arnavi_b2.sim_network import public as public_sim_identity from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore from .independent_equipment import Document, EquipmentStore from .trust import PairingError from .vps_transport import invitation, request, validate_interface class VPSHosts: def __init__(self, root: Path, core_id: str, equipment: EquipmentStore) -> None: self.root = root / "vps-hosts" self.root.mkdir(mode=0o700, exist_ok=True) if self.root.is_symlink() or self.root.stat().st_mode & 0o077: raise PairingError("Хранилище VPS недоступно.") self.path = self.root / "hosts.sqlite3" self.core_id, self.equipment = core_id, equipment self.lock, self.stop = threading.RLock(), threading.Event() self.command_wake = threading.Event() with self.db() as db: db.executescript(""" CREATE TABLE IF NOT EXISTS hosts(id TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS packets(host TEXT NOT NULL, seq INTEGER NOT NULL, instance TEXT NOT NULL, received REAL NOT NULL, raw BLOB NOT NULL, PRIMARY KEY(host,seq)); CREATE TABLE IF NOT EXISTS positions(instance TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS outputs(instance TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS cellular(instance TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS b2_sim_identity( instance TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS links(instance TEXT PRIMARY KEY, host TEXT NOT NULL, received REAL NOT NULL); """) self.path.chmod(0o600) self.worker = threading.Thread(target=self.run, daemon=True, name="mission-core-vps") @contextmanager def db(self) -> Iterator[sqlite3.Connection]: db = sqlite3.connect(self.path, timeout=10) try: db.execute("PRAGMA synchronous=FULL") with db: yield db finally: db.close() def start(self) -> None: self.worker.start() def close(self) -> None: self.stop.set() self.command_wake.set() self.worker.join(timeout=35) @staticmethod def public(value: Document) -> Document: return { k: v for k, v in value.items() if k not in ("token", "secret", "fingerprint", "cursor") } def rows(self) -> list[Document]: with self.db() as db: return [json.loads(r[0]) for r in db.execute("SELECT body FROM hosts ORDER BY rowid")] def listing(self) -> list[Document]: return [self.public(row) for row in self.rows() if row["state"] != "replaced"] def save(self, row: Document) -> None: with self.db() as db: db.execute("INSERT OR REPLACE INTO hosts VALUES(?,?)", (row["id"], json.dumps(row))) def pair( self, code: str, name: str, vehicles: list[str], network_interface: str | None = None, replaces_id: str | None = None, ) -> Document: validate_interface(network_interface) value = invitation(code.strip()) with self.lock: replaced = None if replaces_id: replaced = next((h for h in self.rows() if h["id"] == replaces_id), None) if ( not replaced or replaced["state"] != "paired" or replaced["endpoint"] != value["endpoint"] or replaces_id == value["host_id"] ): raise PairingError("Выберите прежнюю запись этого же VPS для замены.") elif any( h["state"] == "paired" and h["endpoint"] == value["endpoint"] and h["id"] != value["host_id"] for h in self.rows() ): raise PairingError( "Этот адрес уже зарегистрирован. Выберите VPS, который переустановлен." ) row = next((h for h in self.rows() if h["id"] == value["host_id"]), None) if row and row["state"] != "pending": raise PairingError("Этот VPS уже добавлен. Откройте его настройки.") if row is None: row = { **value, "id": value["host_id"], "name": name.strip(), "vehicle_ids": sorted(set(vehicles)), "revision": 1, "token": secrets.token_urlsafe(32), "cursor": 0, "state": "pending", "last_sync_at": None, "status": None, } self.save(row) # Persist retry credential BEFORE the single-use exchange. row["network_interface"] = network_interface self.save(row) status = request( row, "POST", "/v1/pair", {"core_id": self.core_id, "token": row["token"], "secret": row["secret"]}, ) if ( status.get("host_id") != row["id"] or status.get("schema") != "missioncore.vps-host/v1" ): raise PairingError("VPS вернул несовместимое подтверждение.") row.update(state="paired", status=status, last_sync_at=time.time()) row.pop("secret", None) with self.db() as db: db.execute("BEGIN IMMEDIATE") db.execute("UPDATE hosts SET body=? WHERE id=?", (json.dumps(row), row["id"])) if replaced: replaced.update( state="replaced", replaced_by=row["id"], revision=replaced["revision"] + 1 ) db.execute( "UPDATE hosts SET body=? WHERE id=?", (json.dumps(replaced), replaced["id"]) ) return self.public(row) def update( self, identifier: str, revision: int, name: str, vehicles: list[str], network_interface: str | None = None, ) -> Document: validate_interface(network_interface) with self.lock: row = next((r for r in self.rows() if r["id"] == identifier), None) if row is None or row["revision"] != revision: raise PairingError("Настройки VPS изменились. Откройте их повторно.") row.update( name=name.strip(), vehicle_ids=sorted(set(vehicles)), revision=revision + 1, network_interface=network_interface, ) self.save(row) return self.public(row) def devices(self, row: Document) -> list[Document]: endpoint = row["status"]["tracker"] with self.equipment.db() as db: devices = [json.loads(r[0]) for r in db.execute("SELECT body FROM instances")] return [ r for r in devices if r["vehicle_id"] in row["vehicle_ids"] and r["model_id"] == "arnavi-b2" and any( s and s.get("host") == endpoint["host"] and s.get("port") == endpoint["port"] for s in [ r["settings"].get("endpoint"), r.get("network_server1"), *r.get("observed", {}).get("configuration", {}).get("servers", []), ] ) ] def ingest(self, host: Document, items: list[Document], devices: list[Document]) -> int: admitted = {d["id"]: d for d in devices} cursor: int = int(host["cursor"]) with self.db() as db: for item in items: if type(item["id"]) is not int or item["id"] <= cursor: raise ValueError("non-monotonic journal") raw = base64.b64decode(item["raw"], validate=True) parsed = parse_package(raw) if parsed is None or parsed[0] != len(raw): raise ValueError("incomplete journal packet") instance, received = item["instance_id"], float(item["received_at"]) db.execute( "INSERT OR IGNORE INTO packets VALUES(?,?,?,?,?)", (host["id"], item["id"], instance, received, raw), ) if instance in admitted: db.execute( "INSERT INTO links VALUES(?,?,?) ON CONFLICT(instance) DO UPDATE SET " "host=excluded.host,received=MAX(received,excluded.received)", (instance, host["id"], received), ) for packet in parsed[1]: measured = packet["measured_at"] previous_sim = db.execute( "SELECT body FROM b2_sim_identity WHERE instance=?", (instance,) ).fetchone() sim = merge_sim_identity( json.loads(previous_sim[0]) if previous_sim else None, packet, host_id=host["id"], sequence=item["id"], received=received, tracker=admitted[instance].get("identity_key"), ) if sim is not None: db.execute( "INSERT OR REPLACE INTO b2_sim_identity VALUES(?,?)", (instance, json.dumps(sim)), ) if "cellular" in packet and 946684800 < measured <= received + 300: previous = db.execute( "SELECT body FROM cellular WHERE instance=?", (instance,) ).fetchone() cell = json.loads(previous[0]) if previous else {} if cell.get("host_id") != host["id"]: cell = {"host_id": host["id"], "networks": {}} observation = packet["cellular"] stamp = {"measured_at": measured, "received_at": received} if "status" in observation and measured > cell.get("status", {}).get( "measured_at", 0 ): previous_states = cell.get("status", {}).get("sim_states", {}) for slot, state in observation["status"]["sim_states"].items(): if state == 0 or ( previous_states.get(slot) != state and (previous_states.get(slot) == 0 or state == 2) ): # Removal / fresh search invalidates the previous # card's network, even if it was measured recently. cell["networks"].pop(slot, None) cell.setdefault("network_invalidated_at", {})[slot] = ( measured ) cell["status"] = {**observation["status"], **stamp} for slot, network in observation.get("networks", {}).items(): if measured < cell.get("network_invalidated_at", {}).get(slot, 0): continue current_status = cell.get("status", {}) if current_status.get("sim_states", {}).get( slot ) == 0 and measured <= current_status.get("measured_at", 0): continue if measured > cell["networks"].get(slot, {}).get("measured_at", 0): cell["networks"][slot] = {**network, **stamp} db.execute( "INSERT OR REPLACE INTO cellular VALUES(?,?)", (instance, json.dumps(cell)), ) if "outputs" in packet and 946684800 < measured <= received + 300: previous = db.execute( "SELECT body FROM outputs WHERE instance=?", (instance,) ).fetchone() if not previous or json.loads(previous[0])["measured_at"] < measured: outputs = { "pins": packet["outputs"], "host_id": host["id"], "received_at": received, "measured_at": measured, } db.execute( "INSERT OR REPLACE INTO outputs VALUES(?,?)", (instance, json.dumps(outputs)), ) if packet["position"] and 946684800 < measured <= received + 300: previous = db.execute( "SELECT body FROM positions WHERE instance=?", (instance,) ).fetchone() if previous and json.loads(previous[0])["measured_at"] >= measured: continue position = { **packet["position"], "instance_id": instance, "host_id": host["id"], "received_at": received, "measured_at": measured, } db.execute( "INSERT OR REPLACE INTO positions VALUES(?,?)", (instance, json.dumps(position)), ) cursor = item["id"] host["cursor"] = cursor db.execute("UPDATE hosts SET body=? WHERE id=?", (json.dumps(host), host["id"])) return cursor def sync(self, row: Document) -> None: devices = self.devices(row) admission = [] for device in devices: value = {"imei": device["identity_key"], "instance_id": device["id"]} number = device.get("observed", {}).get("device_id") if ( isinstance(number, str) and number.isascii() and number.isdigit() and 1 <= int(number) <= 0xFFFFFFFF ): value["device_id"] = int(number) admission.append(value) request( row, "PUT", "/v1/devices", {"items": admission}, ) batch = request(row, "GET", "/v1/packets?after=" + str(row["cursor"])) cursor = self.ingest(row, batch["items"], devices) if cursor: request(row, "POST", "/v1/ack", {"through": cursor}) row.update( status=request(row, "GET", "/v1/status"), last_sync_at=time.time(), state="paired" ) self.save(row) def run(self) -> None: next_sync: dict[str, float] = {} while not self.stop.is_set(): self.command_wake.clear() pending = False try: pending = self._runtime_tick(next_sync) except (OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException) as exc: # A transient local database failure must not kill the durable sender. logging.getLogger(__name__).warning( "VPS runtime tick failed: %s", type(exc).__name__ ) if not self.stop.is_set(): self.command_wake.wait(1 if pending else 5) def _runtime_tick(self, next_sync: dict[str, float]) -> bool: from . import equipment_command_dispatch from .equipment_command_runtime import pump from .equipment_network import refresh with self.lock: with suppress(OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException): equipment_command_dispatch.pump(self) for row in self.rows(): if self.stop.is_set(): break if row["state"] != "paired": with suppress(OSError, ValueError, KeyError, sqlite3.Error): refresh(self, row) continue # Preserve durable cursors and age the status on any failed exchange. if time.monotonic() >= next_sync.get(row["id"], 0): with suppress( OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException ): self.sync(row) next_sync[row["id"]] = time.monotonic() + 5 # Reconcile durable command results even if telemetry synchronization fails. with suppress( OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException ): refresh(self, row) with suppress(OSError, ValueError, KeyError, sqlite3.Error, http.client.HTTPException): pump(self) with self.equipment.db() as db: pending = db.execute( "SELECT 1 FROM command_journal WHERE state IN " "('waiting','submitting','queued','dispatched') LIMIT 1" ).fetchone() return bool(pending) def telemetry(self, vehicle: str | None = None) -> list[Document]: devices = self.equipment.listing(vehicle) hosts = {r["id"]: r for r in self.rows()} with self.db() as db: positions = { r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM positions") } links = { r[0]: (r[1], r[2]) for r in db.execute("SELECT instance,host,received FROM links") } outputs = { r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM outputs") } cellular = { r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM cellular") } identities = { r[0]: json.loads(r[1]) for r in db.execute("SELECT instance,body FROM b2_sim_identity") } sim_store = SimObservationStore(self.root.parent / "independent-equipment" / "evidence") result = [] for device in devices: link = links.get(device["id"]) position = positions.get(device["id"]) output = outputs.get(device["id"]) cell = cellular.get(device["id"]) sim = identities.get(device["id"]) host = hosts.get(link[0]) if link else None relevant = bool( host and host["state"] == "paired" and device["vehicle_id"] in host["vehicle_ids"] ) if not relevant: link, position, output, cell = None, None, None, None elif output and link and output["host_id"] != link[0]: output = None if cell and (not link or cell["host_id"] != link[0]): cell = None if sim and (not relevant or not link or sim["host_id"] != link[0]): sim = None result.append( { "instance_id": device["id"], "name": device["name"], "vehicle_id": device["vehicle_id"], "position": position, "outputs": output, "cellular": cell, "internet_access": { slot: sim_access.public( sim_access.resolve(sim, sim_store, slot, now=time.time()) ) for slot in ("1", "2") } if sim else None, "sim_identity": public_sim_identity(sim, sim_store, now=time.time()) if sim else None, "outputs_fresh": bool(output and 0 <= time.time() - output["measured_at"] < 90), "last_packet_at": link[1] if link else None, "online": bool( link and host and host["last_sync_at"] and time.time() - host["last_sync_at"] < 30 and time.time() - link[1] < 90 ), "position_fresh": bool(position and time.time() - position["measured_at"] < 90), } ) return result