feat(worker): supervise VPN connections and recover batched telemetry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:10:37 +03:00
parent fe5900ff3b
commit ad5a929e06
46 changed files with 2996 additions and 640 deletions
+4
View File
@@ -106,6 +106,7 @@ from k1link.simulation.projects import SimulationProjectService, SimulationProje
from k1link.web.ai_polygon_api import build_ai_polygon_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.compute_connection_api import build_compute_connection_router
from k1link.web.device_plugin_composition import load_installed_device_plugins
from k1link.web.environment_api import build_environment_router
from k1link.web.equipment_firmware_api import router as equipment_firmware_router
@@ -1156,6 +1157,9 @@ app.include_router(
)
)
app.include_router(build_simulation_world_provider_router())
app.include_router(build_compute_connection_router(
root_provider=lambda: REPOSITORY_ROOT / ".runtime" / "system",
))
app.include_router(
build_simulation_projects_router(
store=simulation_project_store,
+179
View File
@@ -0,0 +1,179 @@
"""Local operator API. Never accepts credentials, shell commands or arbitrary IPs."""
from __future__ import annotations
import secrets
import threading
import time
from collections.abc import Callable
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException
from pydantic import Field
from k1link.compute_connections.service import ConnectionService
from k1link.compute_connections.store import ID, ConnectionError, Record
from k1link.compute_connections.tailscale_client import open_client
from k1link.web.fleet_api import local_operator
class Attach(Record):
profile_id: str = Field(pattern=ID)
peer_id: str = Field(min_length=1, max_length=180)
revision: int = Field(ge=0)
class Enroll(Attach):
binding_id: str = Field(pattern=ID)
class SelectConnection(Record):
connection_id: str = Field(pattern=ID)
revision: int = Field(ge=0)
class Shutdown(Record):
confirmation: str = Field(min_length=43, max_length=43)
def build_compute_connection_router(root_provider: Callable[[], Path]) -> APIRouter:
router = APIRouter(prefix="/api/v1/system/connections", tags=["compute-connections"])
holder: list[ConnectionService] = []
confirmations: dict[str, tuple] = {}
initialization = threading.Lock()
operator_dependency = Depends(local_operator)
def service(fleet=operator_dependency) -> ConnectionService:
with initialization:
if not holder:
def profiles():
with fleet.network_profiles.lock:
return [
{key: row.get(key) for key in ("server_id", "name", "subnet", "status")}
for row in fleet.network_profiles.profiles.values()
]
holder.append(ConnectionService(root_provider(), wireguard=profiles))
return holder[0]
def operation(function, *args):
try:
return function(*args)
except ConnectionError as exc:
raise HTTPException(409, str(exc)) from None
except (OSError, ValueError, KeyError):
raise HTTPException(
409, "Не удалось подтвердить подключение. Сохранённая привязка защищена."
) from None
service_dependency = Depends(service)
@router.get("")
def catalog(manager=service_dependency):
return operation(manager.catalog)
@router.post("/tailscale/open", dependencies=[operator_dependency])
def open_tailscale():
return operation(open_client)
@router.post("/enroll")
def enroll(body: Enroll, manager=service_dependency):
worker = operation(
manager.enroll, body.binding_id, body.profile_id, body.peer_id, body.revision
)
return worker
@router.post("/{contour_id}/attach")
def attach(contour_id: str, body: Attach, manager=service_dependency):
return operation(manager.attach, contour_id, body.profile_id, body.peer_id, body.revision)
@router.post("/{contour_id}/activate")
def activate(contour_id: str, body: SelectConnection, manager=service_dependency):
return operation(manager.activate, contour_id, body.connection_id, body.revision)
@router.get("/{contour_id}/status")
def status(contour_id: str, manager=service_dependency):
worker = operation(lambda: manager.store.read().worker(contour_id))
return dict(channels=operation(manager.link_states, worker))
@router.post("/{contour_id}/check")
def check(contour_id: str, body: SelectConnection, manager=service_dependency):
return operation(manager.check, contour_id, body.connection_id)
@router.post("/{contour_id}/power/prepare")
def prepare_shutdown(contour_id: str, manager=service_dependency):
with manager.lock:
worker = operation(lambda: manager.store.read().worker(contour_id))
binding = manager.transport.binding(worker)
if binding.platform != "windows":
raise HTTPException(
409, "Управление питанием ещё не подготовлено для этого устройства."
)
operation(manager.check, contour_id, worker.active_connection_id)
now = time.monotonic()
for key, value in list(confirmations.items()):
if now - value[0] > 30 or value[1] == contour_id:
confirmations.pop(key, None)
token = secrets.token_urlsafe(32)
confirmations[token] = (
now,
worker.contour_id,
worker.revision,
worker.active_connection_id,
worker.host_key_sha256,
)
return dict(confirmation=token, expires_in_seconds=30)
@router.post("/{contour_id}/power/shutdown")
def shutdown(contour_id: str, body: Shutdown, manager=service_dependency):
with manager.lock:
confirmation = confirmations.pop(body.confirmation, None)
worker = operation(lambda: manager.store.read().worker(contour_id))
identity = (
worker.contour_id,
worker.revision,
worker.active_connection_id,
worker.host_key_sha256,
)
if (
not confirmation
or time.monotonic() - confirmation[0] > 30
or confirmation[1:] != identity
):
raise HTTPException(
409,
"Подтверждение истекло или подключение изменилось. "
"Проверьте устройство ещё раз.",
)
connection = next(x for x in worker.connections if x.id == worker.active_connection_id)
operation(manager.verify, worker, connection)
if time.monotonic() - confirmation[0] > 30:
raise HTTPException(409, "Подтверждение истекло. Повторите проверку.")
# Single attempt, no durable queue and no retry after disconnect.
command = (
"$ErrorActionPreference='Stop'; & shutdown.exe /s /t 5; "
"if ($LASTEXITCODE -ne 0) {exit 1}; Write-Output 'accepted'"
)
try:
result = manager.transport.execute(worker, connection, command)
except ConnectionError:
raise HTTPException(
409,
"Ответ не получен. Команда могла дойти; "
"повторно автоматически не отправляется.",
) from None
if result.strip() != b"accepted":
raise HTTPException(
409, "Воркер не подтвердил команду. Повторная отправка не выполняется."
)
return dict(
state="accepted",
message=(
"Воркер принял команду выключения. "
"Для включения потребуется доступ к компьютеру."
),
)
return router
+27 -2
View File
@@ -197,7 +197,32 @@ class ComputeContourStore:
def list_contours(self) -> list[ComputeContour]:
with self._lock:
return self._read_unlocked()
return self._with_connections(self._read_unlocked())
def _with_connections(self, contours: list[ComputeContour]) -> list[ComputeContour]:
"""Project enrolled identities; the connection registry owns routing."""
from k1link.compute_connections.store import ConnectionStore
from k1link.compute_connections.transport import SshTransport
registry = ConnectionStore(self.root).read()
transport = SshTransport(self.root / "worker-bindings")
rows = {item.contour_id: item for item in contours}
for worker in registry.workers:
binding = transport.binding(worker)
connection = next(
(x for x in worker.connections if x.id == worker.active_connection_id), None
)
prior = rows.get(worker.contour_id)
fields = prior.model_dump() if prior else {
"contour_id": worker.contour_id, "agent_id": worker.contour_id,
"display_name": binding.display_name,
}
rows[worker.contour_id] = ComputeContour.model_validate({
**fields, "expected_node_id": binding.expected_hostname,
"platform": binding.platform, "ssh_port": binding.ssh_port,
"address": connection.endpoint if connection else "",
})
return list(rows.values())
def create(self, request: ComputeContourCreate) -> ComputeContour:
with self._lock:
@@ -230,7 +255,7 @@ class ComputeContourStore:
def update(self, contour_id: str, request: ComputeContourPut) -> ComputeContour:
with self._lock:
contours = self._read_unlocked()
contours = self._with_connections(self._read_unlocked())
for index, current in enumerate(contours):
if current.contour_id != contour_id:
continue
+13 -2
View File
@@ -1105,6 +1105,13 @@ class WorkerTelemetryService:
memory = _mapping(raw.get("memory"))
memory_total = _number(memory.get("total_bytes"))
memory_free = _number(memory.get("free_bytes"))
if (
_number(_mapping(raw.get("cpu")).get("load_percent")) is None
or memory_total is None
or memory_free is None
):
# A pipeline heartbeat proves identity, not current host telemetry.
public_probe["error_code"] = "telemetry-host-incomplete"
memory_used = (
memory_total - memory_free
if memory_total is not None and memory_free is not None
@@ -1137,7 +1144,11 @@ class WorkerTelemetryService:
raw_observed_at if isinstance(raw_observed_at, str) else _utc_now()
)
receive_rate, send_rate = self._latest_network_rates
if observed_at != self._last_history_observed_at:
if not interfaces:
self._previous_network = None
self._latest_network_rates = (None, None)
receive_rate, send_rate = None, None
elif observed_at != self._last_history_observed_at:
receive_rate = None
send_rate = None
if self._previous_network is not None:
@@ -1196,7 +1207,7 @@ class WorkerTelemetryService:
"sent_bytes": sent,
"receive_bytes_per_second": receive_rate,
"send_bytes_per_second": send_rate,
},
} if interfaces else None,
}
history_row = {
"observed_at_utc": observed_at,