"""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()