feat(worker): supervise VPN connections and recover batched telemetry
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""Device identity, network attachments and verified connection selection.
|
||||
|
||||
VPN membership and application capabilities are independent. An address is
|
||||
never a device identity; changing a path never grants a new execution capability.
|
||||
"""
|
||||
@@ -0,0 +1,164 @@
|
||||
"""One installed channel, following a device's active connection.
|
||||
|
||||
Launchd/systemd owns this process. No commands are queued or retried here: only
|
||||
authenticated TCP forwarding is re-established. Every retry re-reads identity.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from .store import ConnectionError, ConnectionStore
|
||||
from .transport import SshTransport, bounded_run, validate_path
|
||||
|
||||
|
||||
def read_wireguard_profile(root: Path, network_id: str) -> dict | None:
|
||||
path = root.parent / "mission-core/fleet/networks/profiles.json"
|
||||
try:
|
||||
value = json.loads(path.read_bytes()).get(network_id)
|
||||
if isinstance(value, dict):
|
||||
# Only provider identity and public peer addresses enter this layer.
|
||||
return {key: value.get(key) for key in ("server_id", "subnet", "status")}
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def selected(store: ConnectionStore, contour_id: str):
|
||||
registry = store.read()
|
||||
worker = registry.worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == worker.active_connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Активное подключение не выбрано.")
|
||||
return worker, connection, registry.profile(connection.profile_id)
|
||||
|
||||
|
||||
def write_state(path: Path, value: dict) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
temporary = path.with_suffix(f".{os.getpid()}.tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps({**value, "observed_at": time.time(), "pid": os.getpid()}))
|
||||
os.chmod(temporary, 0o600)
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def stop_child(child: subprocess.Popen | None) -> None:
|
||||
if child is None or child.poll() is not None:
|
||||
return
|
||||
child.terminate()
|
||||
try:
|
||||
child.wait(timeout=4)
|
||||
except subprocess.TimeoutExpired:
|
||||
child.kill()
|
||||
child.wait(timeout=2)
|
||||
|
||||
|
||||
def run(root: Path, contour_id: str, channel_id: str, stop: Event) -> None:
|
||||
store = ConnectionStore(root)
|
||||
transport = SshTransport(root / "worker-bindings")
|
||||
path = root / "connection-status" / contour_id / f"{channel_id}.json"
|
||||
child = None
|
||||
while not stop.is_set():
|
||||
connection_id = None
|
||||
control_dir = None
|
||||
try:
|
||||
worker, connection, profile = selected(store, contour_id)
|
||||
connection_id = connection.id
|
||||
validate_path(
|
||||
profile,
|
||||
connection,
|
||||
wireguard_profile=read_wireguard_profile(root, profile.network_id),
|
||||
)
|
||||
binding = transport.binding(worker)
|
||||
channel = next(x for x in binding.channels if x.id == channel_id)
|
||||
arguments = transport.arguments(worker, connection)
|
||||
control_dir = tempfile.TemporaryDirectory(prefix="ndc-link-", dir="/tmp")
|
||||
control_path = str(Path(control_dir.name) / "control")
|
||||
child = subprocess.Popen(
|
||||
[
|
||||
arguments[0],
|
||||
"-o",
|
||||
"ControlMaster=yes",
|
||||
"-o",
|
||||
"ControlPath=" + control_path,
|
||||
*arguments[1:-1],
|
||||
"-N",
|
||||
"-o",
|
||||
"ExitOnForwardFailure=yes",
|
||||
*channel.arguments,
|
||||
arguments[-1],
|
||||
],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
started = time.monotonic()
|
||||
while not stop.wait(1):
|
||||
if child.poll() is not None:
|
||||
raise ConnectionError("Канал восстанавливается.")
|
||||
current, active, _ = selected(store, contour_id)
|
||||
if active.id != connection.id or current.host_key_sha256 != worker.host_key_sha256:
|
||||
break
|
||||
# Control master appears only after authenticated setup and forward binding.
|
||||
try:
|
||||
bounded_run(
|
||||
[
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
"/dev/null",
|
||||
"-S",
|
||||
control_path,
|
||||
"-O",
|
||||
"check",
|
||||
binding.ssh_alias,
|
||||
],
|
||||
timeout=2,
|
||||
)
|
||||
except ConnectionError:
|
||||
if time.monotonic() - started >= 15:
|
||||
raise
|
||||
write_state(path, {"connection_id": connection.id, "state": "connecting"})
|
||||
continue
|
||||
write_state(
|
||||
path,
|
||||
{
|
||||
"connection_id": connection.id,
|
||||
"state": "running",
|
||||
"uptime_seconds": round(time.monotonic() - started),
|
||||
},
|
||||
)
|
||||
except (OSError, ValueError, StopIteration):
|
||||
write_state(path, {"connection_id": connection_id, "state": "reconnecting"})
|
||||
stop.wait(3)
|
||||
finally:
|
||||
stop_child(child)
|
||||
child = None
|
||||
if control_dir is not None:
|
||||
control_dir.cleanup()
|
||||
write_state(path, {"connection_id": None, "state": "stopped"})
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--root", type=Path, required=True)
|
||||
parser.add_argument("--contour", required=True)
|
||||
parser.add_argument("--channel", required=True)
|
||||
args = parser.parse_args()
|
||||
stop = Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
run(args.root, args.contour, args.channel, stop)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Provider discovery, identity-bound admission and verified path selection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from .store import Connection, ConnectionError, ConnectionStore, NetworkProfile, WorkerBinding
|
||||
from .tailscale_client import ClientUnavailable, describe
|
||||
from .transport import (
|
||||
SshTransport,
|
||||
TransportBinding,
|
||||
tailscale_profile,
|
||||
tailscale_status,
|
||||
validate_path,
|
||||
)
|
||||
|
||||
|
||||
class ConnectionService:
|
||||
def __init__(
|
||||
self,
|
||||
root: Path,
|
||||
*,
|
||||
wireguard: Callable[[], list[dict]],
|
||||
tailscale: Callable[[], dict] = tailscale_status,
|
||||
transport: SshTransport | None = None,
|
||||
):
|
||||
self.store = ConnectionStore(root)
|
||||
self.transport = transport or SshTransport(root / "worker-bindings")
|
||||
self.wireguard = wireguard
|
||||
self.tailscale = tailscale
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def networks(self) -> tuple[list[NetworkProfile], dict | None, list[dict], str | None, dict]:
|
||||
profiles = []
|
||||
status = None
|
||||
message = None
|
||||
client = describe(state="unavailable")
|
||||
try:
|
||||
status = self.tailscale()
|
||||
profiles.append(tailscale_profile(status))
|
||||
client = describe(status)
|
||||
except ClientUnavailable as exc:
|
||||
message = str(exc)
|
||||
client = exc.client
|
||||
except ConnectionError as exc:
|
||||
message = str(exc)
|
||||
rows = self.wireguard()
|
||||
for row in rows:
|
||||
profiles.append(
|
||||
NetworkProfile(
|
||||
id="wg-" + hashlib.sha256(row["server_id"].encode()).hexdigest()[:24],
|
||||
name=row.get("name") or "WireGuard",
|
||||
provider="wireguard",
|
||||
network_id=row["server_id"],
|
||||
)
|
||||
)
|
||||
return profiles, status, rows, message, client
|
||||
|
||||
def catalog(self) -> dict:
|
||||
registry = self.store.read()
|
||||
profiles, status, rows, message, client = self.networks()
|
||||
peers = []
|
||||
for profile in profiles:
|
||||
if profile.provider == "tailscale" and status:
|
||||
for peer in (status.get("Peer") or {}).values():
|
||||
if peer.get("ID") and peer.get("DNSName"):
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["ID"],
|
||||
name=peer.get("HostName") or peer["DNSName"],
|
||||
online=bool(peer.get("Online")),
|
||||
)
|
||||
)
|
||||
elif profile.provider == "wireguard":
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
for peer in row.get("status", {}).get("peers", []):
|
||||
if peer.get("kind") == "worker":
|
||||
peers.append(
|
||||
dict(
|
||||
profile_id=profile.id,
|
||||
id=peer["id"],
|
||||
name=peer.get("name") or peer["id"],
|
||||
online=None,
|
||||
)
|
||||
)
|
||||
prepared = []
|
||||
for path in sorted(self.transport.root.glob("*.json")):
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
continue
|
||||
try:
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != path.stem:
|
||||
continue
|
||||
prepared.append(
|
||||
dict(
|
||||
id=binding.id,
|
||||
contour_id=binding.contour_id,
|
||||
name=binding.display_name,
|
||||
hostname=binding.expected_hostname,
|
||||
platform=binding.platform,
|
||||
)
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
known = {x.id: x for x in registry.profiles}
|
||||
known.update({x.id: x for x in profiles})
|
||||
return dict(
|
||||
revision=registry.revision,
|
||||
profiles=[x.model_dump() for x in known.values()],
|
||||
available_profile_ids=[x.id for x in profiles],
|
||||
peers=peers,
|
||||
workers=[x.model_dump() for x in registry.workers],
|
||||
prepared=prepared,
|
||||
notice=message,
|
||||
tailscale_client=client,
|
||||
)
|
||||
|
||||
def candidate(self, profile_id: str, peer_id: str) -> tuple[NetworkProfile, Connection]:
|
||||
profiles, status, rows, _, _ = self.networks()
|
||||
profile = next((x for x in profiles if x.id == profile_id), None)
|
||||
if profile is None:
|
||||
raise ConnectionError("Подключите выбранную VPN-сеть на этом компьютере.")
|
||||
row = None
|
||||
if profile.provider == "tailscale":
|
||||
peer = next(
|
||||
(x for x in (status or {}).get("Peer", {}).values() if x.get("ID") == peer_id), None
|
||||
)
|
||||
endpoint = str((peer or {}).get("DNSName", "")).rstrip(".")
|
||||
else:
|
||||
row = next(x for x in rows if x["server_id"] == profile.network_id)
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == peer_id and x.get("kind") == "worker"
|
||||
),
|
||||
None,
|
||||
)
|
||||
endpoint = (peer or {}).get("address", "")
|
||||
if not endpoint:
|
||||
raise ConnectionError("Подготовленный воркер не найден в выбранной сети.")
|
||||
connection = Connection(
|
||||
id="path-" + hashlib.sha256((profile_id + peer_id).encode()).hexdigest()[:24],
|
||||
profile_id=profile.id,
|
||||
peer_id=peer_id,
|
||||
endpoint=endpoint,
|
||||
)
|
||||
validate_path(profile, connection, status=status, wireguard_profile=row)
|
||||
return profile, connection
|
||||
|
||||
def verify(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
profile, candidate = self.candidate(connection.profile_id, connection.peer_id)
|
||||
if candidate.endpoint != connection.endpoint:
|
||||
raise ConnectionError("Адрес устройства изменился. Повторите привязку подключения.")
|
||||
return self.transport.probe(worker, connection)
|
||||
|
||||
def enroll(
|
||||
self, binding_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
# binding_id is schema-validated by the API; private files are installer-owned.
|
||||
with self.lock:
|
||||
path = self.transport.root / (binding_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Привязка устройства ещё не подготовлена.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if binding.id != binding_id:
|
||||
raise ConnectionError("Некорректная привязка устройства.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
worker = WorkerBinding(
|
||||
contour_id=binding.contour_id,
|
||||
transport_id=binding.id,
|
||||
host_key_sha256=binding.fingerprint,
|
||||
connections=(connection,),
|
||||
active_connection_id=connection.id,
|
||||
)
|
||||
self.transport.probe(worker, connection)
|
||||
self.store.enroll(profile, worker, expected_revision=revision)
|
||||
return worker
|
||||
|
||||
def attach(
|
||||
self, contour_id: str, profile_id: str, peer_id: str, revision: int
|
||||
) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
profile, connection = self.candidate(profile_id, peer_id)
|
||||
self.transport.probe(worker, connection)
|
||||
return self.store.attach(contour_id, profile, connection, expected_revision=revision)
|
||||
|
||||
def link_states(self, worker: WorkerBinding) -> list[dict]:
|
||||
binding = self.transport.binding(worker)
|
||||
states = []
|
||||
for channel in binding.channels:
|
||||
path = (
|
||||
self.store.root / "connection-status" / worker.contour_id / (channel.id + ".json")
|
||||
)
|
||||
try:
|
||||
value = json.loads(path.read_bytes())
|
||||
alive = (
|
||||
0 <= time.time() - value["observed_at"] < 6
|
||||
and value.get("connection_id") == worker.active_connection_id
|
||||
and value.get("state") == "running"
|
||||
)
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
alive = False
|
||||
states.append(dict(id=channel.id, label=channel.label, connected=alive))
|
||||
return states
|
||||
|
||||
def check(self, contour_id: str, connection_id: str) -> dict:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
identity = self.verify(worker, connection)
|
||||
return dict(
|
||||
identity=identity,
|
||||
channels=self.link_states(worker),
|
||||
active=worker.active_connection_id == connection_id,
|
||||
)
|
||||
|
||||
def activate(self, contour_id: str, connection_id: str, revision: int) -> WorkerBinding:
|
||||
with self.lock:
|
||||
worker = self.store.read().worker(contour_id)
|
||||
if worker.revision != revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
connection = next((x for x in worker.connections if x.id == connection_id), None)
|
||||
if connection is None:
|
||||
raise ConnectionError("Подключение не найдено.")
|
||||
self.verify(worker, connection)
|
||||
if worker.active_connection_id == connection_id:
|
||||
return worker
|
||||
channels = self.transport.binding(worker).channels
|
||||
if not channels:
|
||||
raise ConnectionError("Рабочие каналы ещё не установлены на этом компьютере.")
|
||||
# Supervisors follow one atomic selection; all paths retain the same host key.
|
||||
updated = self.store.select(contour_id, connection_id, expected_revision=revision)
|
||||
deadline = time.monotonic() + 18
|
||||
while time.monotonic() < deadline:
|
||||
states = self.link_states(updated)
|
||||
if states and all(x["connected"] for x in states):
|
||||
return updated
|
||||
time.sleep(0.4)
|
||||
if worker.active_connection_id is not None:
|
||||
self.store.select(
|
||||
contour_id, worker.active_connection_id, expected_revision=updated.revision
|
||||
)
|
||||
raise ConnectionError(
|
||||
"Рабочие каналы не восстановились. Возвращено прежнее подключение."
|
||||
)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Atomic operator-owned registry. No credentials or observed health on disk."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
ID = r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$"
|
||||
|
||||
|
||||
class ConnectionError(ValueError):
|
||||
"""A bounded product failure; never substitute an empty registry."""
|
||||
|
||||
|
||||
class Record(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", frozen=True)
|
||||
|
||||
|
||||
class NetworkProfile(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
name: str = Field(min_length=1, max_length=80)
|
||||
provider: Literal["tailscale", "wireguard"]
|
||||
# Provider identity, not an account password or a bootstrap credential.
|
||||
network_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
|
||||
class Connection(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
profile_id: str = Field(pattern=ID)
|
||||
endpoint: str = Field(min_length=1, max_length=253)
|
||||
# Different network paths of one host must all prove this same host key.
|
||||
peer_id: str = Field(min_length=1, max_length=180)
|
||||
|
||||
@field_validator("endpoint")
|
||||
@classmethod
|
||||
def safe_endpoint(cls, value: str) -> str:
|
||||
if re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9.:-]{0,252}", value) is None:
|
||||
raise ValueError("Invalid connection endpoint")
|
||||
return value
|
||||
|
||||
|
||||
class WorkerBinding(Record):
|
||||
contour_id: str = Field(pattern=ID)
|
||||
host_key_sha256: str = Field(pattern=r"^SHA256:[A-Za-z0-9+/]{43}$")
|
||||
# Owned transport binding, resolved server-side; never executable user input.
|
||||
transport_id: str = Field(pattern=ID)
|
||||
connections: tuple[Connection, ...] = ()
|
||||
active_connection_id: str | None = None
|
||||
revision: int = Field(default=0, ge=0)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_connections(self) -> WorkerBinding:
|
||||
ids = [x.id for x in self.connections]
|
||||
profiles = [x.profile_id for x in self.connections]
|
||||
if len(set(ids)) != len(ids) or len(set(profiles)) != len(profiles):
|
||||
raise ValueError("Duplicate device connection")
|
||||
if self.active_connection_id is not None and self.active_connection_id not in ids:
|
||||
raise ValueError("Active connection is not attached")
|
||||
return self
|
||||
|
||||
|
||||
class Registry(Record):
|
||||
schema_version: Literal["missioncore.device-connections/v1"] = (
|
||||
"missioncore.device-connections/v1"
|
||||
)
|
||||
revision: int = Field(default=0, ge=0)
|
||||
profiles: tuple[NetworkProfile, ...] = ()
|
||||
workers: tuple[WorkerBinding, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def references(self) -> Registry:
|
||||
profiles = {x.id for x in self.profiles}
|
||||
if len(profiles) != len(self.profiles):
|
||||
raise ValueError("Duplicate network profile")
|
||||
if len({x.contour_id for x in self.workers}) != len(self.workers):
|
||||
raise ValueError("Duplicate worker binding")
|
||||
for worker in self.workers:
|
||||
if any(x.profile_id not in profiles for x in worker.connections):
|
||||
raise ValueError("Connection references a missing network profile")
|
||||
return self
|
||||
|
||||
def worker(self, contour_id: str) -> WorkerBinding:
|
||||
for worker in self.workers:
|
||||
if worker.contour_id == contour_id:
|
||||
return worker
|
||||
raise ConnectionError("Воркер ещё не привязан. Подключите подготовленное устройство.")
|
||||
|
||||
def profile(self, profile_id: str) -> NetworkProfile:
|
||||
for profile in self.profiles:
|
||||
if profile.id == profile_id:
|
||||
return profile
|
||||
raise ConnectionError("Сетевой профиль отсутствует.")
|
||||
|
||||
|
||||
class ConnectionStore:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
self.path = root / "device-connections.json"
|
||||
|
||||
@contextmanager
|
||||
def locked(self):
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
lock = self.root / "device-connections.lock"
|
||||
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
os.close(fd)
|
||||
|
||||
def read(self) -> Registry:
|
||||
if self.path.is_symlink():
|
||||
raise ConnectionError("Хранилище подключений требует проверки.")
|
||||
try:
|
||||
return Registry.model_validate_json(self.path.read_bytes())
|
||||
except FileNotFoundError:
|
||||
return Registry()
|
||||
except (OSError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось прочитать подключения. Сохранённые данные не изменены."
|
||||
) from exc
|
||||
|
||||
def _write(self, registry: Registry) -> Registry:
|
||||
Registry.model_validate(registry.model_dump())
|
||||
fd, name = tempfile.mkstemp(prefix=".device-connections-", dir=self.root)
|
||||
try:
|
||||
with os.fdopen(fd, "w") as stream:
|
||||
stream.write(registry.model_dump_json(indent=2))
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(name, self.path)
|
||||
directory = os.open(self.root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
return registry
|
||||
|
||||
def enroll(
|
||||
self, profile: NetworkProfile, binding: WorkerBinding, *, expected_revision: int
|
||||
) -> Registry:
|
||||
"""Caller must first verify the transport and obtain operator enrollment."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
if current.revision != expected_revision:
|
||||
raise ConnectionError("Подключения изменились. Обновите список.")
|
||||
for existing in current.workers:
|
||||
if existing.contour_id == binding.contour_id:
|
||||
raise ConnectionError("Воркер уже привязан; повторная регистрация запрещена.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
return self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=(*current.workers, binding),
|
||||
)
|
||||
)
|
||||
|
||||
def attach(
|
||||
self,
|
||||
contour_id: str,
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
expected_revision: int,
|
||||
) -> WorkerBinding:
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection.profile_id != profile.id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
profiles = list(current.profiles)
|
||||
prior = next((x for x in profiles if x.id == profile.id), None)
|
||||
if prior is not None and prior != profile:
|
||||
raise ConnectionError("Идентичность сетевого профиля изменилась.")
|
||||
if prior is None:
|
||||
profiles.append(profile)
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"connections": [*worker.connections, connection],
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=tuple(profiles),
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
def select(
|
||||
self, contour_id: str, connection_id: str, *, expected_revision: int
|
||||
) -> WorkerBinding:
|
||||
"""Called only after a successful path transaction; never implies health."""
|
||||
with self.locked():
|
||||
current = self.read()
|
||||
worker = current.worker(contour_id)
|
||||
if worker.revision != expected_revision:
|
||||
raise ConnectionError("Подключения воркера изменились. Обновите список.")
|
||||
if connection_id not in {x.id for x in worker.connections}:
|
||||
raise ConnectionError("Подключение не подготовлено на этом устройстве.")
|
||||
updated = WorkerBinding.model_validate(
|
||||
{
|
||||
**worker.model_dump(),
|
||||
"active_connection_id": connection_id,
|
||||
"revision": worker.revision + 1,
|
||||
}
|
||||
)
|
||||
self._write(
|
||||
Registry(
|
||||
revision=current.revision + 1,
|
||||
profiles=current.profiles,
|
||||
workers=tuple(
|
||||
updated if x.contour_id == contour_id else x for x in current.workers
|
||||
),
|
||||
)
|
||||
)
|
||||
return updated
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Observe the operator's official client; authentication stays with Tailscale."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import plistlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .store import ConnectionError
|
||||
|
||||
APP_IDS = {"io.tailscale.ipn.macsys", "io.tailscale.ipn.macos"}
|
||||
MESSAGES = {
|
||||
"not_installed": "Tailscale не установлен на этом компьютере.",
|
||||
"unavailable": (
|
||||
"Tailscale установлен, но не отвечает. Откройте приложение и проверьте подключение."
|
||||
),
|
||||
"needs_login": (
|
||||
"Войдите в Tailscale. После подключения сеть и устройства появятся здесь автоматически."
|
||||
),
|
||||
"stopped": "Tailscale отключён. Включите подключение в приложении.",
|
||||
"needs_approval": (
|
||||
"Доступ этого компьютера ожидает подтверждения администратора сети Tailscale."
|
||||
),
|
||||
"starting": "Tailscale запускается. Список обновится автоматически.",
|
||||
"connected": "",
|
||||
}
|
||||
|
||||
|
||||
def installed_client(
|
||||
*, app_dirs: tuple[Path, ...] | None = None
|
||||
) -> tuple[Path | None, str | None, str | None]:
|
||||
"""Prefer the installed app's own CLI; no install, downgrade or second daemon."""
|
||||
app = None
|
||||
version = None
|
||||
if sys.platform == "darwin":
|
||||
for directory in app_dirs or (Path("/Applications"), Path.home() / "Applications"):
|
||||
candidate = directory / "Tailscale.app"
|
||||
try:
|
||||
info = plistlib.loads((candidate / "Contents/Info.plist").read_bytes())
|
||||
if info.get("CFBundleIdentifier") not in APP_IDS:
|
||||
continue
|
||||
app = candidate
|
||||
value = info.get("CFBundleShortVersionString")
|
||||
version = value[:80] if isinstance(value, str) else None
|
||||
break
|
||||
except (OSError, ValueError, plistlib.InvalidFileException):
|
||||
continue
|
||||
candidates = ([app / "Contents/MacOS/Tailscale"] if app else []) + [
|
||||
Path("/usr/local/bin/tailscale"),
|
||||
Path("/opt/homebrew/bin/tailscale"),
|
||||
]
|
||||
found = shutil.which("tailscale")
|
||||
if found:
|
||||
candidates.append(Path(found))
|
||||
binary = next((str(p) for p in candidates if p.is_file() and os.access(p, os.X_OK)), None)
|
||||
return app, binary, version
|
||||
|
||||
|
||||
def run(args: list[str], *, cli: bool = False) -> bytes:
|
||||
# Official Tailscale CLI contract: force CLI mode in non-interactive hosts.
|
||||
# Do not propagate it to the explicit native-app /usr/bin/open action.
|
||||
env = {**os.environ, "TAILSCALE_BE_CLI": "1"} if cli else None
|
||||
result = subprocess.run(args, capture_output=True, timeout=4, check=False, env=env)
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ValueError("Client command failed")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def describe(
|
||||
status: dict[str, Any] | None = None, *, state: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
app, _, version = installed_client()
|
||||
states = {
|
||||
"Running": "connected",
|
||||
"NeedsLogin": "needs_login",
|
||||
"Stopped": "stopped",
|
||||
"NeedsMachineAuth": "needs_approval",
|
||||
"Starting": "starting",
|
||||
"NoState": "starting",
|
||||
}
|
||||
backend = (status or {}).get("BackendState")
|
||||
state = state or (
|
||||
states.get(backend, "unavailable") if isinstance(backend, str) else "unavailable"
|
||||
)
|
||||
daemon_version = (status or {}).get("Version")
|
||||
return dict(
|
||||
state=state,
|
||||
message=MESSAGES[state],
|
||||
can_open=app is not None,
|
||||
version=version or (daemon_version[:80] if isinstance(daemon_version, str) else None),
|
||||
)
|
||||
|
||||
|
||||
def observe() -> tuple[dict[str, Any], dict[str, Any] | None]:
|
||||
app, binary, _ = installed_client()
|
||||
if binary is None:
|
||||
return describe(state="unavailable" if app else "not_installed"), None
|
||||
try:
|
||||
status = json.loads(run([binary, "status", "--json"], cli=True))
|
||||
if not isinstance(status, dict):
|
||||
raise ValueError("Invalid client response")
|
||||
return describe(status), status
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired):
|
||||
return describe(state="unavailable"), None
|
||||
|
||||
|
||||
class ClientUnavailable(ConnectionError):
|
||||
def __init__(self, client: dict[str, Any]):
|
||||
super().__init__(client["message"])
|
||||
self.client = client
|
||||
|
||||
|
||||
def running_status() -> dict[str, Any]:
|
||||
client, status = observe()
|
||||
if client["state"] != "connected" or status is None:
|
||||
raise ClientUnavailable(client)
|
||||
return status
|
||||
|
||||
|
||||
def open_client() -> dict[str, str]:
|
||||
app, _, _ = installed_client()
|
||||
if app is None:
|
||||
raise ConnectionError("Приложение Tailscale не найдено на этом компьютере.")
|
||||
try:
|
||||
# Reopening an existing app does not switch accounts, reset routes or force login.
|
||||
run(["/usr/bin/open", "-a", str(app)])
|
||||
client, status = observe()
|
||||
if client["state"] == "needs_login":
|
||||
url = (status or {}).get("AuthURL")
|
||||
parsed = urlsplit(url) if isinstance(url, str) and len(url) <= 2048 else None
|
||||
if (
|
||||
isinstance(url, str)
|
||||
and parsed
|
||||
and parsed.scheme == "https"
|
||||
and parsed.netloc == "login.tailscale.com"
|
||||
and parsed.path.startswith("/a/")
|
||||
and not parsed.fragment
|
||||
):
|
||||
run(["/usr/bin/open", url])
|
||||
return dict(state="opened")
|
||||
except (OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
raise ConnectionError(
|
||||
"Не удалось открыть Tailscale. Запустите его из списка приложений."
|
||||
) from exc
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Existing SSH transport behind enrolled identities and provider-owned paths.
|
||||
|
||||
SSH is an explicit migration adapter, not a VPN provider. Credentials and host
|
||||
trust belong to the installed binding. UI requests cannot supply commands,
|
||||
users, private keys or arbitrary destination addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from .store import ID, Connection, ConnectionError, NetworkProfile, Record, WorkerBinding
|
||||
from .tailscale_client import running_status
|
||||
|
||||
|
||||
class Channel(Record):
|
||||
id: str = Field(pattern=ID)
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
direction: Literal["local", "remote"]
|
||||
listen_port: int = Field(ge=1, le=65535)
|
||||
target_port: int = Field(ge=1, le=65535)
|
||||
|
||||
@property
|
||||
def arguments(self) -> list[str]:
|
||||
return [
|
||||
"-L" if self.direction == "local" else "-R",
|
||||
f"127.0.0.1:{self.listen_port}:127.0.0.1:{self.target_port}",
|
||||
]
|
||||
|
||||
|
||||
class TransportBinding(Record):
|
||||
schema_version: Literal["missioncore.worker-ssh-binding/v1"] = (
|
||||
"missioncore.worker-ssh-binding/v1"
|
||||
)
|
||||
id: str = Field(pattern=ID)
|
||||
contour_id: str = Field(pattern=ID)
|
||||
display_name: str = Field(min_length=1, max_length=80)
|
||||
expected_hostname: str = Field(min_length=1, max_length=128)
|
||||
ssh_alias: str = Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,100}$")
|
||||
platform: Literal["windows", "linux"]
|
||||
host_key: str = Field(min_length=20, max_length=4096)
|
||||
ssh_port: int = Field(default=22, ge=1, le=65535)
|
||||
channels: tuple[Channel, ...] = ()
|
||||
|
||||
@model_validator(mode="after")
|
||||
def unique_channels(self) -> TransportBinding:
|
||||
if len({x.id for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate channel")
|
||||
if len({(x.direction, x.listen_port) for x in self.channels}) != len(self.channels):
|
||||
raise ValueError("Duplicate listener")
|
||||
return self
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
try:
|
||||
algorithm, encoded = self.host_key.split()
|
||||
if algorithm != "ssh-ed25519":
|
||||
raise ValueError
|
||||
key = base64.b64decode(encoded, validate=True)
|
||||
# SSH wire blob: string algorithm + string 32-byte key.
|
||||
if len(key) != 51 or key[:19] != b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20":
|
||||
raise ValueError
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise ConnectionError("Повреждён ключ привязки воркера.") from exc
|
||||
return "SHA256:" + base64.b64encode(hashlib.sha256(key).digest()).decode().rstrip("=")
|
||||
|
||||
|
||||
def bounded_run(args: list[str], *, data: bytes | None = None, timeout: float = 8) -> bytes:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
input=data,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise ConnectionError("Устройство недоступно. Проверьте сетевое подключение.") from exc
|
||||
if result.returncode or len(result.stdout) > 4 * 1024 * 1024:
|
||||
raise ConnectionError("Подключение не подтверждено. Сохранённый профиль не изменён.")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def tailscale_status() -> dict:
|
||||
return running_status()
|
||||
|
||||
|
||||
def tailscale_profile(status: dict) -> NetworkProfile:
|
||||
network = status.get("CurrentTailnet", {}).get("MagicDNSSuffix")
|
||||
if not isinstance(network, str) or not network.endswith(".ts.net"):
|
||||
raise ConnectionError("Tailscale не подтвердил идентичность сети.")
|
||||
return NetworkProfile(
|
||||
id="ts-" + hashlib.sha256(network.encode()).hexdigest()[:24],
|
||||
name="Tailscale · " + network,
|
||||
provider="tailscale",
|
||||
network_id=network,
|
||||
)
|
||||
|
||||
|
||||
def validate_path(
|
||||
profile: NetworkProfile,
|
||||
connection: Connection,
|
||||
*,
|
||||
status: dict | None = None,
|
||||
wireguard_profile: dict | None = None,
|
||||
) -> None:
|
||||
if profile.id != connection.profile_id:
|
||||
raise ConnectionError("Подключение относится к другой сети.")
|
||||
if profile.provider == "tailscale":
|
||||
status = tailscale_status() if status is None else status
|
||||
if tailscale_profile(status).network_id != profile.network_id:
|
||||
raise ConnectionError("На этом компьютере выбрана другая сеть Tailscale.")
|
||||
peers = status.get("Peer") or {}
|
||||
peer = next((x for x in peers.values() if x.get("ID") == connection.peer_id), None)
|
||||
if not peer or not peer.get("Online"):
|
||||
raise ConnectionError("Устройство недоступно в выбранной сети Tailscale.")
|
||||
names = {str(peer.get("DNSName", "")).rstrip("."), *peer.get("TailscaleIPs", [])}
|
||||
if connection.endpoint not in names:
|
||||
raise ConnectionError("Адрес больше не принадлежит привязанному устройству.")
|
||||
else:
|
||||
row = wireguard_profile
|
||||
if not row or row.get("server_id") != profile.network_id:
|
||||
raise ConnectionError("Профиль WireGuard не найден.")
|
||||
try:
|
||||
network = ipaddress.ip_network(row["subnet"])
|
||||
if ipaddress.ip_address(connection.endpoint) not in network:
|
||||
raise ValueError
|
||||
peer = next(
|
||||
(
|
||||
x
|
||||
for x in row.get("status", {}).get("peers", [])
|
||||
if x.get("id") == connection.peer_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not peer or peer.get("address") != connection.endpoint:
|
||||
raise ValueError
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise ConnectionError(
|
||||
"Устройство ещё не зарегистрировано в этом WireGuard-профиле."
|
||||
) from exc
|
||||
|
||||
|
||||
WINDOWS_IDENTITY = (
|
||||
"[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding; "
|
||||
"$ErrorActionPreference='Stop'; "
|
||||
"@{hostname=$env:COMPUTERNAME;platform='windows'} | ConvertTo-Json -Compress"
|
||||
)
|
||||
LINUX_IDENTITY = (
|
||||
"python3 -c 'import json,socket; "
|
||||
'print(json.dumps(dict(hostname=socket.gethostname(),platform="linux")))\''
|
||||
)
|
||||
|
||||
|
||||
class SshTransport:
|
||||
def __init__(self, root: Path):
|
||||
self.root = root
|
||||
|
||||
def binding(self, worker: WorkerBinding) -> TransportBinding:
|
||||
path = self.root / (worker.transport_id + ".json")
|
||||
if path.is_symlink() or path.stat().st_mode & 0o077:
|
||||
raise ConnectionError("Права привязки воркера требуют проверки.")
|
||||
binding = TransportBinding.model_validate_json(path.read_bytes())
|
||||
if (
|
||||
binding.id != worker.transport_id
|
||||
or binding.contour_id != worker.contour_id
|
||||
or binding.fingerprint != worker.host_key_sha256
|
||||
):
|
||||
raise ConnectionError("Идентичность воркера изменилась. Переключение запрещено.")
|
||||
return binding
|
||||
|
||||
def arguments(self, worker: WorkerBinding, connection: Connection) -> list[str]:
|
||||
binding = self.binding(worker)
|
||||
known = self.root / (binding.id + ".known_hosts")
|
||||
expected = (binding.id + " " + binding.host_key + "\n").encode()
|
||||
if known.is_symlink() or known.read_bytes() != expected:
|
||||
raise ConnectionError("Ключ подключения не совпал с привязкой воркера.")
|
||||
return [
|
||||
"/usr/bin/ssh",
|
||||
"-F",
|
||||
str(Path.home() / ".ssh/config"),
|
||||
"-o",
|
||||
"BatchMode=yes",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=yes",
|
||||
"-o",
|
||||
"UserKnownHostsFile=" + str(known),
|
||||
"-o",
|
||||
"GlobalKnownHostsFile=/dev/null",
|
||||
"-o",
|
||||
"HostKeyAlias=" + binding.id,
|
||||
"-o",
|
||||
"HostKeyAlgorithms=ssh-ed25519",
|
||||
"-o",
|
||||
"UpdateHostKeys=no",
|
||||
"-o",
|
||||
"ForwardAgent=no",
|
||||
"-o",
|
||||
"PermitLocalCommand=no",
|
||||
"-o",
|
||||
"ControlMaster=no",
|
||||
"-o",
|
||||
"ControlPath=none",
|
||||
"-o",
|
||||
"RequestTTY=no",
|
||||
"-o",
|
||||
"ProxyCommand=none",
|
||||
"-o",
|
||||
"ProxyJump=none",
|
||||
"-o",
|
||||
"ConnectTimeout=8",
|
||||
"-o",
|
||||
"ServerAliveInterval=10",
|
||||
"-o",
|
||||
"ServerAliveCountMax=3",
|
||||
"-o",
|
||||
"HostName=" + connection.endpoint,
|
||||
"-p",
|
||||
str(binding.ssh_port),
|
||||
binding.ssh_alias,
|
||||
]
|
||||
|
||||
def execute(self, worker: WorkerBinding, connection: Connection, command: str) -> bytes:
|
||||
# Commands are constants owned by this adapter, never request fields.
|
||||
binding = self.binding(worker)
|
||||
if binding.platform == "windows":
|
||||
command = (
|
||||
"powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand "
|
||||
+ base64.b64encode(command.encode("utf-16le")).decode()
|
||||
)
|
||||
return bounded_run(
|
||||
[
|
||||
*self.arguments(worker, connection)[:-1],
|
||||
"-o",
|
||||
"ClearAllForwardings=yes",
|
||||
binding.ssh_alias,
|
||||
command,
|
||||
],
|
||||
timeout=12,
|
||||
)
|
||||
|
||||
def probe(self, worker: WorkerBinding, connection: Connection) -> dict:
|
||||
binding = self.binding(worker)
|
||||
command = WINDOWS_IDENTITY if binding.platform == "windows" else LINUX_IDENTITY
|
||||
try:
|
||||
value = json.loads(self.execute(worker, connection, command))
|
||||
if (
|
||||
value.get("platform") != binding.platform
|
||||
or value.get("hostname", "").casefold() != binding.expected_hostname.casefold()
|
||||
):
|
||||
raise ValueError
|
||||
except (ValueError, OSError) as exc:
|
||||
raise ConnectionError("Устройство не подтвердило свою конфигурацию.") from exc
|
||||
return {
|
||||
"hostname": value["hostname"],
|
||||
"platform": value["platform"],
|
||||
"host_key_sha256": binding.fingerprint,
|
||||
}
|
||||
@@ -391,7 +391,7 @@ class _ValidatedClaim:
|
||||
|
||||
|
||||
class ObservatoryWorkerAgent:
|
||||
"""Runs at most one sealed recorded-job claim at a time on Worker 006."""
|
||||
"""Runs one sealed job at a time under the enrolled Worker identity."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -401,6 +401,7 @@ class ObservatoryWorkerAgent:
|
||||
claim_request_id_factory: Callable[[], str] | None = None,
|
||||
heartbeat_interval_seconds: float | None = None,
|
||||
heartbeat_stop_timeout_seconds: float = 5.0,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
) -> None:
|
||||
if heartbeat_interval_seconds is not None and not (
|
||||
0.01 <= heartbeat_interval_seconds <= 300.0
|
||||
@@ -408,9 +409,12 @@ class ObservatoryWorkerAgent:
|
||||
raise ValueError("Worker heartbeat interval is invalid")
|
||||
if not 0.1 <= heartbeat_stop_timeout_seconds <= 300.0:
|
||||
raise ValueError("Worker heartbeat stop timeout is invalid")
|
||||
self._contour_id = validate_worker_contour_id(contour_id)
|
||||
self._transport = transport
|
||||
self._executors = executors
|
||||
self._claim_request_id_factory = claim_request_id_factory or _default_claim_request_id
|
||||
self._claim_request_id_factory = claim_request_id_factory or (
|
||||
lambda: _default_claim_request_id(self._contour_id)
|
||||
)
|
||||
self._heartbeat_interval_seconds = heartbeat_interval_seconds
|
||||
self._heartbeat_stop_timeout_seconds = heartbeat_stop_timeout_seconds
|
||||
self._cycle_lock = threading.Lock()
|
||||
@@ -419,7 +423,7 @@ class ObservatoryWorkerAgent:
|
||||
"""Claim, validate, execute, and seal one durable job if available."""
|
||||
|
||||
if not self._cycle_lock.acquire(blocking=False):
|
||||
raise ObservatoryWorkerAgentBusyError("Worker 006 already owns an active claim cycle")
|
||||
raise ObservatoryWorkerAgentBusyError("Worker already owns an active claim cycle")
|
||||
try:
|
||||
return self._run_once_locked()
|
||||
finally:
|
||||
@@ -430,7 +434,7 @@ class ObservatoryWorkerAgent:
|
||||
if _CLAIM_REQUEST_ID.fullmatch(claim_request_id) is None:
|
||||
raise ValueError("Worker claim request id is invalid")
|
||||
payload = self._transport.claim_next(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
claim_request_id=claim_request_id,
|
||||
supported_executor_identities=self._executors.supported_identities,
|
||||
)
|
||||
@@ -442,6 +446,7 @@ class ObservatoryWorkerAgent:
|
||||
try:
|
||||
claim = _validate_claim(
|
||||
payload,
|
||||
contour_id=self._contour_id,
|
||||
claim_request_id=claim_request_id,
|
||||
supported_executor_identities=self._executors.supported_identities,
|
||||
)
|
||||
@@ -457,11 +462,11 @@ class ObservatoryWorkerAgent:
|
||||
except ObservatoryWorkerExecutorUnavailableError:
|
||||
failure_code = "executor-not-allowlisted"
|
||||
acknowledgement = self._transport.fail(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
error_code=failure_code,
|
||||
message="Exact executor identity is not installed on Worker 006.",
|
||||
message="Exact executor identity is not installed on this Worker.",
|
||||
)
|
||||
_validate_transition_acknowledgement(
|
||||
acknowledgement,
|
||||
@@ -476,7 +481,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
|
||||
started_payload = self._transport.start(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
)
|
||||
@@ -495,6 +500,7 @@ class ObservatoryWorkerAgent:
|
||||
active_job = _seal_job(started)
|
||||
heartbeat = _ClaimHeartbeat(
|
||||
transport=self._transport,
|
||||
contour_id=self._contour_id,
|
||||
job=active_job,
|
||||
claim_token=claim.claim_token,
|
||||
interval_seconds=(
|
||||
@@ -544,7 +550,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
failure_code = "executor-error"
|
||||
acknowledgement = self._transport.fail(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
error_code=failure_code,
|
||||
@@ -572,7 +578,7 @@ class ObservatoryWorkerAgent:
|
||||
)
|
||||
|
||||
acknowledgement = self._transport.succeed(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=claim.job.job_id,
|
||||
claim_token=claim.claim_token,
|
||||
result_id=result.result_id,
|
||||
@@ -614,9 +620,11 @@ class _ClaimHeartbeat:
|
||||
interval_seconds: float,
|
||||
stop_timeout_seconds: float,
|
||||
clock: Callable[[], float] = time.monotonic,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
) -> None:
|
||||
if interval_seconds <= 0:
|
||||
raise ValueError("Worker heartbeat interval must be positive")
|
||||
self._contour_id = validate_worker_contour_id(contour_id)
|
||||
self._transport = transport
|
||||
self._job = job
|
||||
self._claim_token = claim_token
|
||||
@@ -671,7 +679,7 @@ class _ClaimHeartbeat:
|
||||
"Worker heartbeat lease budget expired"
|
||||
)
|
||||
acknowledgement = self._transport.renew_claim(
|
||||
claimant_id=WORKER_006_CONTOUR_ID,
|
||||
claimant_id=self._contour_id,
|
||||
job_id=self._job.job_id,
|
||||
claim_token=self._claim_token,
|
||||
claim_generation=self._job.claim_generation,
|
||||
@@ -756,19 +764,20 @@ def _validate_claim(
|
||||
payload: Mapping[str, object],
|
||||
*,
|
||||
claim_request_id: str,
|
||||
contour_id: str = WORKER_006_CONTOUR_ID,
|
||||
supported_executor_identities: tuple[ObservatoryWorkerExecutorIdentity, ...],
|
||||
) -> _ValidatedClaim:
|
||||
try:
|
||||
claim = _RecordedClaimPayload.model_validate(dict(payload))
|
||||
if claim.claim_request_id != claim_request_id:
|
||||
raise ObservatoryWorkerClaimRejectedError("Worker claim request identity changed")
|
||||
if claim.claimant_id != WORKER_006_CONTOUR_ID:
|
||||
if claim.claimant_id != contour_id:
|
||||
raise ObservatoryWorkerClaimRejectedError("Worker claim belongs to another claimant")
|
||||
expected_claim_request_sha256 = _sha256_document(
|
||||
{
|
||||
"schema_version": OBSERVATORY_RECORDED_CLAIM_SCHEMA,
|
||||
"claim_request_id": claim_request_id,
|
||||
"claimant_id": WORKER_006_CONTOUR_ID,
|
||||
"claimant_id": contour_id,
|
||||
"supported_executor_identities": [
|
||||
identity.as_dict() for identity in sorted(supported_executor_identities)
|
||||
],
|
||||
@@ -963,8 +972,17 @@ def _validate_transition_acknowledgement(
|
||||
return acknowledgement
|
||||
|
||||
|
||||
def _default_claim_request_id() -> str:
|
||||
return f"worker-006:{uuid4().hex}"
|
||||
def validate_worker_contour_id(value: str) -> str:
|
||||
if (
|
||||
not isinstance(value, str)
|
||||
or re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?", value) is None
|
||||
):
|
||||
raise ValueError("Worker contour identity is invalid")
|
||||
return value
|
||||
|
||||
|
||||
def _default_claim_request_id(contour_id: str = WORKER_006_CONTOUR_ID) -> str:
|
||||
return f"{contour_id}:{uuid4().hex}"
|
||||
|
||||
|
||||
def _default_heartbeat_interval(job: SealedObservatoryRecordedJob) -> float:
|
||||
|
||||
@@ -59,6 +59,7 @@ from k1link.observatory.worker_agent import (
|
||||
ObservatoryWorkerTransientTransportError,
|
||||
ObservatoryWorkerTransport,
|
||||
SealedObservatoryRecordedJob,
|
||||
validate_worker_contour_id,
|
||||
)
|
||||
from k1link.observatory.worker_source_cache import WorkerSourceCache, WorkerSourceCacheError
|
||||
|
||||
@@ -177,8 +178,7 @@ class ObservatoryWorkerHttpGateway(ObservatoryWorkerTransport):
|
||||
self._base_url = _validated_base_url(base_url)
|
||||
if _TOKEN.fullmatch(bearer_token) is None:
|
||||
raise ValueError("Worker bearer credential format is invalid")
|
||||
if contour_id != WORKER_006_CONTOUR_ID:
|
||||
raise ValueError("portable Worker gateway is pinned to Worker 006")
|
||||
self.contour_id = validate_worker_contour_id(contour_id)
|
||||
if not 1 <= timeout_seconds <= 300:
|
||||
raise ValueError("Worker HTTP timeout is invalid")
|
||||
self._headers = {
|
||||
@@ -865,9 +865,8 @@ class ObservatoryWorkerHttpGateway(ObservatoryWorkerTransport):
|
||||
_CLAIM_GENERATION_HEADER: str(context.claim_generation),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _require_claimant(claimant_id: str) -> None:
|
||||
if claimant_id != WORKER_006_CONTOUR_ID:
|
||||
def _require_claimant(self, claimant_id: str) -> None:
|
||||
if claimant_id != self.contour_id:
|
||||
raise ObservatoryWorkerHttpError("Worker claimant identity changed")
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -142,8 +142,12 @@ class ObservatoryWorkerServiceConfiguration:
|
||||
transport_backoff_seconds: float = DEFAULT_OBSERVATORY_WORKER_TRANSPORT_BACKOFF_SECONDS
|
||||
max_consecutive_transport_failures: int = DEFAULT_OBSERVATORY_WORKER_MAX_TRANSPORT_FAILURES
|
||||
source_cache_root: Path | None = None
|
||||
contour_id: str = "worker-006"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
from k1link.observatory.worker_agent import validate_worker_contour_id
|
||||
|
||||
validate_worker_contour_id(self.contour_id)
|
||||
_validate_worker_base_url(self.base_url)
|
||||
_absolute_path(self.bearer_token_file, "Worker bearer token file")
|
||||
_absolute_path(self.work_root, "Worker work root")
|
||||
@@ -177,6 +181,7 @@ class ObservatoryWorkerServiceConfiguration:
|
||||
OBSERVATORY_WORKER_BASE_URL_ENV,
|
||||
DEFAULT_OBSERVATORY_WORKER_BASE_URL,
|
||||
),
|
||||
contour_id=values.get("MISSIONCORE_CONTOUR_ID", "worker-006"),
|
||||
bearer_token_file=token_file,
|
||||
work_root=work_root,
|
||||
source_cache_root=(
|
||||
@@ -271,6 +276,7 @@ def compose_installed_observatory_worker_service(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -283,7 +289,9 @@ def compose_installed_observatory_worker_service(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -309,6 +317,7 @@ def compose_installed_observatory_worker_service_from_builders(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -325,7 +334,9 @@ def compose_installed_observatory_worker_service_from_builders(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
if gateway is not None:
|
||||
@@ -351,6 +362,7 @@ def compose_installed_observatory_worker_service_from_packages(
|
||||
try:
|
||||
gateway = ObservatoryWorkerHttpGateway(
|
||||
base_url=configuration.base_url,
|
||||
contour_id=configuration.contour_id,
|
||||
bearer_token=bearer_token,
|
||||
work_root=configuration.work_root,
|
||||
transport=http_transport,
|
||||
@@ -368,7 +380,9 @@ def compose_installed_observatory_worker_service_from_packages(
|
||||
return InstalledObservatoryWorkerService(
|
||||
configuration=configuration,
|
||||
gateway=gateway,
|
||||
agent=ObservatoryWorkerAgent(transport=gateway, executors=executors),
|
||||
agent=ObservatoryWorkerAgent(
|
||||
transport=gateway, executors=executors, contour_id=configuration.contour_id
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
if gateway is not None:
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user