feat(system): add worker and VPS catalogs with guarded local removal

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:11:24 +03:00
parent ad5a929e06
commit e8025bc99f
25 changed files with 1556 additions and 116 deletions
+140
View File
@@ -0,0 +1,140 @@
"""VPS inventory metadata. Service registries retain all trust and execution authority."""
import ipaddress
import re
import sqlite3
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
from uuid import NAMESPACE_URL, uuid5
Document = dict[str, Any]
def address(value: str) -> str:
value = value.strip().lower().rstrip(".")
try:
return str(ipaddress.ip_address(value))
except ValueError:
if (
len(value) > 253
or not re.fullmatch(
r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+",
value,
)
or all(c in "0123456789." for c in value)
):
raise ValueError("Укажите IP-адрес или DNS-имя VPS без протокола и порта.") from None
return value
def endpoint_address(endpoint: str) -> str:
return address(urlsplit(endpoint).hostname or "")
def identifier(host: str) -> str:
return "server_" + uuid5(NAMESPACE_URL, "missioncore:vps:" + host).hex
class ServerCatalog:
"""Only labels/addresses persist here; service observations are projected on read.
Equal literal addresses group services for presentation, never merge their
certificates/IDs. DNS aliases are not resolved or merged automatically.
"""
def __init__(self, root: Path):
self.path = root / "server-catalog.sqlite3"
@contextmanager
def db(self) -> Iterator[sqlite3.Connection]:
db = sqlite3.connect(self.path, timeout=10)
try:
db.execute("PRAGMA synchronous=FULL")
db.execute(
"CREATE TABLE IF NOT EXISTS servers "
"(id TEXT PRIMARY KEY, name TEXT NOT NULL, address TEXT UNIQUE NOT NULL, "
"revision INTEGER NOT NULL)"
)
self.path.chmod(0o600)
with db:
yield db
finally:
db.close()
def listing(self, services: list[Document]) -> list[Document]:
with self.db() as db:
rows = db.execute(
"SELECT id,name,address,revision FROM servers ORDER BY rowid"
).fetchall()
hosts = {
r[2]: dict(id=r[0], name=r[1], address=r[2], revision=r[3], services=[]) for r in rows
}
for service in services:
host = endpoint_address(service["endpoint"])
hosts.setdefault(
host, dict(id=identifier(host), name=host, address=host, revision=1, services=[])
)
hosts[host]["services"].append(service)
return list(hosts.values())
def find(self, key: str, services: list[Document]) -> Document:
row = next((r for r in self.listing(services) if r["id"] == key), None)
if row is None:
raise ValueError("VPS не найден. Обновите список.")
return row
def retain(self, row: Document) -> None:
"""Keep a retryable catalog entry until all connection owners acknowledge removal."""
with self.db() as db:
db.execute("INSERT OR IGNORE INTO servers VALUES(?,?,?,?)",
(row["id"], row["name"], row["address"], row["revision"]))
def remove(self, key: str) -> None:
with self.db() as db:
db.execute("DELETE FROM servers WHERE id=?", (key,))
def save(
self,
name: str,
host: str,
services: list[Document],
key: str | None = None,
revision: int | None = None,
) -> Document:
host = address(host)
name = name.strip()
if not name or len(name) > 80:
raise ValueError("Укажите название VPS (до 80 символов).")
current = self.find(key, services) if key else None
if current and current["services"] and current["address"] != host:
raise ValueError(
"Адрес VPS связан с подключёнными службами. "
"Смена адреса требует переподключения служб."
)
rows = self.listing(services)
if any(r["address"] == host and r["id"] != key for r in rows):
raise ValueError("Этот VPS уже есть в списке.")
key = key or identifier(host)
with self.db() as db:
db.execute("BEGIN IMMEDIATE")
saved = db.execute("SELECT revision FROM servers WHERE id=?", (key,)).fetchone()
if current:
if revision != (saved[0] if saved else current["revision"]):
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
next_revision = int(current["revision"]) + 1
else:
if saved:
raise ValueError("Этот VPS уже есть в списке.")
next_revision = 1
try:
db.execute(
"INSERT INTO servers VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET "
"name=excluded.name,address=excluded.address,revision=excluded.revision",
(key, name, host, next_revision),
)
except sqlite3.IntegrityError:
raise ValueError("Этот VPS уже есть в списке.") from None
return self.find(key, services)
+212
View File
@@ -0,0 +1,212 @@
"""Explicit local VPS disconnection. Never administers the remote host or its peers."""
import copy
import hashlib
import ipaddress
import json
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
from k1link.fleet import network_client
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
class ServerRemoval:
def __init__(self, fleet: Any, connections_root: Path):
self.fleet = fleet
self.hosts = fleet.vps_hosts
self.networks = fleet.network_profiles
self.connections = ConnectionStore(connections_root)
self.catalog = ServerCatalog(fleet.root)
@contextmanager
def locked(self) -> Iterator[None]:
# Existing owners retain their locks. Profile imports and tunnel changes
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
with (
self.networks.import_lock,
self.hosts.lock,
self.networks.sync_lock,
self.fleet.lock,
self.networks.lock,
self.connections.locked(),
):
yield
def snapshot(
self, host: Document
) -> tuple[Document, list[Document], list[Document], Registry, set[str], list[Document]]:
arnavi = [
r for r in self.hosts.rows() if endpoint_address(r["endpoint"]) == host["address"]
]
wg = [
r
for r in self.networks.profiles.values()
if endpoint_address(r["endpoint"]) == host["address"]
]
ids = {r["server_id"] for r in wg}
registry = self.connections.read()
profiles = {
p.id for p in registry.profiles if p.provider == "wireguard" and p.network_id in ids
}
vehicles = self.fleet.rows()
blocked = []
affected = []
for row in vehicles:
paths = set(row.get("network_paths", {})) & ids
if paths:
affected.append(row["id"])
if row.get("network_active") in ids or (paths and not row.get("network_active")):
blocked.append(
f"Переключите подключение аппарата «{row.get('name') or row['id']}» "
"на другую сеть."
)
for worker in registry.workers:
if any(
c.id == worker.active_connection_id and c.profile_id in profiles
for c in worker.connections
):
blocked.append(
f"Переключите подключение воркера «{worker.contour_id}» на другую сеть."
)
if any(t.is_alive() for t in self.networks.workers.values()):
blocked.append("Дождитесь завершения переключения сетевых подключений.")
if any(r.get("revocations") for r in wg):
blocked.append("Дождитесь завершения отзыва сетевого доступа.")
host_ids = {r["id"] for r in arnavi}
with self.hosts.equipment.db() as db:
pending = [
json.loads(r[0])
for r in db.execute(
"SELECT body FROM command_journal "
"WHERE state IN ('waiting','submitting','queued','dispatched')"
)
]
probes = {r[0] for r in db.execute("SELECT host FROM command_result_probes")}
outbox = {x for r in db.execute("SELECT host,target FROM network_outbox") for x in r}
if any(r.get("host_id") in host_ids for r in pending) or (probes | outbox) & host_ids:
blocked.append("Дождитесь завершения команд оборудования, отправленных через этот VPS.")
signature = {
"server": {k: host[k] for k in ("id", "name", "address", "revision")},
"arnavi": [
{k: r.get(k) for k in ("id", "revision", "endpoint", "fingerprint", "vehicle_ids")}
for r in arnavi
],
"wg": [
{
k: r.get(k)
for k in ("server_id", "endpoint", "fingerprint", "state", "revocations")
}
for r in wg
],
"vehicles": [
{
"id": r["id"],
"active": r.get("network_active"),
"paths": sorted(set(r.get("network_paths", {})) & ids),
}
for r in vehicles
],
"connections_revision": registry.revision,
"blocked": blocked,
}
digest = hashlib.sha256(json.dumps(signature, sort_keys=True).encode()).hexdigest()
plan = {
"confirmation": digest,
"name": host["name"],
"blocked": blocked,
"services": ["ARNavi"] * len(arnavi) + ["WireGuard"] * len(wg),
"vehicle_connections": len(affected),
"worker_connections": sum(
c.profile_id in profiles for w in registry.workers for c in w.connections
),
}
return plan, arnavi, wg, registry, profiles, vehicles
def preview(self, host: Document) -> Document:
with self.locked():
return self.snapshot(host)[0]
def remove(self, host: Document, confirmation: str) -> Document:
with self.locked():
plan, arnavi, wg, registry, profiles, vehicles = self.snapshot(host)
if plan["confirmation"] != confirmation:
raise ValueError(
"Настройки или подключения изменились. Проверьте удаление ещё раз."
)
if plan["blocked"]:
raise ValueError(plan["blocked"][0])
self.catalog.retain(host)
ids = {r["server_id"] for r in wg}
# Do not erase the registry while an owned OS tunnel remains active.
# The existing installer may request OS authorization on first use.
if wg:
network_client.ensure() # type: ignore[no-untyped-call] # existing OS helper
for row in wg:
result = network_client.request("forget", row["server_id"]) # type: ignore[no-untyped-call]
if result.get("removed") is not True:
raise ValueError(
"Не удалось удалить локальный туннель. Повторите удаление VPS."
)
address = str(ipaddress.ip_network(row["subnet"])[2])
listener = self.fleet.listeners.get(address)
if listener is not None:
listener.shutdown()
listener.server_close()
self.fleet.listeners.pop(address, None)
if ids:
workers = tuple(
WorkerBinding.model_validate(
{
**w.model_dump(),
"revision": w.revision + 1,
"connections": [
c for c in w.connections if c.profile_id not in profiles
],
}
)
for w in registry.workers
)
self.connections._write(
Registry(
revision=registry.revision + 1,
profiles=tuple(p for p in registry.profiles if p.id not in profiles),
workers=workers,
)
)
for vehicle in vehicles:
if set(vehicle.get("network_paths", {})) & ids:
vehicle["network_paths"] = {
k: v for k, v in vehicle["network_paths"].items() if k not in ids
}
self.fleet.save(vehicle)
previous = copy.deepcopy(self.networks.profiles)
for identity in ids:
self.networks.profiles.pop(identity, None)
try:
self.networks.save()
except Exception:
self.networks.profiles = previous
raise
for identity in ids:
self.networks.revoke_retry.pop(identity, None)
# A failed stage retains the server row. Retrying repeats only owners
# that remain; successful removal is never reported before all finish.
with self.hosts.db() as db:
db.execute("PRAGMA secure_delete=ON")
for row in arnavi:
instances = [
r[0]
for r in db.execute("SELECT instance FROM links WHERE host=?", (row["id"],))
]
for instance in instances:
for table in ("positions", "outputs", "cellular", "b2_sim_identity"):
db.execute(f"DELETE FROM {table} WHERE instance=?", (instance,))
db.execute("DELETE FROM links WHERE host=?", (row["id"],))
db.execute("DELETE FROM packets WHERE host=?", (row["id"],))
db.execute("DELETE FROM hosts WHERE id=?", (row["id"],))
self.catalog.remove(host["id"])
return {"removed": True, "id": host["id"]}
+3
View File
@@ -158,6 +158,7 @@ from k1link.web.simulation_world_provider_api import build_simulation_world_prov
from k1link.web.system_telemetry_api import build_system_telemetry_router
from k1link.web.viewer_diagnostics_api import build_viewer_diagnostics_router
from k1link.web.vps_host_api import router as vps_host_router
from k1link.web.server_catalog_api import router as server_catalog_router
from k1link.web.vps_host_api import start as start_vps_hosts
REPOSITORY_ROOT = Path(__file__).resolve().parents[3]
@@ -856,6 +857,8 @@ app.include_router(fleet_router)
app.include_router(equipment_router)
app.include_router(equipment_firmware_router)
app.include_router(vps_host_router)
app.state.system_connections_root = REPOSITORY_ROOT / ".runtime" / "system"
app.include_router(server_catalog_router)
app.include_router(installer_router)
app.include_router(rover_router)
+188
View File
@@ -0,0 +1,188 @@
"""Global VPS inventory; existing ARNavi/WireGuard authorities perform admission."""
import asyncio
import copy
import http.client
import sqlite3
import threading
from collections.abc import Callable
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.network_profiles import parse_file
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
from k1link.fleet.server_removal import ServerRemoval
from k1link.fleet.vps_transport import invitation
from k1link.web.fleet_api import local_operator
from k1link.web.server_health import ServerHealth
from k1link.web.vps_host_api import store as arnavi_store
router = APIRouter(prefix="/api/v1/system/servers", tags=["system-servers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
# Serialize this catalog's edits and imports, including the remote admission.
lock = threading.RLock()
class Details(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=80)
address: str = Field(min_length=1, max_length=253)
class Update(Details):
expected_revision: int = Field(ge=1, strict=True)
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard"]
document: str = Field(min_length=1, max_length=16384)
network_interface: str | None = Field(default=None, max_length=20)
expected_revision: int = Field(ge=1, strict=True)
class RemovalPreview(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
class Removal(RemovalPreview):
confirmation: str = Field(pattern=r"^[a-f0-9]{64}$")
def services(fleet: FleetRegistry) -> list[Document]:
# Do not silently show missing service stores as an empty inventory.
result = []
for h in arnavi_store(fleet).listing():
result.append(
dict(
kind="arnavi",
id=h["id"],
endpoint=h["endpoint"],
name="ARNavi",
state=h["state"],
last_seen=h["last_sync_at"],
details=h,
)
)
for p in fleet.network_profiles.listing(): # type: ignore[no-untyped-call] # existing network authority
result.append(
dict(
kind="wireguard",
id=p["id"],
endpoint=p["endpoint"],
name="WireGuard",
state=p["state"],
last_seen=p.get("last_verified"),
details=p,
)
)
return result
def perform(callback: Callable[[], Document]) -> Document:
try:
with lock:
return callback()
except ValueError as error:
raise HTTPException(409, str(error)) from None
except (OSError, sqlite3.Error, http.client.HTTPException):
raise HTTPException(503, "Операция VPS не завершена. Повторите действие.") from None
@router.get("")
def listing(response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return perform(lambda: {"items": ServerCatalog(fleet.root).listing(services(fleet))})
@router.get("/{key}/health")
async def health(key: str, request: Request, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
host = perform(lambda: ServerCatalog(fleet.root).find(key, services(fleet)))
observer = getattr(request.app.state, "server_health", None)
if observer is None:
observer = request.app.state.server_health = ServerHealth()
known = {(s["kind"], s["id"]) for s in host["services"]}
rows = [("arnavi", r) for r in arnavi_store(fleet).rows() if ("arnavi", r["id"]) in known]
with fleet.network_profiles.lock:
rows += [
("wireguard", copy.deepcopy(r))
for r in fleet.network_profiles.profiles.values()
if ("wireguard", r["server_id"]) in known
]
async def inspect(kind: str, row: Document) -> Document:
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
return {"items": await asyncio.gather(*(inspect(kind, row) for kind, row in rows))}
@router.post("")
def create(body: Details, fleet: Fleet) -> Document:
return perform(lambda: ServerCatalog(fleet.root).save(body.name, body.address, services(fleet)))
def removal_target(key: str, revision: int, fleet: FleetRegistry) -> Document:
host = ServerCatalog(fleet.root).find(key, services(fleet))
if host["revision"] != revision:
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
return host
@router.post("/{key}/removal")
def prepare_removal(key: str, body: RemovalPreview, request: Request, fleet: Fleet) -> Document:
return perform(
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).preview(
removal_target(key, body.expected_revision, fleet)
)
)
@router.delete("/{key}")
def remove(key: str, body: Removal, request: Request, fleet: Fleet) -> Document:
return perform(
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).remove(
removal_target(key, body.expected_revision, fleet), body.confirmation
)
)
@router.put("/{key}")
def update(key: str, body: Update, fleet: Fleet) -> Document:
return perform(
lambda: ServerCatalog(fleet.root).save(
body.name, body.address, services(fleet), key, body.expected_revision
)
)
@router.post("/{key}/services")
def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
def connect() -> Document:
catalog = ServerCatalog(fleet.root)
host = catalog.find(key, services(fleet))
if host["revision"] != body.expected_revision:
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else invitation(body.document.strip())
)
if endpoint_address(parsed["endpoint"]) != host["address"]:
raise ValueError("Приглашение выдано другим VPS. Проверьте адрес выбранного сервера.")
if body.kind == "wireguard":
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
else:
arnavi_store(fleet).pair(body.document, host["name"], [], body.network_interface)
# Membership derives from the authoritative registries: no second commit
# can orphan a successfully paired service, including after a lost response.
return catalog.find(key, services(fleet))
return perform(connect)
+59
View File
@@ -0,0 +1,59 @@
"""Read-only, bounded live observations of already trusted VPS services."""
import asyncio
import http.client
import time
from collections.abc import Callable
from k1link.fleet.server_catalog import Document
from k1link.fleet.vps_transport import request
def probe(kind: str, row: Document, verify: Callable[[Document, Document], Document]) -> Document:
try:
value = request(row, "GET", "/v1/status")
if kind == "wireguard":
verify(row, value)
elif value.get("schema") != "missioncore.vps-host/v1" or value.get("host_id") != row["id"]:
raise ValueError("Service identity mismatch")
state = "online"
except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
state = "unavailable"
return {"state": state, "checked_at": time.time()}
class ServerHealth:
"""RAM-only observations; no enrollment, tunnel apply, or profile writes."""
def __init__(self) -> None:
self.slots = asyncio.Semaphore(4)
self.cache: dict[tuple[str, ...], tuple[float, Document]] = {}
self.pending: dict[tuple[str, ...], asyncio.Task[Document]] = {}
async def observe(
self, kind: str, row: Document, verify: Callable[[Document, Document], Document]
) -> Document:
# Changes to the trusted binding must invalidate its prior observation.
key = tuple(str(x) for x in (
kind, row.get("id", row.get("server_id")), row["endpoint"],
row.get("fingerprint"), row.get("token"), row.get("network_interface"),
))
now = time.monotonic()
self.cache = {k: v for k, v in self.cache.items() if now - v[0] < 15}
if key in self.cache:
return self.cache[key][1]
task = self.pending.get(key)
if task is None:
async def run() -> Document:
try:
async with self.slots:
value = await asyncio.to_thread(probe, kind, row, verify)
if len(self.cache) >= 1024:
self.cache.pop(next(iter(self.cache)))
self.cache[key] = (time.monotonic(), value)
return value
finally:
self.pending.pop(key, None)
task = asyncio.create_task(run())
self.pending[key] = task
return await asyncio.shield(task)