feat(fleet): integrate independent trackers, VPS pairing and recoverable commands

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:44:12 +03:00
parent d684eb7e05
commit f3a7592d90
45 changed files with 10006 additions and 0 deletions
+46
View File
@@ -0,0 +1,46 @@
"""Firmware-qualified commands, separate from desired configuration/profile writes."""
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
from .independent_equipment import Document, EquipmentError, EquipmentStore
KINDS = {"request-position", "pulse-output", "set-output", "restart"}
def plan(equipment: EquipmentStore, row: Document, command: Document) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01":
raise EquipmentError("Команды для этой версии устройства не проверены.")
kind = command.get("kind")
if kind not in KINDS:
raise EquipmentError("Эта команда не поддерживается.")
config = decode_configuration(
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes()
)
allowed = {"kind"}
if kind in ("pulse-output", "set-output"):
allowed |= {"pin", "seconds" if kind == "pulse-output" else "enabled"}
pin = command.get("pin")
if type(pin) is not int or pin not in (4, 5, 6):
raise EquipmentError("Выберите выход PIN4–PIN6.")
seconds = command.get("seconds")
if kind == "pulse-output" and (type(seconds) is not int or not 1 <= seconds <= 5):
raise EquipmentError("Длительность импульса — от 1 до 5 секунд.")
if kind == "set-output" and type(command.get("enabled")) is not bool:
raise EquipmentError("Укажите включение или выключение выхода.")
if config.integer(16 + pin, 1) != 1:
raise EquipmentError("У выбранного выхода не подтверждён ручной режим управления.")
if set(command) != allowed:
raise EquipmentError("Некорректные параметры команды.")
private = (
{}
if kind in ("request-position", "restart")
else {"encoding": "text", "password": config.text(5)}
)
return {
**command,
**private,
"imei": row["identity_key"],
"model": 231,
"firmware": "0.01",
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
}
+65
View File
@@ -0,0 +1,65 @@
"""Admit the owner VPS before touching the tracker's initial USB channels."""
import time
from .independent_equipment import EquipmentError
def apply(hosts, identifier, revision):
equipment = hosts.equipment
with hosts.lock:
row = next((r for r in equipment.listing() if r["id"] == identifier), None)
if row is None or row["revision"] != revision:
raise EquipmentError("Настройки изменились. Откройте устройство заново.")
equipment.require_idle(row)
endpoint = row["settings"].get("endpoint")
if not endpoint or endpoint["slot"] != 1:
raise EquipmentError("Выберите ваш VPS как сервер 1 для первоначальной настройки.")
host = next(
(
h
for h in hosts.rows()
if h["state"] == "paired"
and row["vehicle_id"] in h["vehicle_ids"]
and h.get("status", {}).get("tracker") == {k: endpoint[k] for k in ("host", "port")}
),
None,
)
if not host:
raise EquipmentError("Сначала подключите выбранный VPS к этому аппарату.")
hosts.sync(host) # durably admit this device before its first cellular connection
if (
host.get("status", {}).get("version")
not in (
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
)
or time.time() - host["last_sync_at"] > 30
):
raise EquipmentError("Установите актуальный VPS Host и проверьте связь с ним.")
return equipment.apply(identifier, revision)
@@ -0,0 +1,80 @@
"""Firmware-qualified, human-readable actions. Previews never contain credentials."""
from .equipment_actions import plan
from .independent_equipment import Document, EquipmentError, EquipmentStore
def presets() -> list[Document]:
values = [
{
"id": "position",
"label": "Запросить координаты",
"command": {"kind": "request-position"},
"wire": "01 01",
"encoding": "INTERNAL · FF",
"queue_seconds": 30,
"confirmation": "Ответ B2 с токеном команды. Новая позиция зависит от GNSS.",
},
{
"id": "restart",
"label": "Перезапустить B2",
"command": {"kind": "restart"},
"wire": "01 07",
"encoding": "INTERNAL · FF",
"queue_seconds": 3,
"confirmation": "Свежие данные B2 по новому соединению после команды.",
},
]
for pin in (4, 5, 6):
for enabled in (True, False):
values.append(
{
"id": f"pin{pin}-{'on' if enabled else 'off'}",
"label": f"{'Включить' if enabled else 'Выключить'} выход PIN{pin}",
"command": {"kind": "set-output", "pin": pin, "enabled": enabled},
"wire": f"••••••*SERV*8.{pin}.{int(enabled)}",
"encoding": "INTERNAL · FC",
"queue_seconds": 3,
"confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.",
}
)
values.append(
{
"id": f"pin{pin}-pulse",
"label": f"Импульс PIN{pin} · 5 с",
"command": {"kind": "pulse-output", "pin": pin, "seconds": 5},
"wire": f"••••••*SERV*24.{pin}.0.5",
"encoding": "INTERNAL · FC",
"queue_seconds": 3,
"confirmation": "Текстовая команда без токена. "
"Ответ не доказывает положение контактов реле.",
}
)
return values
def describe(command: Document | None, kind: str) -> Document:
for value in presets():
if value["command"] == command:
return {k: v for k, v in value.items() if k != "command"}
labels = {
"read-configuration": "Прочитать настройки",
"configure-all": "Применить настройки",
"select-sim": "Переключить SIM",
"read-settings": "Прочитать сервер",
"configure-server1": "Изменить сервер",
}
return {"label": labels.get(kind, "Операция B2"), "wire": "", "encoding": "INTERNAL"}
def catalog(equipment: EquipmentStore, row: Document) -> list[Document]:
result = []
for preset in presets():
reason = ""
try:
plan(equipment, row, preset["command"])
except (EquipmentError, ValueError, OSError):
reason = "Команда недоступна для прочитанной прошивки или режима выхода."
result.append({**preset, "firmware": row["observed"]["firmware"], "unavailable": reason})
return result
@@ -0,0 +1,198 @@
"""Durable, redacted operation history and observed transitions in Core."""
import json
import time
from .equipment_command_catalog import describe
PENDING = {"waiting", "submitting", "queued", "dispatched"}
FIELDS = {
"id",
"host_id",
"state",
"scope",
"kind",
"command",
"stage",
"read_only",
"created_at",
"vps_created_at",
"expires_at",
"dispatched_at",
"received_at",
"verified_at",
"configuration_received_at",
"write_reply_sent_at",
"queue_seconds",
"roundtrip_seconds",
"device_code",
"device_accepted_at",
"durable",
"runtime_phase",
"attempt_count",
"next_attempt_at",
"attempt_expires_at",
"stop_requested",
"reconnected_at",
"reconnect_seconds",
"unchanged",
"active_sim",
"reconcile_pending",
"recovery_at",
"recovery_count",
"recovery_verification",
}
def initialize(db):
db.executescript("""
CREATE TABLE IF NOT EXISTS command_journal(seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT UNIQUE NOT NULL, instance TEXT NOT NULL,
state TEXT NOT NULL, body TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS command_journal_device ON command_journal(instance,seq);
CREATE INDEX IF NOT EXISTS command_journal_pending ON command_journal(state,seq);
CREATE TABLE IF NOT EXISTS command_journal_migrations(name TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS command_result_probes(id TEXT PRIMARY KEY,
instance TEXT NOT NULL,host TEXT NOT NULL,body TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,next_attempt REAL NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS command_result_probes_due
ON command_result_probes(host,next_attempt);
""")
if db.execute("SELECT 1 FROM command_journal_migrations WHERE name='history-v1'").fetchone():
return
for (body,) in db.execute("SELECT body FROM history ORDER BY revision").fetchall():
row = json.loads(body)
capture(db, row, historical=True)
current = set()
for (body,) in db.execute("SELECT body FROM instances").fetchall():
row = json.loads(body)
capture(db, row, historical=True)
current.add(row.get("network_operation", {}).get("id"))
for instance, body in db.execute(
"SELECT instance,body FROM command_journal "
"WHERE state IN ('submitting','queued','dispatched')"
).fetchall():
value = json.loads(body)
if value["id"] not in current:
finish(db, instance, value, "uncertain", "historical_result_missing")
db.execute("INSERT INTO command_journal_migrations VALUES('history-v1')")
def capture(db, row, *, historical=False):
op = row.get("network_operation")
if not op or not op.get("id"):
return
found = db.execute("SELECT body FROM command_journal WHERE id=?", (op["id"],)).fetchone()
old = json.loads(found[0]) if found else None
previous = dict(old or {})
if op.get("durable"):
from .equipment_operations import ATTEMPT_FACTS
for field in ATTEMPT_FACTS:
previous.pop(field, None)
value = {**previous, **{k: v for k, v in op.items() if k in FIELDS}}
value.setdefault("description", describe(op.get("command"), op.get("kind", "")))
value.setdefault("firmware", row.get("observed", {}).get("firmware"))
value.setdefault("events", [])
if value.get("attempt_count", 0) > (old or {}).get("attempt_count", 0):
value["events"].append(
{
"state": "attempt_started",
"attempt": value["attempt_count"],
"observed_at": time.time(),
"occurred_at": op.get("dispatched_at", time.time()),
"historical": historical,
}
)
if not historical:
for field, state in (
("vps_created_at", "queued"),
("dispatched_at", "dispatched"),
("device_accepted_at", "device_accepted"),
("received_at", value["state"]),
("reconnected_at", "reconnected"),
("verified_at", value["state"]),
("recovery_at", "queued"),
):
if field in value and not any(
e.get("evidence") == field and e.get("occurred_at") == value[field]
for e in value["events"]
):
value["events"].append(
{
"state": state,
"occurred_at": value[field],
"observed_at": time.time(),
"historical": False,
"evidence": field,
}
)
transition = (value["state"], value.get("stage"))
if not old or transition != (old["state"], old.get("stage")):
value["events"].append(
{
"state": value["state"],
"stage": value.get("stage"),
"observed_at": time.time(),
"historical": historical,
}
)
value["updated_at"] = time.time()
put(db, row["id"], value)
def put(db, instance, value):
db.execute(
"INSERT INTO command_journal(id,instance,state,body) VALUES(?,?,?,?) "
"ON CONFLICT(id) DO UPDATE SET state=excluded.state,body=excluded.body",
(value["id"], instance, value["state"], json.dumps(value)),
)
def finish(db, instance, value, state, reason):
saved = db.execute("SELECT state FROM command_journal WHERE id=?", (value["id"],)).fetchone()
if saved and saved[0] not in PENDING:
return
value.update(state=state, reason=reason, finished_at=time.time(), updated_at=time.time())
value["events"].append({"state": state, "observed_at": time.time(), "historical": False})
put(db, instance, value)
def public(value):
return {k: v for k, v in value.items() if k not in {"guard", "digest", "preset_id"}}
def listing(equipment, identifier, before=None, limit=25, tracked=()):
with equipment.db() as db:
equipment._find(db, "instances", identifier)
rows = db.execute(
"SELECT seq,body FROM command_journal WHERE instance=? AND seq<? "
"ORDER BY seq DESC LIMIT ?",
(identifier, before or 2**63 - 1, limit + 1),
).fetchall()
counts = dict(
db.execute(
"SELECT state,count(*) FROM command_journal WHERE instance=? GROUP BY state",
(identifier,),
)
)
# Keep every in-flight row visible even outside the current history page.
# Also return final outcomes for IDs that the caller last saw in flight.
tracked = tuple(tracked[:32])
placeholders = ",".join("?" for _ in tracked) or "NULL"
tracked_rows = db.execute(
"SELECT seq,body FROM command_journal WHERE instance=? AND "
"(state IN ('waiting','submitting','queued','dispatched') "
"OR id IN (SELECT id FROM command_result_probes WHERE instance=? "
"ORDER BY rowid DESC LIMIT 32) "
f"OR id IN ({placeholders})) ORDER BY seq DESC",
(identifier, identifier, *tracked),
).fetchall()
return {
"items": [{**public(json.loads(body)), "sequence": seq} for seq, body in rows[:limit]],
"tracked_items": [
{**public(json.loads(body)), "sequence": seq} for seq, body in tracked_rows
],
"next_before": rows[limit - 1][0] if len(rows) > limit else None,
"counts": counts,
}
@@ -0,0 +1,38 @@
"""Durable, bounded GET-only reconciliation after Core loses a VPS result."""
import http.client
import json
import time
def defer(db, identifier, op):
op["reconcile_pending"] = True
db.execute(
"INSERT OR IGNORE INTO command_result_probes(id,instance,host,body) VALUES(?,?,?,?)",
(op["id"], identifier, op["host_id"], json.dumps(op)),
)
def refresh(hosts, host, request, record):
if host["state"] != "paired":
return
# Claim before network I/O; a restart cannot turn an outage into a busy loop.
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
due = db.execute(
"SELECT id,instance,attempts FROM command_result_probes "
"WHERE host=? AND next_attempt<=? ORDER BY next_attempt,id LIMIT 2",
(host["id"], time.time()),
).fetchall()
for identifier, _, attempts in due:
delay = min(300, 5 * 2 ** min(attempts, 6))
db.execute(
"UPDATE command_result_probes SET attempts=attempts+1,next_attempt=? WHERE id=?",
(time.time() + delay, identifier),
)
for operation_id, instance, _ in due:
try:
result = request(host, "GET", "/v1/commands/" + operation_id)
record(hosts, instance, operation_id, result)
except (OSError, ValueError, http.client.HTTPException):
continue
@@ -0,0 +1,188 @@
"""Bounded per-device FIFO. Core owns accepted intents; VPS owns dispatch/results."""
import hashlib
import json
import re
import time
from . import equipment_command_journal as journal
from . import equipment_operations
from .equipment_command_catalog import catalog
from .independent_equipment import EquipmentError
CAPACITY = 32
def guard(row):
return {
"vehicle_id": row["vehicle_id"],
"identity": row["identity_key"],
"firmware": row["observed"]["firmware"],
}
def source(hosts, row):
from .equipment_network import plan
endpoint = plan(hosts.equipment, row, True)["secondary"]
return next(
(
h
for h in hosts.rows()
if h["state"] == "paired"
and row["vehicle_id"] in h["vehicle_ids"]
and h.get("status", {}).get("tracker") == endpoint
),
None,
)
def enqueue(hosts, identifier, request_id, preset_id):
if not re.fullmatch(r"[a-f0-9]{32}", request_id):
raise EquipmentError("Некорректный идентификатор запроса.")
digest = hashlib.sha256(f"{identifier}:{preset_id}".encode()).hexdigest()
equipment = hosts.equipment
# No hosts.lock or network I/O: accepting an intent cannot wait on a radio exchange.
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
old = db.execute("SELECT body FROM command_journal WHERE id=?", (request_id,)).fetchone()
if old:
value = json.loads(old[0])
if value.get("digest") != digest:
raise EquipmentError("Этот ID уже принадлежит другой команде.")
return journal.public(value)
row = equipment._find(db, "instances", identifier)
selected = next((p for p in catalog(equipment, row) if p["id"] == preset_id), None)
if not selected or selected["unavailable"]:
raise EquipmentError("Команда недоступна для этого устройства.")
host = source(hosts, row)
if not host or host.get("status", {}).get("version") not in {
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
}:
raise EquipmentError("Подключите проверенную версию VPS Host с поддержкой очереди.")
count = db.execute(
"SELECT count(*) FROM command_journal WHERE instance=? AND state IN "
"('waiting','submitting','queued','dispatched')",
(identifier,),
).fetchone()[0]
if count >= CAPACITY:
raise EquipmentError(
"Очередь устройства заполнена (32 операции). Дождитесь завершения."
)
now = time.time()
value = {
"id": request_id,
"digest": digest,
"host_id": host["id"],
"preset_id": preset_id,
"guard": guard(row),
"firmware": row["observed"]["firmware"],
"command": selected["command"],
"kind": selected["command"]["kind"],
"description": {
k: v for k, v in selected.items() if k not in {"command", "unavailable"}
},
"state": "waiting",
"scope": "command",
"created_at": now,
"queue_deadline": now + selected["queue_seconds"],
"expires_at": now + (180 if preset_id == "restart" else 30),
"events": [{"state": "waiting", "observed_at": now, "historical": False}],
}
if equipment_operations.supported(host, value["kind"]):
value["durable"] = True
value.pop("queue_deadline")
value.pop("expires_at")
journal.put(db, identifier, value)
hosts.command_wake.set()
return journal.public(value)
def cancel(equipment, identifier, request_id, hosts=None):
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
found = db.execute(
"SELECT body FROM command_journal WHERE instance=? AND id=?", (identifier, request_id)
).fetchone()
if not found:
raise EquipmentError("Операция не найдена.")
value = json.loads(found[0])
if value["state"] == "cancelled":
return journal.public(value)
if value.get("durable") and value["state"] in {"submitting", "queued", "dispatched"}:
row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {})
if op.get("id") != request_id:
raise EquipmentError("Операция больше не является текущей.")
op["stop_requested"] = True
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
journal.capture(db, row)
if hosts is not None:
hosts.command_wake.set()
return journal.public({**value, "stop_requested": True})
if value["state"] != "waiting":
raise EquipmentError("Передача уже началась. Отмену исполнения подтвердить нельзя.")
journal.finish(db, identifier, value, "cancelled", "operator_cancelled")
return journal.public(value)
def pump(hosts):
from .equipment_network import PENDING, start
equipment = hosts.equipment
with equipment.db() as db:
rows = db.execute(
"SELECT instance,body FROM command_journal WHERE state='waiting' ORDER BY seq"
).fetchall()
visited = set()
for identifier, body in rows:
value = json.loads(body)
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
value = json.loads(
db.execute(
"SELECT body FROM command_journal WHERE id=?", (value["id"],)
).fetchone()[0]
)
if value["state"] != "waiting":
continue
row = equipment._find(db, "instances", identifier)
if not value.get("durable") and value["queue_deadline"] <= time.time():
journal.finish(db, identifier, value, "expired", "queue_deadline")
continue
if guard(row) != value["guard"]:
journal.finish(db, identifier, value, "rejected", "device_changed")
continue
if identifier in visited:
continue
visited.add(identifier)
if row.get("network_operation", {}).get("state") in PENDING:
continue
host = source(hosts, row)
if not host or host["id"] != value["host_id"]:
with equipment.db() as db:
journal.finish(db, identifier, value, "rejected", "host_changed")
continue
if time.time() - (host.get("last_sync_at") or 0) > 30:
continue
try:
start(hosts, identifier, row["revision"], command=value["command"], queued_job=value)
except EquipmentError:
# A concurrent config/USB change or an expired/cancelled intent is
# re-evaluated on the next tick; never manufacture a new ID.
continue
@@ -0,0 +1,72 @@
"""Private full-configuration evidence received from an authenticated owner VPS."""
import hashlib
import json
import math
import os
import time
from k1link.device_plugins.arnavi_b2 import profiles
from k1link.device_plugins.arnavi_b2.usb_protocol import decode_configuration
def snapshot(equipment, row, operation, result):
raw = bytes.fromhex(result["configuration"])
config = decode_configuration(raw)
digest = hashlib.sha256(raw).hexdigest()
if digest != result.get("configuration_sha256"):
raise ValueError("configuration digest mismatch")
received = result.get("configuration_received_at")
if type(received) not in (int, float) or not math.isfinite(received) or received <= 0:
raise ValueError("invalid configuration observation time")
old = equipment.root / "evidence" / row["evidence_id"]
identity = (old / "identity.json").read_bytes()
if json.loads(identity)["imei"] != row["identity_key"]:
raise ValueError("configuration evidence identity mismatch")
directory = equipment.root / "evidence" / ("network-" + operation["id"])
directory.mkdir(mode=0o700, exist_ok=True)
files = {"configuration.bin": raw, "identity.json": identity}
files["manifest.json"] = json.dumps(
{
"schema": "missioncore.b2-network-snapshot/v1",
"operation_id": operation["id"],
"host_id": operation["host_id"],
"received_at": received,
"recorded_at": time.time(),
"monotonic_ns": time.monotonic_ns(),
"configuration_sha256": digest,
"identity_source": row["evidence_id"],
"identity_note": (
"Identity/SIM observations retained from previous snapshot; "
"not refreshed by configuration upload"
),
},
indent=2,
).encode()
for name, data in files.items():
temporary = directory / (name + ".new")
with os.fdopen(os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.replace(temporary, directory / name)
handle = os.open(directory, os.O_RDONLY)
try:
os.fsync(handle)
finally:
os.close(handle)
row["evidence_id"] = directory.name
row["observed"] = {
**row["observed"],
"configuration": config.summary(),
"output_modes": {
str(r.number - 16): r.value[0]
for r in config.records
if r.number in (20, 21, 22) and len(r.value) == 1
},
"configuration_read_at": received,
"configuration_transport": "vps",
"supported_profile_fields": list(profiles.portable(config)["parameters"]),
}
row["network_server1"] = {"host": config.text(1), "port": config.integer(2, 2)}
return config
@@ -0,0 +1,67 @@
"""Resolve a saved automatic policy at admission, then freeze the card-bound intent."""
import json
import time
from typing import TYPE_CHECKING
from k1link.device_plugins.arnavi_b2 import sim_access
from k1link.device_plugins.arnavi_b2.connectivity import SIM_FIELDS
from k1link.device_plugins.arnavi_b2.sim_observation_store import SimObservationStore
from k1link.device_plugins.arnavi_b2.usb_protocol import Configuration
from .independent_equipment import Document, EquipmentError, EquipmentStore
if TYPE_CHECKING:
from .vps_hosts import VPSHosts
def resolve(hosts: "VPSHosts", row: Document, source: Document | None) -> Document:
if not source or "arnavi-b2-sim-guard-v1" not in source.get("status", {}).get(
"capabilities", []
):
raise EquipmentError("Для автоподбора обновите VPS Host ARNavi.")
with hosts.db() as db:
record = db.execute(
"SELECT body FROM b2_sim_identity WHERE instance=?", (row["id"],)
).fetchone()
value = json.loads(record[0]) if record else None
if not value or value["host_id"] != source["id"] or value.get("tracker") != row["identity_key"]:
raise EquipmentError("Ожидаем распознавание SIM через подключённый VPS.")
store = SimObservationStore(hosts.equipment.root / "evidence")
result = sim_access.resolve(
value, store, str(row["settings"]["connectivity"]["sim_slot"]), now=time.time()
)
if result["state"] != "ready":
raise EquipmentError(
{
"waiting_identity": "Ожидаем подтверждение карты в выбранном слоте.",
"unknown_card": "Карта ещё не распознана. "
"Прочитайте её через USB или задайте APN вручную.",
"unsupported_operator": "Для этой карты нет сохранённых настроек интернета. "
"Задайте APN вручную.",
}[result["state"]]
)
return result
def remember(
equipment: EquipmentStore,
row: Document,
op: Document,
result: Document,
config: Configuration,
) -> None:
card = op.get("automatic_card")
if not card or op["state"] != "sim_selected" or result.get("sim_guard_verified") is not True:
return
a, u, p = SIM_FIELDS[op["sim_slot"]]
access = (config.text(a), config.text(u), config.text(p))
SimObservationStore(equipment.root / "evidence").remember_access(
row["identity_key"],
card["card_ref"],
access,
operation=op["id"],
verified_at=result["verified_at"],
configuration_sha256=result["configuration_sha256"],
)
op["automatic_access_verified"] = True
+132
View File
@@ -0,0 +1,132 @@
"""Local firmware archive. Storing bytes never authorizes a device update."""
import hashlib
import re
import sqlite3
import time
from pathlib import Path
from typing import Any
MAX_FIRMWARE_BYTES = 4 * 1024 * 1024
MAX_ARCHIVE_BYTES = 128 * 1024 * 1024
class FirmwareError(ValueError):
pass
class FirmwareArchive:
def __init__(self, root: Path, known: dict[str, dict[str, dict[str, Any]]]) -> None:
self.known = known
self.directory = root / "firmware"
self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
self.path = self.directory / "archive.sqlite3"
if self.directory.is_symlink() or self.path.is_symlink():
raise FirmwareError("Хранилище прошивок недоступно.")
db = self.connect()
try:
with db:
db.execute("""CREATE TABLE IF NOT EXISTS images (
model TEXT NOT NULL, digest TEXT NOT NULL, filename TEXT NOT NULL,
added REAL NOT NULL, payload BLOB NOT NULL,
PRIMARY KEY(model, digest))""")
finally:
db.close()
self.path.chmod(0o600)
def connect(self) -> sqlite3.Connection:
db = sqlite3.connect(self.path, timeout=5)
db.row_factory = sqlite3.Row
db.execute("PRAGMA synchronous=FULL")
return db
def require_model(self, model: str) -> None:
if model not in self.known:
raise FirmwareError("Архив прошивок для этой модели недоступен.")
def describe(self, row: sqlite3.Row) -> dict[str, Any]:
data = bytes(row["payload"])
if hashlib.sha256(data).hexdigest() != row["digest"]:
raise FirmwareError("Файл прошивки повреждён. Добавьте исходный файл повторно.")
source = self.known[row["model"]].get(row["digest"], {})
return {
"id": row["digest"],
"model_id": row["model"],
"filename": row["filename"],
"bytes": len(data),
"sha256": row["digest"],
"added_at": row["added"],
"version": source.get("version"),
"source_url": source.get("source_url"),
"source": "manufacturer" if source else "user",
# A known manufacturer's image is not a qualified Mission Core update.
"installable": False,
}
def listing(self, model: str) -> list[dict[str, Any]]:
self.require_model(model)
db = self.connect()
try:
return [
self.describe(row)
for row in db.execute(
"SELECT * FROM images WHERE model=? ORDER BY added DESC, digest", (model,)
)
]
finally:
db.close()
def add(self, model: str, filename: str, payload: bytes) -> dict[str, Any]:
self.require_model(model)
if not re.fullmatch(r"[\w ().-]{1,116}\.dfw", filename, re.IGNORECASE):
raise FirmwareError("Выберите файл .dfw с обычным именем без пути.")
if not 0 < len(payload) <= MAX_FIRMWARE_BYTES:
raise FirmwareError("Файл .dfw должен быть непустым и не больше 4 МБ.")
digest = hashlib.sha256(payload).hexdigest()
db = self.connect()
try:
with db:
db.execute("BEGIN IMMEDIATE")
previous = db.execute(
"SELECT * FROM images WHERE model=? AND digest=?", (model, digest)
).fetchone()
if previous is not None:
if hashlib.sha256(bytes(previous["payload"])).hexdigest() != digest:
db.execute(
"UPDATE images SET payload=? WHERE model=? AND digest=?",
(payload, model, digest),
)
previous = db.execute(
"SELECT * FROM images WHERE model=? AND digest=?", (model, digest)
).fetchone()
return self.describe(previous)
size = db.execute("SELECT COALESCE(SUM(length(payload)),0) FROM images").fetchone()[
0
]
if size + len(payload) > MAX_ARCHIVE_BYTES:
raise FirmwareError("Недостаточно места в архиве прошивок.")
db.execute(
"INSERT INTO images VALUES (?,?,?,?,?)",
(model, digest, filename, time.time(), payload),
)
row = db.execute(
"SELECT * FROM images WHERE model=? AND digest=?", (model, digest)
).fetchone()
return self.describe(row)
finally:
db.close()
def download(self, model: str, digest: str) -> tuple[dict[str, Any], bytes]:
self.require_model(model)
if not re.fullmatch(r"[0-9a-f]{64}", digest):
raise FirmwareError("Файл прошивки не найден.")
db = self.connect()
try:
row = db.execute(
"SELECT * FROM images WHERE model=? AND digest=?", (model, digest)
).fetchone()
if row is None:
raise FirmwareError("Файл прошивки не найден.")
return self.describe(row), bytes(row["payload"])
finally:
db.close()
+902
View File
@@ -0,0 +1,902 @@
"""VPS-backed equipment operations; private wire state never enters browser models."""
import hashlib
import http.client
import json
import math
import re
import time
import uuid
from typing import TYPE_CHECKING
from k1link.device_plugins.arnavi_b2 import connectivity, profiles
from k1link.device_plugins.arnavi_b2.usb_protocol import (
decode_configuration,
prepare_server_slot,
)
from . import equipment_command_reconciliation, equipment_operations, equipment_outbox
from .independent_equipment import Document, EquipmentError, EquipmentStore
from .vps_transport import request
if TYPE_CHECKING:
from .vps_hosts import VPSHosts
PENDING = {"submitting", "queued", "dispatched"}
TERMINAL = {
"verified",
"observed",
"rejected",
"not_applied",
"uncertain",
"unconfirmed",
"expired",
"device_confirmed",
"device_rejected",
"reconnected",
"sim_selected",
"accepted",
"stopped",
}
def idle(row: Document) -> None:
if row.get("network_operation", {}).get("state") in PENDING:
raise EquipmentError("Дождитесь результата текущей операции через VPS.")
def plan(
equipment: EquipmentStore,
row: Document,
read_only: bool = False,
full: bool = False,
*,
select_sim: bool = False,
automatic_access: Document | None = None,
) -> Document:
if row["model_id"] != "arnavi-b2" or row["observed"]["firmware"] != "0.01":
raise EquipmentError("Сетевая запись для этой модели или версии ПО не проверена.")
config = decode_configuration(
(equipment.root / "evidence" / row["evidence_id"] / "configuration.bin").read_bytes()
)
if row.get("network_server1"):
config = prepare_server_slot(config, slot=1, **row["network_server1"])
if full:
body = {
"kind": "read-configuration" if read_only else "configure-all",
"model": 231,
"firmware": "0.01",
"imei": row["identity_key"],
"password": config.text(5),
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
}
if not read_only:
desired = profiles.prepare(
config,
row["settings"],
automatic_access=automatic_access["access"] if automatic_access else None,
)
body.update(
expected_sha256=hashlib.sha256(config.encode()).hexdigest(),
target_configuration=desired.encode().hex(),
target={"host": desired.text(1), "port": desired.integer(2, 2)},
)
connection = row["settings"]["connectivity"]
# A portable desired SIM is not a recurring restart command. An
# explicit operator action still runs when the stored bits already
# match (the live modem may be using another SIM).
sim_mask = (1 << 10) | (1 << 20)
both_allowed = connection["strategy"] in ("both", "native")
selection_requested = connection.get("activate") or both_allowed
selection_changed = selection_requested and (
(desired.integer(72, 4) ^ config.integer(72, 4)) & sim_mask
)
if select_sim and not selection_requested:
raise EquipmentError("Выберите SIM для интернета перед применением.")
access_changed = automatic_access and any(
desired.value(n) != config.value(n)
for n in connectivity.SIM_FIELDS[connection["sim_slot"]]
)
native_access_changed = connection["strategy"] == "native" and any(
desired.value(n) != config.value(n)
for numbers in connectivity.SIM_FIELDS.values()
for n in numbers
)
if select_sim or selection_changed or access_changed or native_access_changed:
body["kind"] = "select-sim"
if both_allowed:
body["sim_policy"] = "both"
else:
body["sim_slot"] = connection["sim_slot"]
if automatic_access:
body["sim_guard"] = {
"slot": connection["sim_slot"],
"sid": automatic_access["firmware_sid"],
}
return body
if read_only:
return {
"kind": "read-settings",
"imei": row["identity_key"],
"password": config.text(5),
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
}
target = row["settings"].get("endpoint")
if not target or target["slot"] != 1 or len(target["host"]) > 32:
raise EquipmentError(
"По сети доступна смена сервера 1 (адрес до 32 символов). "
"Сервер 2 должен сохранять связь с текущим VPS."
)
desired = profiles.prepare(config, row["settings"])
changed = {r.number for r in desired.records if r.value != config.value(r.number)}
if changed - {1, 2} or config.integer(9, 1) != 0:
raise EquipmentError(
"В этой операции можно изменить только адрес и порт сервера 1. "
"Сетевая запись остальных изменённых параметров пока не поддерживается."
)
return {
"kind": "configure-server1",
"model": 231,
"firmware": "0.01",
"imei": row["identity_key"],
"password": config.text(5),
"expected": {"host": config.text(1), "port": config.integer(2, 2)},
"target": {"host": target["host"], "port": target["port"]},
"secondary": {"host": config.text(3), "port": config.integer(4, 2)},
}
def start(
hosts: "VPSHosts",
identifier: str,
revision: int,
read_only: bool = False,
*,
command: Document | None = None,
queued_job: Document | None = None,
select_sim: bool = False,
) -> Document:
from .equipment_command_journal import capture
equipment = hosts.equipment
# Serialize against VPS reassignment and USB operations; no DB transaction over the network.
with hosts.lock, equipment.read_lock:
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = equipment._find(db, "instances", identifier)
previous = row.get("network_operation", {})
if queued_job is not None:
saved = db.execute(
"SELECT body FROM command_journal WHERE id=? AND instance=?",
(queued_job["id"], identifier),
).fetchone()
if not saved:
raise EquipmentError("Операция очереди не найдена.")
queued_job = json.loads(saved[0])
from .equipment_command_runtime import guard
if (
queued_job["state"] != "waiting"
or (
not queued_job.get("durable")
and queued_job["queue_deadline"] <= time.time()
)
or queued_job["guard"] != guard(row)
or queued_job["command"] != command
):
raise EquipmentError("Операция отменена, просрочена или устройство изменилось.")
if (
queued_job is None
and previous.get("requested_revision") == revision
and previous.get("read_only", False) == read_only
and previous.get("command") == command
and previous.get("select_sim", False) == select_sim
):
return equipment.public(row) # lost response retry, same durable operation
if row["revision"] != revision:
raise EquipmentError("Настройки изменились. Откройте устройство заново.")
idle(row)
candidates = [
h
for h in hosts.rows()
if h["state"] == "paired" and row["vehicle_id"] in h["vehicle_ids"]
]
probe = plan(equipment, row, True)
source = next(
(h for h in candidates if h.get("status", {}).get("tracker") == probe["secondary"]),
None,
)
full = (
command is None
and source is not None
and source.get("status", {}).get("version")
in (
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
)
)
automatic_access = None
if (
command is None
and not read_only
and row["settings"]["connectivity"].get("automatic")
):
from .equipment_connectivity import resolve
automatic_access = resolve(hosts, row, source)
if not full:
raise EquipmentError("Автоподбор требует полной настройки через VPS.")
body = (
plan(
equipment,
row,
read_only,
full,
select_sim=select_sim,
automatic_access=automatic_access,
)
if command is None
else None
)
# Only a SIM action or an actual SIM/APN overlay needs current
# presence. Stale cellular telemetry must not block unrelated edits.
connection_changed = False
if (
body
and full
and not read_only
and row["settings"]["connectivity"]["strategy"] == "sim"
):
baseline = decode_configuration(
(
equipment.root / "evidence" / row["evidence_id"] / "configuration.bin"
).read_bytes()
)
desired = decode_configuration(bytes.fromhex(body["target_configuration"]))
slot = row["settings"]["connectivity"]["sim_slot"]
apn_number = 67 if slot == 1 else 89
connection_changed = body["kind"] == "select-sim" or baseline.value(
apn_number
) != desired.value(apn_number)
if not read_only and command is None and connection_changed:
slot = str(row["settings"]["connectivity"]["sim_slot"])
report = next((t for t in hosts.telemetry() if t["instance_id"] == identifier), {})
cellular = report.get("cellular") or {}
status = cellular.get("status") or {}
if (
not report.get("online")
or not source
or cellular.get("host_id") != source["id"]
or not 0 <= time.time() - status.get("measured_at", 0) < 90
or status.get("sim_states", {}).get(slot) not in (1, 2, 3, 5, 6)
):
raise EquipmentError(
f"Наличие SIM {slot} не подтверждено свежими данными B2. "
"Дождитесь обновления сведений о SIM."
)
if command is None:
assert body is not None
if body.get("sim_policy") == "both" and source.get("status", {}).get(
"version"
) not in {"0.1.37", "0.1.38", "0.1.39", "0.1.40", "0.1.41"}:
raise EquipmentError("Для разрешения обеих SIM установите актуальный VPS Host.")
if body["kind"] == "select-sim" and source.get("status", {}).get("version") not in {
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
}:
raise EquipmentError("Для смены SIM установите актуальный VPS Host.")
else:
from .equipment_actions import plan as action_plan
body = action_plan(equipment, row, command)
target = (
source
if read_only or command is not None
else next(
(h for h in candidates if h.get("status", {}).get("tracker") == body["target"]),
None,
)
)
if not source or not target:
raise EquipmentError("Текущий и новый VPS должны быть подключены к этому аппарату.")
if queued_job is not None and source["id"] != queued_job["host_id"]:
raise EquipmentError("Привязка VPS изменилась.")
if command is not None:
versions = {
"restart": (
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
),
"request-position": (
"0.1.8",
"0.1.9",
"0.1.10",
"0.1.11",
"0.1.12",
"0.1.13",
"0.1.14",
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
),
"pulse-output": (
"0.1.9",
"0.1.10",
"0.1.11",
"0.1.12",
"0.1.13",
"0.1.14",
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
),
"set-output": (
"0.1.10",
"0.1.11",
"0.1.12",
"0.1.13",
"0.1.14",
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
),
}
if source.get("status", {}).get("version") not in versions[command["kind"]]:
raise EquipmentError("Для этой команды установите актуальную версию VPS Host.")
if any(
time.time() - (h.get("last_sync_at") or 0) > 30
or h.get("status", {}).get("version")
not in (
"0.1.6",
"0.1.7",
"0.1.8",
"0.1.9",
"0.1.10",
"0.1.11",
"0.1.12",
"0.1.13",
"0.1.14",
"0.1.15",
"0.1.16",
"0.1.17",
"0.1.18",
"0.1.19",
"0.1.20",
"0.1.21",
"0.1.22",
"0.1.23",
"0.1.24",
"0.1.25",
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
)
for h in (source, target)
):
raise EquipmentError("Проверьте связь с VPS и установите актуальную версию хоста.")
body.pop("secondary")
if full:
body.pop("target", None)
body["id"] = queued_job["id"] if queued_job is not None else uuid.uuid4().hex
# Admit the new destination before asking the device to move its primary channel.
op = {
"id": body["id"],
"host_id": source["id"],
"state": "submitting",
"requested_revision": revision,
"created_at": time.time(),
"expires_at": time.time()
+ (
390
if body["kind"] == "select-sim"
else 210
if body["kind"] == "restart"
else 60
if command is not None
else 240
),
"scope": "command"
if command is not None
else "sim-selection"
if body["kind"] == "select-sim"
else "configuration"
if full
else "server1",
"read_only": read_only,
"kind": body["kind"],
"command": command,
"select_sim": select_sim,
}
if body["kind"] == "select-sim":
if body.get("sim_policy") == "both":
op["sim_policy"] = "both"
else:
op["sim_slot"] = body["sim_slot"]
if automatic_access and body.get("sim_guard"):
op["automatic_card"] = {
key: automatic_access[key] for key in ("card_ref", "source", "home_network")
}
if full and not read_only:
op["target_configuration_sha256"] = hashlib.sha256(
bytes.fromhex(body["target_configuration"])
).hexdigest()
if queued_job is not None:
op["created_at"] = queued_job["created_at"]
if not queued_job.get("durable"):
op["expires_at"] = queued_job["expires_at"]
if equipment_operations.supported(source, body["kind"]):
op.update(durable=True, runtime_phase="reconciling")
op.pop("expires_at", None)
updated = {
**row,
"revision": revision + 1,
"network_operation": op,
"updated_at": time.time(),
}
db.execute("INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(row)))
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(updated), identifier))
durable_delivery = source.get("status", {}).get("version") in {
"0.1.26",
"0.1.27",
"0.1.28",
"0.1.29",
"0.1.30",
"0.1.31",
"0.1.32",
"0.1.33",
"0.1.34",
"0.1.35",
"0.1.36",
"0.1.37",
"0.1.38",
"0.1.39",
"0.1.40",
"0.1.41",
}
if durable_delivery:
lifetime = (
360
if body["kind"] == "select-sim"
else 180
if full or body["kind"] == "restart"
else 30
if command is not None
else 120
)
if not op.get("durable"):
body["not_after"] = op["created_at"] + lifetime
db.execute(
"INSERT INTO network_outbox(id,instance,host,target,body) VALUES(?,?,?,?,?)",
(op["id"], identifier, source["id"], target["id"], json.dumps(body)),
)
capture(db, updated)
# Older VPS releases lack an original request deadline; retain GET-only
# reconciliation for those operations instead of making delayed writes.
try:
if durable_delivery:
result = equipment_outbox.attempt(hosts, source, op["id"], request)
else:
hosts.sync(target)
result = request(source, "POST", "/v1/commands", body)
if result is not None:
record(hosts, identifier, op["id"], result)
except (OSError, ValueError, http.client.HTTPException):
pass
with equipment.db() as db:
return equipment.public(equipment._find(db, "instances", identifier))
def record(
hosts: "VPSHosts",
identifier: str,
operation_id: str,
result: Document,
*,
reconcile: bool = False,
) -> None:
from .equipment_command_journal import capture
equipment = hosts.equipment
if result.get("id") != operation_id:
raise ValueError("operation identity mismatch")
if result.get("state") not in PENDING | TERMINAL | {"reply_received"}:
raise ValueError("invalid operation state")
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {})
historical = False
probe = db.execute(
"SELECT body FROM command_result_probes WHERE id=? AND instance=?",
(operation_id, identifier),
).fetchone()
if op.get("id") != operation_id or op.get("state") not in PENDING:
if not probe or result["state"] in PENDING:
return
historical = op.get("id") != operation_id
op = json.loads(probe[0])
kind = op.get("kind") or ("read-settings" if op.get("read_only") else "configure-server1")
if result.get("kind") != kind:
raise ValueError("operation kind mismatch")
equipment_operations.project(op, result)
# The VPS durably owns this exact operation, or Core has closed its
# uncertain outcome. The wire body must never enter public/history JSON.
db.execute("DELETE FROM network_outbox WHERE id=?", (operation_id,))
deadline = result.get("expires_at")
if (
not op.get("durable")
and type(deadline) in (int, float)
and math.isfinite(deadline)
and deadline > 0
):
# The VPS owns the transaction deadline. Never extend Core's bound.
op["expires_at"] = min(op["expires_at"], deadline)
if op.get("scope") in ("configuration", "sim-selection"):
for source, target in (
("created_at", "vps_created_at"),
("dispatched_at", "dispatched_at"),
("configuration_received_at", "configuration_received_at"),
("write_reply_sent_at", "write_reply_sent_at"),
("recovery_at", "recovery_at"),
):
value = result.get(source)
if type(value) in (int, float) and math.isfinite(value) and value > 0:
op[target] = value
count = result.get("recovery_count")
if type(count) is int and count > 0 and result.get("recovery_verification") is True:
op.update(recovery_count=count, recovery_verification=True)
if result["state"] == "sim_selected" and (
kind != "select-sim"
or type(result.get("active_sim")) is not int
or result["active_sim"] not in (1, 2)
or op.get("sim_policy") != "both"
and result["active_sim"] != op.get("sim_slot")
):
raise ValueError("SIM selection result mismatch")
if kind == "select-sim" and result["state"] == "verified":
raise ValueError("configuration readback is not SIM selection")
if (
op.get("automatic_card")
and result["state"] == "sim_selected"
and result.get("sim_guard_verified") is not True
):
raise ValueError("card-bound connectivity result missing")
op.update(
{
k: result[k]
for k in (
"state",
"stage",
"verified_at",
"unchanged",
"active_sim",
"telemetry_measured_at",
"reconnect_seconds",
)
if k in result
}
)
if result["state"] in TERMINAL and "configuration" in result:
from .equipment_configuration import snapshot
config = snapshot(equipment, row, op, result)
op["configuration_sha256"] = result["configuration_sha256"]
op["record_count"] = len(config.records)
if (
result["state"] in ("verified", "sim_selected")
and not op["read_only"]
and result["configuration_sha256"] != op["target_configuration_sha256"]
):
op["state"] = "uncertain"
if not op["read_only"]:
from .equipment_connectivity import remember
remember(equipment, row, op, result, config)
row["policy_state"] = (
("unchanged" if result.get("unchanged") else "applied")
if op["state"] in ("verified", "sim_selected")
else "not_applied"
if result["state"] in ("rejected", "not_applied")
else "uncertain"
)
if result.get("reason") == "sim_card_changed" and result.get(
"write_reply_sent_at"
):
row["policy_state"] = "uncertain"
elif result["state"] in TERMINAL and not op["read_only"]:
if result["state"] in ("verified", "sim_selected"):
op["state"] = "uncertain"
row["policy_state"] = (
"not_started"
if (result["state"] == "stopped" and result.get("attempt_count") == 0)
or result["state"] in ("unconfirmed", "expired")
and result.get("stage") == "preflight"
and not result.get("write_reply_sent_at")
else "uncertain"
)
row["network_operation"] = op
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
capture(db, row)
return
if op.get("scope") == "command":
if result["state"] not in PENDING | {
"device_confirmed",
"device_rejected",
"reconnected",
"expired",
"unconfirmed",
"uncertain",
"accepted",
"stopped",
"rejected",
}:
raise ValueError("invalid command outcome")
if result["state"] == "reconnected" and kind != "restart":
raise ValueError("reconnection is only a restart outcome")
if kind == "restart" and result["state"] == "device_confirmed":
raise ValueError("restart receipt is not reconnection")
op["state"] = result["state"]
if reconcile:
equipment_command_reconciliation.defer(db, identifier, op)
elif probe:
op["reconcile_pending"] = False
db.execute("DELETE FROM command_result_probes WHERE id=?", (operation_id,))
for key in (
"roundtrip_seconds",
"received_at",
"dispatched_at",
"device_code",
"device_accepted_at",
"reconnected_at",
"reconnect_seconds",
"telemetry_measured_at",
):
value = result.get(key)
if type(value) in (int, float) and math.isfinite(value) and value >= 0:
op[key] = value
created, dispatched = result.get("created_at"), result.get("dispatched_at")
if type(created) in (int, float) and math.isfinite(created) and created > 0:
op["vps_created_at"] = created
if (
type(created) in (int, float)
and type(dispatched) in (int, float)
and math.isfinite(dispatched - created)
and dispatched >= created
):
op["queue_seconds"] = dispatched - created
if not historical:
row["network_operation"] = op
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
capture(db, {**row, "network_operation": op})
return
# Explicit projection. Never expose GETP, password, APN credentials or arbitrary errors.
op.update({k: result[k] for k in ("state", "stage", "verified_at") if k in result})
if result["state"] == "reply_received":
if not op.get("read_only"):
raise ValueError("write receipt is not readback")
replies = result.get("replies", [])
match = (
re.match(r"^#1=([A-Za-z0-9.-]{1,32}),([0-9]{1,5}),0,0,#", replies[0])
if len(replies) == 1
else None
)
if not match or not 1 <= int(match[2]) <= 65535:
op["state"] = "uncertain"
else:
endpoint = {"host": match[1], "port": int(match[2])}
row["network_server1"] = endpoint
op.update(state="observed", server1=endpoint, verified_at=time.time())
if result["state"] == "verified":
target = row["settings"]["endpoint"]
expected = {"host": target["host"], "port": target["port"]}
if result.get("server1") != expected:
op["state"] = "uncertain"
else:
row["network_server1"] = expected
# Scope is intentionally not the entire USB profile.
op["server1"] = expected
row["network_operation"] = op
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
capture(db, row)
def refresh(hosts: "VPSHosts", host: Document) -> None:
equipment = hosts.equipment
equipment_command_reconciliation.refresh(hosts, host, request, record)
for row in equipment.listing():
op = row.get("network_operation", {})
if op.get("host_id") != host["id"] or op.get("state") not in PENDING:
continue
reconcile = False
try:
if host["state"] != "paired":
raise ValueError("host replaced")
if op.get("durable") and op.get("stop_requested"):
result = request(
host,
"POST",
equipment_operations.path(op) + op["id"] + "/cancel",
{"kind": op["kind"]},
)
else:
result = request(host, "GET", equipment_operations.path(op) + op["id"])
except (OSError, ValueError, http.client.HTTPException):
if op.get("durable") or time.time() <= op["expires_at"]:
if op.get("durable"):
equipment_operations.disconnected(equipment, row["id"], op["id"])
if op.get("stop_requested"):
continue
if op["state"] == "submitting" and host["state"] == "paired":
try:
receipt = equipment_outbox.attempt(hosts, host, op["id"], request)
if receipt is not None:
record(hosts, row["id"], op["id"], receipt)
except (OSError, ValueError, http.client.HTTPException):
pass
continue
result = {
"id": op["id"],
"kind": op.get("kind")
or ("read-settings" if op.get("read_only") else "configure-server1"),
"state": "uncertain",
}
reconcile = True
# Even an available but stuck VPS must not leave Core pending forever.
# This is unknown outcome, not cancellation or permission to retry a write.
if (
not op.get("durable")
and result.get("state") in PENDING
and time.time() > op["expires_at"]
):
result = {**result, "state": "uncertain"}
reconcile = True
record(hosts, row["id"], op["id"], result, reconcile=reconcile)
+107
View File
@@ -0,0 +1,107 @@
"""Core projection of VPS-owned durable tracker maintenance operations."""
import json
import math
ATTEMPT_FACTS = {
"dispatched_at",
"received_at",
"device_accepted_at",
"device_code",
"roundtrip_seconds",
"reconnected_at",
"reconnect_seconds",
"verified_at",
"configuration_received_at",
"write_reply_sent_at",
"active_sim",
"telemetry_measured_at",
"unchanged",
"stage",
"queue_seconds",
"attempt_expires_at",
}
KINDS = {"request-position", "restart", "read-configuration", "configure-all", "select-sim"}
def supported(host, kind):
return kind in KINDS and "arnavi-b2-durable-operations-v1" in host.get("status", {}).get(
"capabilities", []
)
def path(op):
return "/v1/operations/" if op.get("durable") else "/v1/commands/"
def project(op, result):
if not op.get("durable"):
return
if result.get("durable") is not True:
raise ValueError("durable operation result missing")
# A new attempt must not inherit an earlier ACK, timing or write stage.
for field in ATTEMPT_FACTS:
op.pop(field, None)
op["reconcile_pending"] = False
for field in ("attempt_count", "next_attempt_at", "attempt_expires_at"):
value = result.get(field)
if type(value) in (int, float) and math.isfinite(value) and value >= 0:
op[field] = value
phase = result.get("runtime_phase")
if phase in {
"waiting-link",
"waiting-identity",
"retry-wait",
"checking-result",
"executing",
"complete",
"stopped",
}:
op["runtime_phase"] = phase
if result.get("stop_requested") is True:
op["stop_requested"] = True
if result.get("reason") == "sim_card_changed":
op["reason"] = "sim_card_changed"
def disconnected(equipment, identifier, operation_id):
with equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = equipment._find(db, "instances", identifier)
op = row.get("network_operation", {})
if op.get("id") != operation_id or not op.get("durable") or op.get("reconcile_pending"):
return
op.update(reconcile_pending=True, runtime_phase="reconciling")
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
from .equipment_command_journal import capture
capture(db, row)
def attempts(hosts, identifier, request_id, before=None):
"""Only the paired owning host may supply this instance's attempt history."""
from .independent_equipment import EquipmentError
from .vps_transport import request
with hosts.equipment.db() as db:
row = db.execute(
"SELECT body FROM command_journal WHERE instance=? AND id=?",
(identifier, request_id),
).fetchone()
value = json.loads(row[0]) if row else {}
host = next(
(h for h in hosts.rows() if h["id"] == value.get("host_id") and h["state"] == "paired"),
None,
)
if not value.get("durable") or not host:
raise EquipmentError("История попыток этой операции недоступна.")
suffix = f"?before={before}" if before is not None else ""
result = request(host, "GET", f"/v1/operations/{request_id}/attempts{suffix}")
allowed = ATTEMPT_FACTS | {"id", "number", "phase", "state", "observed_at"}
return {
"items": [
{k: v for k, v in item.items() if k in allowed} for item in result.get("items", [])[:20]
],
"next_before": result.get("next_before"),
}
+51
View File
@@ -0,0 +1,51 @@
"""Private, transactional Core → VPS delivery; never a second tracker operation."""
import json
import time
from collections.abc import Callable
from typing import TYPE_CHECKING
from .independent_equipment import Document
if TYPE_CHECKING:
from .vps_hosts import VPSHosts
def attempt(
hosts: "VPSHosts", source: Document, operation_id: str, send: Callable[..., Document]
) -> Document | None:
# The caller owns hosts.lock. Claim the backoff durably before network I/O.
# A process restart cannot generate a new ID, body, destination or deadline.
with hosts.equipment.db() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute(
"SELECT instance,host,target,body,attempts,next_attempt FROM network_outbox WHERE id=?",
(operation_id,),
).fetchone()
if row is None or row[1] != source["id"] or source["state"] != "paired":
return None
instance = hosts.equipment._find(db, "instances", row[0])
op = instance.get("network_operation", {})
body = json.loads(row[3])
now = time.time()
if (
op.get("id") != operation_id
or op.get("state") != "submitting"
or (not op.get("durable") and min(op["expires_at"], body["not_after"]) <= now)
or row[5] > now
):
return None
# Up to 30 s between retries, with stable per-operation staggering.
delay = min(30, 2 ** min(row[4] + 1, 5)) + int(operation_id[-4:], 16) / 65536
db.execute(
"UPDATE network_outbox SET attempts=attempts+1,next_attempt=? WHERE id=?",
(now + delay, operation_id),
)
target = next((h for h in hosts.rows() if h["id"] == row[2] and h["state"] == "paired"), None)
if target is None:
return None
hosts.sync(target)
# Sync may consume the remaining deadline; do not send stale requests.
if not op.get("durable") and time.time() >= body["not_after"]:
return None
return send(source, "POST", "/v1/operations" if op.get("durable") else "/v1/commands", body)
+285
View File
@@ -0,0 +1,285 @@
"""Independent equipment identities, immutable profiles and assignment history.
No vehicle node_id is used for identity, availability, or enrollment. Saving a
policy never claims the hardware has applied it. Adapter owns vendor semantics.
"""
import json
import secrets
import sqlite3
import threading
import time
import uuid
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any, Protocol, cast
Document = dict[str, Any]
class EnrollmentAdapter(Protocol):
def catalog(self) -> Document: ...
def validate_policy(self, value: Document) -> Document: ...
def inspect(self, evidence: Path) -> Document: ...
def check_policy(self, candidate: Document, evidence: Path, policy: Document) -> None: ...
def apply(self, instance: Document, evidence: Path) -> Document: ...
class EquipmentError(ValueError):
pass
class EquipmentStore:
@staticmethod
def require_idle(row: Document) -> None:
from .equipment_network import idle
idle(row)
def __init__(self, root: Path, adapters: dict[str, EnrollmentAdapter]) -> None:
self.root = root / "independent-equipment"
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
if self.root.is_symlink() or self.root.stat().st_mode & 0o077:
raise EquipmentError("Хранилище оборудования недоступно.")
self.path = self.root / "registry.sqlite3"
if self.path.is_symlink():
raise EquipmentError("Хранилище оборудования недоступно.")
self.adapters = adapters
self.read_lock = threading.Lock()
with self.db() as db:
db.executescript("""
CREATE TABLE IF NOT EXISTS profiles(id TEXT PRIMARY KEY, body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS candidates(id TEXT PRIMARY KEY, expires REAL NOT NULL,
body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS instances(id TEXT PRIMARY KEY,
identity_key TEXT UNIQUE NOT NULL,
body TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS history(instance_id TEXT NOT NULL,
revision INTEGER NOT NULL,
body TEXT NOT NULL, PRIMARY KEY(instance_id, revision));
CREATE TABLE IF NOT EXISTS network_outbox(
id TEXT PRIMARY KEY, instance TEXT NOT NULL, host TEXT NOT NULL,
target TEXT NOT NULL, body TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0);
""")
from .equipment_command_journal import initialize
initialize(db)
self.path.chmod(0o600)
@contextmanager
def db(self) -> Iterator[sqlite3.Connection]:
db = sqlite3.connect(self.path, timeout=5)
try:
db.execute("PRAGMA synchronous=FULL")
with db:
yield db
finally:
db.close()
def adapter(self, model: str) -> EnrollmentAdapter:
if model not in self.adapters:
raise EquipmentError("Модель не поддерживается.")
return self.adapters[model]
def catalog(self) -> Document:
return {"models": [a.catalog() for a in self.adapters.values()]}
def public(self, row: Document) -> Document:
public = {k: v for k, v in row.items() if k not in ("identity_key", "evidence_id")}
details = getattr(self.adapters.get(row.get("model_id")), "observation_details", None)
if details and row.get("evidence_id"):
# Add newly supported observations from the immutable enrollment
# snapshot without requiring USB reconnection or altering policy.
public["observed"] = {
**row.get("observed", {}),
**details(self.root / "evidence" / row["evidence_id"]),
}
return public
def profiles(self) -> list[Document]:
with self.db() as db:
return [
json.loads(r[0])
for r in db.execute("SELECT body FROM profiles ORDER BY rowid DESC")
]
def save_profile(self, name: str, model: str, settings: Document) -> Document:
settings = self.adapter(model).validate_policy(settings)
name = name.strip()
if not name or len(name) > 80:
raise EquipmentError("Укажите название профиля до 80 символов.")
row: Document = {
"id": uuid.uuid4().hex,
"name": name,
"model_id": model,
"settings": settings,
"created_at": time.time(),
}
with self.db() as db:
db.execute("INSERT INTO profiles VALUES(?,?)", (row["id"], json.dumps(row)))
return row
def inspect(self, model: str) -> Document:
adapter = self.adapter(model)
if not self.read_lock.acquire(blocking=False):
raise EquipmentError("Чтение USB уже выполняется. Дождитесь результата.")
try:
row = adapter.inspect(self.root / "evidence")
row.update(id=secrets.token_urlsafe(32), expires_at=time.time() + 600)
with self.db() as db:
db.execute("DELETE FROM candidates WHERE expires < ?", (time.time(),))
db.execute(
"INSERT INTO candidates VALUES(?,?,?)",
(row["id"], row["expires_at"], json.dumps(row)),
)
return self.public(row)
finally:
self.read_lock.release()
@staticmethod
def _find(db: sqlite3.Connection, table: str, identifier: str) -> Document:
# Table names are internal constants, never request data.
row = db.execute(f"SELECT body FROM {table} WHERE id=?", (identifier,)).fetchone()
if row is None:
raise EquipmentError("Запись не найдена. Обновите список.")
return cast(Document, json.loads(row[0]))
def listing(self, vehicle: str | None = None) -> list[Document]:
with self.db() as db:
rows = [
json.loads(r[0]) for r in db.execute("SELECT body FROM instances ORDER BY rowid")
]
return [self.public(r) for r in rows if vehicle is None or r["vehicle_id"] == vehicle]
def add(
self, candidate_id: str, name: str, vehicle_id: str, profile_id: str | None = None
) -> Document:
name = name.strip()
if not name or len(name) > 80:
raise EquipmentError("Укажите название устройства до 80 символов.")
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
candidate = self._find(db, "candidates", candidate_id)
if candidate["expires_at"] <= time.time():
raise EquipmentError("Проверка USB устарела. Прочитайте трекер повторно.")
settings = candidate["settings"]
if profile_id:
profile = self._find(db, "profiles", profile_id)
if profile["model_id"] != candidate["model_id"]:
raise EquipmentError("Профиль предназначен для другой модели.")
settings = profile["settings"]
self.adapter(candidate["model_id"]).check_policy(
candidate, self.root / "evidence", settings
)
row = {
**candidate,
"id": uuid.uuid4().hex,
"name": name,
"vehicle_id": vehicle_id,
"revision": 1,
"settings": settings,
"profile_id": profile_id,
"policy_state": "saved",
"updated_at": time.time(),
}
row.pop("expires_at")
try:
db.execute(
"INSERT INTO instances VALUES(?,?,?)",
(row["id"], row["identity_key"], json.dumps(row)),
)
except sqlite3.IntegrityError:
raise EquipmentError(
"Этот трекер уже добавлен. Измените аппарат в его настройках."
) from None
db.execute("DELETE FROM candidates WHERE id=?", (candidate_id,))
return self.public(row)
def update(
self, identifier: str, revision: int, name: str, vehicle_id: str, settings: Document
) -> Document:
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
old = self._find(db, "instances", identifier)
self.require_idle(old)
if old["revision"] != revision:
raise EquipmentError("Настройки изменились в другом окне. Откройте их заново.")
name = name.strip()
if not name or len(name) > 80:
raise EquipmentError("Укажите название устройства до 80 символов.")
settings = self.adapter(old["model_id"]).validate_policy(settings)
self.adapter(old["model_id"]).check_policy(old, self.root / "evidence", settings)
row = {
**old,
"name": name,
"vehicle_id": vehicle_id,
"settings": settings,
"revision": revision + 1,
"updated_at": time.time(),
}
if settings != old["settings"]:
row.update(policy_state="saved", profile_id=None)
db.execute(
"INSERT INTO history VALUES(?,?,?)", (old["id"], old["revision"], json.dumps(old))
)
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
return self.public(row)
def refresh_observation(self, identifier: str, revision: int) -> Document:
with self.db() as db:
before = self._find(db, "instances", identifier)
self.require_idle(before)
if before["revision"] != revision:
raise EquipmentError("Настройки изменились. Откройте устройство заново.")
candidate = self.inspect(before["model_id"])
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
snapshot = self._find(db, "candidates", candidate["id"])
old = self._find(db, "instances", identifier)
self.require_idle(old)
if old["revision"] != revision:
raise EquipmentError("Настройки изменились во время чтения. Повторите проверку.")
if snapshot["identity_key"] != old["identity_key"]:
raise EquipmentError("Подключён другой трекер. Существующая запись не изменена.")
row = {
**old,
"observed": snapshot["observed"],
"evidence_id": snapshot["evidence_id"],
"revision": revision + 1,
"updated_at": time.time(),
}
# Fresh USB observation supersedes the endpoint projection.
row.pop("network_server1", None)
if snapshot["observed"].get("configuration") != old["observed"].get("configuration"):
row["policy_state"] = "saved"
db.execute("INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old)))
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
db.execute("DELETE FROM candidates WHERE id=?", (candidate["id"],))
return self.public(row)
def apply(self, identifier: str, revision: int) -> Document:
if not self.read_lock.acquire(blocking=False):
raise EquipmentError("USB занят. Дождитесь завершения текущего действия.")
try:
# Keep assignment/policy stable for the entire bounded USB operation.
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
old = self._find(db, "instances", identifier)
self.require_idle(old)
if old["revision"] != revision:
raise EquipmentError("Настройки изменились. Откройте устройство заново.")
adapter = self.adapter(old["model_id"])
adapter.check_policy(old, self.root / "evidence", old["settings"])
result = adapter.apply(old, self.root / "evidence")
row = {**old, **result, "revision": revision + 1, "updated_at": time.time()}
if "observed" in result:
row.pop("network_server1", None)
db.execute(
"INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old))
)
db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier))
return self.public(row)
finally:
self.read_lock.release()
+9
View File
@@ -9,6 +9,11 @@ import time
from contextlib import suppress
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .independent_equipment import EquipmentStore
from .vps_hosts import VPSHosts
from cryptography import x509
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
@@ -27,6 +32,8 @@ class FleetRegistry:
raise PairingError("Хранилище реестра требует закрытый каталог.")
self.started_at = time.time()
self.root = root
self.independent_equipment: EquipmentStore | None = None
self.vps_hosts: VPSHosts | None = None
self.lock = threading.RLock()
from .events import FleetEvents
@@ -119,6 +126,8 @@ class FleetRegistry:
def close(self):
self.stop.set()
if self.vps_hosts is not None:
self.vps_hosts.close()
if self.worker:
self.worker.join(timeout=20)
if self.recovery_worker:
+467
View File
@@ -0,0 +1,467 @@
"""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 .equipment_command_runtime import pump
from .equipment_network import refresh
with self.lock:
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
+150
View File
@@ -0,0 +1,150 @@
"""Public VPS transport, separate from the private-LAN Node pairing contract."""
import base64
import hashlib
import http.client
import ipaddress
import json
import re
import socket
import ssl
import subprocess
import sys
import time
from typing import Any, cast
from urllib.parse import urlsplit
from .trust import PairingError
def destination(endpoint: str) -> tuple[str, int, str]:
url = urlsplit(endpoint)
if (
url.scheme != "https"
or url.username
or url.password
or url.path
or url.query
or url.fragment
or not url.hostname
or not url.port
or not 1024 <= url.port <= 65535
):
raise PairingError("Некорректный адрес VPS.")
addresses = {
str(item[4][0])
for item in socket.getaddrinfo(url.hostname, url.port, socket.AF_INET, socket.SOCK_STREAM)
}
if not addresses or any(not ipaddress.ip_address(ip).is_global for ip in addresses):
raise PairingError("VPS должен иметь публичный IPv4 или DNS-имя.")
return url.hostname, url.port, sorted(addresses)[0]
def invitation(code: str) -> dict[str, Any]:
try:
if len(code) > 4096 or not code.startswith("MCV1."):
raise ValueError
encoded = code[5:]
value = json.loads(
base64.b64decode(encoded + "=" * (-len(encoded) % 4), altchars=b"-_", validate=True)
)
if set(value) != {"schema", "host_id", "endpoint", "fingerprint", "secret", "expires_at"}:
raise ValueError
if (
value["schema"] != "missioncore.vps-pairing/v1"
or not re.fullmatch("[0-9a-f]{64}", value["fingerprint"])
or value["host_id"] != "vps_" + value["fingerprint"]
or not re.fullmatch("[A-Za-z0-9_-]{43}", value["secret"])
):
raise ValueError
if not time.time() < value["expires_at"] <= time.time() + 86500:
raise PairingError("Ключ VPS просрочен. Создайте новый ключ на сервере.")
destination(value["endpoint"])
return cast(dict[str, Any], value)
except (ValueError, TypeError, KeyError) as error:
if isinstance(error, PairingError):
raise
raise PairingError("Ключ VPS повреждён или имеет неподдерживаемую версию.") from None
def interfaces() -> list[dict[str, str]]:
if sys.platform != "darwin":
return []
labels: dict[str, str] = {}
try:
output = subprocess.run(
["/usr/sbin/networksetup", "-listallhardwareports"],
capture_output=True,
text=True,
timeout=3,
check=True,
).stdout
for block in output.split("\n\n"):
parts = dict(line.split(": ", 1) for line in block.splitlines() if ": " in line)
if "Device" in parts and "Hardware Port" in parts:
labels[parts["Device"]] = parts["Hardware Port"]
except (OSError, subprocess.SubprocessError):
pass
return [
{"id": name, "label": labels.get(name, "Сетевой адаптер " + name)}
for _, name in socket.if_nameindex()
if re.fullmatch(r"en[0-9]+", name)
]
def validate_interface(name: str | None) -> None:
if name and name not in {item["id"] for item in interfaces()}:
raise PairingError("Сетевой интерфейс недоступен на этом компьютере.")
def connect(address: str, port: int, interface: str | None) -> socket.socket:
validate_interface(interface)
if not interface:
return socket.create_connection((address, port), 8)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.settimeout(8)
# Darwin IP_BOUND_IF applies to this one socket, not global routing.
sock.setsockopt(socket.IPPROTO_IP, 25, socket.if_nametoindex(interface))
sock.connect((address, port))
return sock
except Exception:
sock.close()
raise
def request(
host: dict[str, Any], method: str, path: str, body: dict[str, Any] | None = None
) -> dict[str, Any]:
name, port, address = destination(host["endpoint"])
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.minimum_version = ssl.TLSVersion.TLSv1_3
connection = http.client.HTTPConnection(name, port, timeout=8)
try:
raw = connect(address, port, host.get("network_interface"))
try:
secure = context.wrap_socket(raw, server_hostname=name)
except Exception:
raw.close()
raise
connection.sock = secure
if (
hashlib.sha256(secure.getpeercert(binary_form=True) or b"").hexdigest()
!= host["fingerprint"]
):
raise PairingError("Идентичность VPS изменилась. Секреты не отправлены.")
headers = {"Content-Type": "application/json"}
if host.get("token"):
headers["Authorization"] = "Bearer " + host["token"]
connection.request(
method, path, json.dumps(body).encode() if body is not None else None, headers
)
response = connection.getresponse()
data = response.read(4 * 1024 * 1024 + 1)
if response.status != 200 or len(data) > 4 * 1024 * 1024:
raise PairingError("VPS не подтвердил запрос. Проверьте ключ и состояние сервера.")
return cast(dict[str, Any], json.loads(data))
finally:
connection.close()
+9
View File
@@ -112,6 +112,10 @@ from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router
from k1link.web.artifact_health_api import build_artifact_health_router
from k1link.web.compute_contour_api import build_compute_contour_router
from k1link.web.fleet_api import router as fleet_router
from k1link.web.independent_equipment_api import router as equipment_router
from k1link.web.equipment_firmware_api import router as equipment_firmware_router
from k1link.web.installer_api import router as installer_router
from k1link.web.vps_host_api import router as vps_host_router, start as start_vps_hosts
from k1link.web.rover_api import router as rover_router
from k1link.web.device_plugin_composition import load_installed_device_plugins
from k1link.web.e30_engineering_api import build_e30_engineering_router
@@ -939,6 +943,7 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]:
try:
fleet = FleetRegistry(session_store.data_dir / "fleet")
fleet.start()
start_vps_hosts(fleet)
application.state.fleet = fleet
except (OSError, ValueError, sqlite3.Error):
# Fail closed for pairing without taking down unrelated operator work.
@@ -1005,6 +1010,10 @@ app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compressle
app.include_router(fleet_router)
app.include_router(equipment_router)
app.include_router(equipment_firmware_router)
app.include_router(vps_host_router)
app.include_router(installer_router)
app.include_router(rover_router)
+74
View File
@@ -0,0 +1,74 @@
"""Local firmware files only: no USB, VPS, or manufacturer requests."""
import sqlite3
from typing import Annotated, Any
from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from starlette.concurrency import run_in_threadpool
from k1link.fleet.equipment_firmware import MAX_FIRMWARE_BYTES, FirmwareError
from k1link.fleet.registry import FleetRegistry
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import firmware_archive
router = APIRouter(prefix="/api/v1/fleet/equipment/firmware", tags=["equipment-firmware"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
@router.get("/{model}")
def catalog(model: str, response: Response, fleet: Fleet) -> dict[str, Any]:
response.headers["Cache-Control"] = "no-store"
try:
return {"items": firmware_archive(fleet).listing(model), "update_available": False}
except FirmwareError as exc:
raise HTTPException(409, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Архив прошивок недоступен.") from None
@router.post("/{model}")
async def upload(
model: str,
request: Request,
fleet: Fleet,
filename: str = Query(min_length=1, max_length=120),
) -> dict[str, Any]:
if request.headers.get("content-type", "").split(";")[0] != "application/octet-stream":
raise HTTPException(415, "Передайте файл .dfw.")
data = bytearray()
async for chunk in request.stream():
if len(data) + len(chunk) > MAX_FIRMWARE_BYTES:
raise HTTPException(413, "Размер файла не должен превышать 4 МБ.")
data.extend(chunk)
def save() -> dict[str, Any]:
return firmware_archive(fleet).add(model, filename, bytes(data))
try:
return await run_in_threadpool(save)
except FirmwareError as exc:
raise HTTPException(422, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Не удалось сохранить файл прошивки.") from None
@router.get("/{model}/{digest}/download")
def download(model: str, digest: str, fleet: Fleet) -> Response:
try:
item, data = firmware_archive(fleet).download(model, digest)
except FirmwareError as exc:
raise HTTPException(404, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Файл прошивки недоступен.") from None
return Response(
data,
media_type="application/octet-stream",
headers={
"Content-Disposition": "attachment; filename*=UTF-8''"
+ quote(item["filename"], safe=""),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"X-Content-SHA256": item["sha256"],
},
)
+258
View File
@@ -0,0 +1,258 @@
"""Local operator API for independent equipment, profiles and assignments."""
from collections.abc import Callable
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from k1link.fleet.independent_equipment import Document, EquipmentError
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.trust import PairingError
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import equipment_store
router = APIRouter(prefix="/api/v1/fleet/equipment", tags=["independent-equipment"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
class ModelRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_id: str = Field(min_length=1, max_length=60)
class ProfileRequest(ModelRequest):
name: str = Field(min_length=1, max_length=80)
settings: Document
class AddRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
candidate_id: str = Field(min_length=43, max_length=43)
name: str = Field(min_length=1, max_length=80)
vehicle_id: str = Field(min_length=1, max_length=80)
profile_id: str | None = Field(default=None, min_length=32, max_length=32)
class UpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
name: str = Field(min_length=1, max_length=80)
vehicle_id: str = Field(min_length=1, max_length=80)
settings: Document
def action(response: Response, callback: Callable[[], Document]) -> Document:
response.headers["Cache-Control"] = "no-store"
try:
return callback()
except (EquipmentError, PairingError) as exc:
raise HTTPException(409, str(exc)) from None
except ValidationError:
raise HTTPException(
422, "Проверьте значения профиля. Уникальные данные и пароли в профиль не входят."
) from None
except ValueError:
raise HTTPException(
422,
"Не удалось проверить настройки или прочитать устройство. "
"Проверьте USB и совместимость профиля.",
) from None
except OSError:
raise HTTPException(503, "Хранилище или USB недоступны. Повторите действие.") from None
@router.get("/catalog")
def catalog(response: Response, fleet: Fleet) -> Document:
return action(response, lambda: equipment_store(fleet).catalog())
@router.get("/profiles")
def profiles(response: Response, fleet: Fleet) -> Document:
return action(response, lambda: {"items": equipment_store(fleet).profiles()})
@router.post("/profiles")
def save_profile(body: ProfileRequest, response: Response, fleet: Fleet) -> Document:
return action(
response,
lambda: equipment_store(fleet).save_profile(body.name, body.model_id, body.settings),
)
@router.post("/inspect")
def inspect(body: ModelRequest, response: Response, fleet: Fleet) -> Document:
return action(response, lambda: equipment_store(fleet).inspect(body.model_id))
@router.get("/instances")
def instances(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document:
return action(response, lambda: {"items": equipment_store(fleet).listing(vehicle_id)})
@router.post("/instances")
def add(body: AddRequest, response: Response, fleet: Fleet) -> Document:
def run() -> Document:
with fleet.lock:
fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary
result = equipment_store(fleet).add(**body.model_dump())
fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary
return result
return action(response, run)
@router.put("/instances/{identifier}")
def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document:
def run() -> Document:
with fleet.lock:
fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary
result = equipment_store(fleet).update(
identifier, body.expected_revision, body.name, body.vehicle_id, body.settings
)
fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary
return result
return action(response, run)
class ReadRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
class NetworkApplyRequest(ReadRequest):
select_sim: bool = Field(default=False, strict=True)
class CommandRequest(ReadRequest):
kind: Literal["request-position", "pulse-output", "set-output", "restart"]
pin: int | None = Field(default=None, ge=4, le=6, strict=True)
seconds: int | None = Field(default=None, ge=1, le=5, strict=True)
enabled: bool | None = Field(default=None, strict=True)
@router.post("/instances/{identifier}/command")
def send_command(
identifier: str, body: CommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
command = body.model_dump(exclude={"expected_revision"}, exclude_none=True)
return action(
response, lambda: start(store(fleet), identifier, body.expected_revision, command=command)
)
@router.post("/instances/{identifier}/inspect")
def read_existing(identifier: str, body: ReadRequest, response: Response, fleet: Fleet) -> Document:
return action(
response,
lambda: equipment_store(fleet).refresh_observation(identifier, body.expected_revision),
)
@router.post("/instances/{identifier}/apply")
def apply_existing(
identifier: str, body: ReadRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_bootstrap import apply
from k1link.web.vps_host_api import store
return action(response, lambda: apply(store(fleet), identifier, body.expected_revision))
@router.post("/instances/{identifier}/apply-network")
def apply_network(
identifier: str, body: NetworkApplyRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
return action(
response,
lambda: start(store(fleet), identifier, body.expected_revision, select_sim=body.select_sim),
)
@router.post("/instances/{identifier}/inspect-network")
def inspect_network(
identifier: str, body: ReadRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
return action(response, lambda: start(store(fleet), identifier, body.expected_revision, True))
class QueuedCommandRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
preset_id: str = Field(min_length=1, max_length=40)
@router.get("/instances/{identifier}/commands")
def command_runtime(
identifier: str,
response: Response,
fleet: Fleet,
before: int | None = Query(default=None, ge=1),
tracked: Annotated[list[str] | None, Query(max_length=32)] = None,
) -> Document:
from k1link.fleet.equipment_command_catalog import catalog
from k1link.fleet.equipment_command_journal import listing
from k1link.fleet.equipment_command_runtime import source
from k1link.fleet.equipment_operations import KINDS, supported
from k1link.web.vps_host_api import store
def run() -> Document:
equipment = equipment_store(fleet)
with equipment.db() as db:
row = equipment._find(db, "instances", identifier)
host = source(store(fleet), row)
return {
**listing(equipment, identifier, before, tracked=tracked or ()),
"device": equipment.public(row),
"catalog": catalog(equipment, row),
"capacity": 32,
"durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)),
}
return action(response, run)
@router.post("/instances/{identifier}/commands")
def enqueue_command(
identifier: str, body: QueuedCommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_command_runtime import enqueue
from k1link.web.vps_host_api import store
return action(
response, lambda: enqueue(store(fleet), identifier, body.request_id, body.preset_id)
)
@router.post("/instances/{identifier}/commands/{request_id}/cancel")
def cancel_command(identifier: str, request_id: str, response: Response, fleet: Fleet) -> Document:
from k1link.fleet.equipment_command_runtime import cancel
from k1link.web.vps_host_api import store
return action(
response, lambda: cancel(equipment_store(fleet), identifier, request_id, store(fleet))
)
@router.get("/instances/{identifier}/commands/{request_id}/attempts")
def command_attempts(
identifier: str,
request_id: str,
response: Response,
fleet: Fleet,
before: int | None = Query(default=None, ge=1),
) -> Document:
from k1link.fleet.equipment_operations import attempts
from k1link.web.vps_host_api import store
return action(response, lambda: attempts(store(fleet), identifier, request_id, before))
@@ -0,0 +1,19 @@
"""Reviewed operator-host enrollment adapters; no onboard plugin dependency."""
from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment
from k1link.device_plugins.arnavi_b2.firmware import KNOWN_IMAGES
from k1link.fleet.equipment_firmware import FirmwareArchive
from k1link.fleet.independent_equipment import EquipmentStore
from k1link.fleet.registry import FleetRegistry
def equipment_store(fleet: FleetRegistry) -> EquipmentStore:
with fleet.lock:
if fleet.independent_equipment is None:
adapter = B2Enrollment()
fleet.independent_equipment = EquipmentStore(fleet.root, {adapter.model_id: adapter})
return fleet.independent_equipment
def firmware_archive(fleet: FleetRegistry) -> FirmwareArchive:
return FirmwareArchive(fleet.root, {B2Enrollment.model_id: KNOWN_IMAGES})
+69
View File
@@ -0,0 +1,69 @@
"""Verified, locally published installers. Never expose arbitrary filesystem paths."""
import hashlib
import json
import re
from pathlib import Path
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Response
from fastapi.responses import FileResponse
from k1link.fleet.registry import FleetRegistry
from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi"}
DOWNLOAD_NAMES = {
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
}
def verified(root: Path, kind: str) -> tuple[dict[str, Any], Path]:
if kind not in KINDS:
raise ValueError("unknown installer")
directory = root / "installers"
item = json.loads((directory / (kind + ".json")).read_text())
if item["id"] != kind or not re.fullmatch(r"[a-zA-Z0-9_.-]+\.pyz", item["filename"]):
raise ValueError("invalid installer manifest")
file = directory / item["filename"]
if file.is_symlink() or file.stat().st_size != item["bytes"]:
raise ValueError("installer changed")
with file.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != item["sha256"]:
raise ValueError("installer changed")
return {
**item,
"filename": DOWNLOAD_NAMES[kind],
"download_url": f"/api/v1/fleet/installers/{kind}/download",
}, file
@router.get("")
def catalog(response: Response, fleet: Fleet) -> dict[str, Any]:
response.headers["Cache-Control"] = "no-store"
items = []
for kind in sorted(KINDS):
try:
item, _ = verified(fleet.root, kind)
items.append(item)
except (OSError, ValueError, KeyError, TypeError):
continue
return {"items": items}
@router.get("/{kind}/download")
def download(kind: str, fleet: Fleet) -> FileResponse:
try:
item, path = verified(fleet.root, kind)
except (OSError, ValueError, KeyError, TypeError):
raise HTTPException(404, "Проверенный установщик недоступен.") from None
return FileResponse(
path,
filename=item["filename"],
media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
)
+108
View File
@@ -0,0 +1,108 @@
"""Local-operator VPS enrollment and shared vehicle assignment."""
import logging
import sqlite3
from collections.abc import Callable
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.independent_equipment import Document
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.trust import PairingError
from k1link.fleet.vps_hosts import VPSHosts
from k1link.fleet.vps_transport import interfaces
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import equipment_store
router = APIRouter(prefix="/api/v1/fleet/vps-hosts", tags=["vps-hosts"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
def start(fleet: FleetRegistry) -> None:
try:
fleet.vps_hosts = VPSHosts(fleet.root, fleet.trust.core_id, equipment_store(fleet))
fleet.vps_hosts.start()
except (OSError, ValueError, sqlite3.Error):
fleet.vps_hosts = None
logging.getLogger(__name__).error("VPS storage unavailable; independent host API disabled")
def store(fleet: FleetRegistry) -> VPSHosts:
if fleet.vps_hosts is None:
raise HTTPException(503, "Хранилище VPS недоступно.")
return fleet.vps_hosts
class Details(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=80)
vehicle_ids: list[str] = Field(max_length=10000)
network_interface: str | None = Field(default=None, max_length=20)
class PairRequest(Details):
code: str = Field(min_length=1, max_length=4096)
replaces_id: str | None = Field(default=None, max_length=80)
class UpdateRequest(Details):
expected_revision: int = Field(ge=1)
def operation(fleet: FleetRegistry, body: Details, callback: Callable[[], Document]) -> Document:
try:
if not body.name.strip():
raise PairingError("Укажите название VPS.")
with fleet.lock:
for vehicle in body.vehicle_ids:
fleet.find(vehicle) # type: ignore[no-untyped-call] # legacy fleet boundary
return callback()
except PairingError as error:
raise HTTPException(409, str(error)) from None
except (OSError, ValueError):
raise HTTPException(
503, "Не удалось связаться с VPS. Проверьте адрес и доступность сервера."
) from None
@router.get("")
def listing(response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return {"items": store(fleet).listing()}
@router.get("/interfaces")
def network_interfaces(fleet: Fleet) -> Document:
return {"items": interfaces()}
@router.get("/telemetry")
def telemetry(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document:
response.headers["Cache-Control"] = "no-store"
return {"items": store(fleet).telemetry(vehicle_id)}
@router.post("")
def pair(body: PairRequest, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return operation(
fleet,
body,
lambda: store(fleet).pair(
body.code, body.name, body.vehicle_ids, body.network_interface, body.replaces_id
),
)
@router.put("/{identifier}")
def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return operation(
fleet,
body,
lambda: store(fleet).update(
identifier, body.expected_revision, body.name, body.vehicle_ids, body.network_interface
),
)