feat(network): verify selected uplinks, roll back failures and manage NetBird policy
This commit is contained in:
@@ -28,11 +28,18 @@ SAFE_FLAGS = [
|
||||
"--disable-ipv6",
|
||||
"--allow-server-ssh=false",
|
||||
"--allow-remote-jobs=false",
|
||||
"--network-monitor=true",
|
||||
"--disable-auto-connect=false",
|
||||
]
|
||||
|
||||
|
||||
def safe_flags():
|
||||
# The native engine reconnects transports independently. The optional monitor
|
||||
# rebuilds the whole engine on route churn (including unrelated macOS VPNs).
|
||||
# Preserve the enrolled profile and avoid these collateral disconnects.
|
||||
monitor = "false" if platform.system() in ("Linux", "FreeBSD", "Darwin") else "true"
|
||||
return [*SAFE_FLAGS, "--network-monitor=" + monitor]
|
||||
|
||||
|
||||
def server_url(value: str) -> str:
|
||||
try:
|
||||
parsed = urlsplit(value.strip())
|
||||
@@ -348,7 +355,7 @@ class Client:
|
||||
"--no-browser",
|
||||
"--log-file",
|
||||
"console",
|
||||
*SAFE_FLAGS,
|
||||
*safe_flags(),
|
||||
],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
"""Versioned Mac profile policy migration through the official NetBird CLI.
|
||||
|
||||
Read private configuration only to establish ownership/readback. Never rewrite
|
||||
it, change routes, restart launchd, create a profile, or touch peer credentials.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import pwd
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
VERSION = "1.0.2"
|
||||
ROOT = Path("/var/lib/netbird")
|
||||
BINARY = "/usr/local/bin/netbird"
|
||||
RECEIPT = ROOT / "missioncore-monitor-policy.json"
|
||||
|
||||
|
||||
def fingerprint(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def invoke(*args):
|
||||
environment = {k: v for k, v in os.environ.items() if not k.startswith(("NB_", "SUDO_"))}
|
||||
active = json.loads((ROOT / "active_profile.json").read_text())
|
||||
owner = pwd.getpwnam(active["username"])
|
||||
environment["HOME"] = owner.pw_dir
|
||||
result = subprocess.run(
|
||||
[BINARY, *args, "--log-file", "console"],
|
||||
user=owner.pw_uid,
|
||||
group=owner.pw_gid,
|
||||
extra_groups=[],
|
||||
env=environment,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=45,
|
||||
)
|
||||
if result.returncode:
|
||||
error_file = ROOT / "missioncore-monitor-cli-error.json"
|
||||
fd = os.open(error_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump(
|
||||
dict(exit_code=result.returncode, stdout=result.stdout, stderr=result.stderr), f
|
||||
)
|
||||
raise RuntimeError("Official NetBird CLI failed (exit " + str(result.returncode) + ")")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def config():
|
||||
active = json.loads((ROOT / "active_profile.json").read_text())
|
||||
if not re.fullmatch(r"[a-f0-9]{32}", active.get("name", "")) or not re.fullmatch(
|
||||
r"[A-Za-z0-9_-]+", active.get("username", "")
|
||||
):
|
||||
raise ValueError("Unsupported active profile identity")
|
||||
path = ROOT / active["username"] / (active["name"] + ".json")
|
||||
if path.is_symlink() or path.stat().st_uid != 0 or path.stat().st_size > 262144:
|
||||
raise ValueError("Foreign profile file")
|
||||
value = json.loads(path.read_text())
|
||||
if value.get("Name") != "mission-core" or type(value.get("NetworkMonitor")) is not bool:
|
||||
raise ValueError("Not the owned mission-core profile")
|
||||
return active, value
|
||||
|
||||
|
||||
def status():
|
||||
return json.loads(invoke("status", "--json"))
|
||||
|
||||
|
||||
def plan(owner, rollback=False):
|
||||
if os.geteuid() != 0 or platform.system() != "Darwin":
|
||||
raise ValueError("Run the owned package with administrator authorization on macOS")
|
||||
saved = json.loads(owner.read_text())
|
||||
server = saved["server_url"]
|
||||
url = urlsplit(server)
|
||||
if url.scheme != "https" or url.username or url.password or not url.hostname:
|
||||
raise ValueError("Invalid saved management URL")
|
||||
active, before = config()
|
||||
observed = status()
|
||||
if (
|
||||
observed.get("daemonVersion") != "0.82.0"
|
||||
or observed.get("profileName") != "mission-core"
|
||||
or observed.get("management", {}).get("url") != server
|
||||
or not observed.get("management", {}).get("connected")
|
||||
or not observed.get("signal", {}).get("connected")
|
||||
):
|
||||
raise ValueError("Owned supported network must be connected before migration")
|
||||
desired = False
|
||||
if rollback:
|
||||
receipt = json.loads(RECEIPT.read_text())
|
||||
if (
|
||||
receipt.get("state") != "ready"
|
||||
or receipt["plan"]["active"] != active
|
||||
or fingerprint(before) != receipt["after_sha256"]
|
||||
):
|
||||
raise ValueError("Profile changed after migration; rollback refused")
|
||||
desired = receipt["plan"]["before"]
|
||||
payload = dict(
|
||||
schema="missioncore.netbird-macos-policy/v1",
|
||||
version=VERSION,
|
||||
active=active,
|
||||
server_url=server,
|
||||
before=before["NetworkMonitor"],
|
||||
after=desired,
|
||||
rollback=rollback,
|
||||
changed=before["NetworkMonitor"] != desired,
|
||||
profile_sha256=fingerprint(before),
|
||||
artifact_sha256=hashlib.sha256(Path(sys.argv[0]).read_bytes()).hexdigest(),
|
||||
preserve=["peer_identity", "IP", "routes", "DNS", "management", "native_reconnect"],
|
||||
)
|
||||
payload["plan_sha256"] = fingerprint(payload)
|
||||
return payload
|
||||
|
||||
|
||||
def save(value):
|
||||
fd = os.open(RECEIPT, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
json.dump(value, f, indent=2)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
|
||||
|
||||
def await_health(before):
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
current = status()
|
||||
if current.get("management", {}).get("connected") and current.get("signal", {}).get(
|
||||
"connected"
|
||||
):
|
||||
for key in ("profileName", "publicKey", "netbirdIp"):
|
||||
if current.get(key) != before.get(key):
|
||||
raise ValueError("NetBird identity changed")
|
||||
if current["management"]["url"] != before["management"]["url"]:
|
||||
raise ValueError("Management identity changed")
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("NetBird did not reconnect")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def apply(owner, expected, rollback=False):
|
||||
proposal = plan(owner, rollback)
|
||||
if proposal["plan_sha256"] != expected:
|
||||
raise ValueError("Plan changed; inspect a fresh plan")
|
||||
active, before = config()
|
||||
previous_status = status()
|
||||
if not proposal["changed"]:
|
||||
return dict(state="ready", changed=False)
|
||||
try:
|
||||
# 0.82.0 ignores up flags while already connected. Use the verified
|
||||
# existing profile ID under its owner to request its native reconnect.
|
||||
invoke(
|
||||
"up",
|
||||
"--profile",
|
||||
active["name"],
|
||||
"--network-monitor=" + str(proposal["after"]).lower(),
|
||||
"--no-browser",
|
||||
)
|
||||
after_active, after = config()
|
||||
if after_active != active or after != {**before, "NetworkMonitor": proposal["after"]}:
|
||||
raise ValueError(
|
||||
"Profile readback mismatch: "
|
||||
+ ",".join(
|
||||
sorted(
|
||||
k
|
||||
for k in set(before) | set(after)
|
||||
if after.get(k) != {**before, "NetworkMonitor": proposal["after"]}.get(k)
|
||||
)
|
||||
)
|
||||
)
|
||||
await_health(previous_status)
|
||||
except Exception as error:
|
||||
try:
|
||||
if config() != (active, before):
|
||||
invoke(
|
||||
"up",
|
||||
"--profile",
|
||||
active["name"],
|
||||
"--network-monitor=" + str(proposal["before"]).lower(),
|
||||
"--no-browser",
|
||||
)
|
||||
if config() != (active, before):
|
||||
raise ValueError("Rollback identity/readback changed")
|
||||
await_health(previous_status)
|
||||
save(dict(plan=proposal, state="rolled_back", error_type=type(error).__name__))
|
||||
except Exception:
|
||||
save(dict(plan=proposal, state="rollback_failed", error_type=type(error).__name__))
|
||||
raise
|
||||
raise
|
||||
save(
|
||||
dict(
|
||||
plan=proposal,
|
||||
state="rolled_back" if rollback else "ready",
|
||||
after_sha256=fingerprint(after),
|
||||
)
|
||||
)
|
||||
return dict(
|
||||
state="ready", changed=True, network_monitor=proposal["after"], identity_preserved=True
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Owned Mission Core Mac NetBird policy migration")
|
||||
parser.add_argument("action", choices=("plan", "apply", "rollback"))
|
||||
parser.add_argument("--owner-config", type=Path, required=True)
|
||||
parser.add_argument("--plan-sha256")
|
||||
parser.add_argument("--rollback", action="store_true")
|
||||
args = parser.parse_args()
|
||||
result = (
|
||||
plan(args.owner_config, args.rollback)
|
||||
if args.action == "plan"
|
||||
else apply(args.owner_config, args.plan_sha256, args.action == "rollback")
|
||||
)
|
||||
print(json.dumps(result, indent=2))
|
||||
@@ -336,6 +336,8 @@ class NetworkProfiles:
|
||||
raise ValueError("Неизвестный способ подключения.")
|
||||
with self.fleet.lock:
|
||||
vehicle = copy.deepcopy(self.fleet.find(vehicle_id))
|
||||
if self.fleet.uplinks.busy(vehicle["node_id"]):
|
||||
raise ValueError("Дождитесь завершения выбора сетевого подключения.")
|
||||
if vehicle["enrollment"] != "paired":
|
||||
raise ValueError("Сначала привяжите бортовой компьютер.")
|
||||
node_id = vehicle["node_id"]
|
||||
|
||||
@@ -53,6 +53,8 @@ class FleetRegistry:
|
||||
self.monitor = MonitorReceiver(root)
|
||||
from .rover_control import RoverControl
|
||||
self.rover_control = RoverControl()
|
||||
from .uplinks import Uplinks
|
||||
self.uplinks = Uplinks(guard=self.rover_control.network_change)
|
||||
from .rover_channel import RoverChannel
|
||||
self.rover_channel = RoverChannel(self.rover_control)
|
||||
from .rover_configuration import RoverConfigurations
|
||||
@@ -429,6 +431,7 @@ class FleetRegistry:
|
||||
self.network_profiles.reconcile()
|
||||
with self.lock:
|
||||
self.routers.prune()
|
||||
self.uplinks.prune()
|
||||
active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")]
|
||||
for address in {address for row in active for address in listener_addresses(row)}:
|
||||
try:
|
||||
@@ -515,6 +518,7 @@ class FleetRegistry:
|
||||
sensor_response = sensors.heartbeat(row, value)
|
||||
configuration_response = self.rover_configurations.heartbeat(node_id, value)
|
||||
network_response = self.network_profiles.heartbeat(row, value)
|
||||
uplink_response = self.uplinks.heartbeat(row, value)
|
||||
archive_ack = None
|
||||
archive_started = time.monotonic()
|
||||
try:
|
||||
@@ -573,6 +577,7 @@ class FleetRegistry:
|
||||
"client_pem": row["binding"]["client_pem"],
|
||||
**configuration_response,
|
||||
**network_response,
|
||||
**uplink_response,
|
||||
**sensor_response,
|
||||
**enrollment_response,
|
||||
**router_response,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""A bounded command receipt for the board-owned fallback setting."""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool
|
||||
|
||||
|
||||
class FallbackValue(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
enabled: StrictBool
|
||||
revision: int = Field(ge=0, le=2147483647)
|
||||
operation_id: str = Field(default='', max_length=32)
|
||||
|
||||
|
||||
class FallbackCommands:
|
||||
def __init__(self, clock):
|
||||
self.clock = clock
|
||||
self.operations = {}
|
||||
|
||||
def prune(self):
|
||||
now = self.clock()
|
||||
for node, op in list(self.operations.items()):
|
||||
if op['phase'] == 'queued' and now >= op['expires_at']:
|
||||
op.update(phase='failed', message='Нет подтверждения сохранения настройки.')
|
||||
if now - op['started'] > 600 and op['phase'] != 'queued':
|
||||
del self.operations[node]
|
||||
|
||||
def busy(self, node):
|
||||
self.prune()
|
||||
return self.operations.get(node, {}).get('phase') == 'queued'
|
||||
|
||||
def public(self, node):
|
||||
self.prune()
|
||||
op = self.operations.get(node)
|
||||
return {k: op[k] for k in ('id', 'phase', 'message')} if op else None
|
||||
|
||||
def start(self, row, view, body):
|
||||
node = row['node_id']
|
||||
old = self.operations.get(node)
|
||||
identity = body['operation_id']
|
||||
if old and old['id'] == identity:
|
||||
if (old['enabled'], old['revision'], old['runtime'], old['binding']) != (
|
||||
body['enabled'], body['revision'], body['runtime'],
|
||||
row['binding']['binding_id']):
|
||||
raise ValueError('Конфликт настройки резервного подключения.')
|
||||
return self.public(node)
|
||||
if self.busy(node):
|
||||
raise ValueError('Дождитесь сохранения настройки.')
|
||||
policy = view.get('fallback')
|
||||
if (not view['available'] or not view['path_verified'] or not policy
|
||||
or view['runtime'] != body['runtime'] or policy['revision'] != body['revision']):
|
||||
raise ValueError('Дождитесь актуального подтверждения подключения борта.')
|
||||
if len(self.operations) >= 128 and node not in self.operations:
|
||||
raise ValueError('Слишком много одновременных настроек.')
|
||||
self.operations[node] = dict(
|
||||
id=identity, kind='fallback', enabled=body['enabled'], revision=body['revision'],
|
||||
runtime=body['runtime'], binding=row['binding']['binding_id'],
|
||||
started=self.clock(), expires_at=int(self.clock()) + 30, phase='queued',
|
||||
message='Сохраняем настройку на борту.')
|
||||
return self.public(node)
|
||||
|
||||
def heartbeat(self, row, latest):
|
||||
self.prune()
|
||||
op = self.operations.get(row['node_id'])
|
||||
if not op or not latest:
|
||||
return {}
|
||||
value = latest['value']
|
||||
if latest['runtime'] != op['runtime'] or latest['binding'] != op['binding']:
|
||||
if op['phase'] == 'queued':
|
||||
op.update(phase='failed', message='Борт перезапустился. Проверьте настройку.')
|
||||
return {}
|
||||
policy = value.get('fallback')
|
||||
if (policy and policy['operation_id'] == op['id']
|
||||
and policy['enabled'] == op['enabled']
|
||||
and policy['revision'] == op['revision'] + 1):
|
||||
op.update(phase='applied', message='')
|
||||
receipt = value.get('receipt') or {}
|
||||
if receipt.get('id') == op['id'] and receipt.get('phase') == 'failed':
|
||||
op.update(phase='failed', message=str(
|
||||
receipt.get('message', 'Настройка не сохранена.'))[:512])
|
||||
if op['phase'] == 'queued':
|
||||
return {'uplink_change': {k: op[k] for k in (
|
||||
'id', 'kind', 'enabled', 'revision', 'runtime', 'expires_at')}}
|
||||
return {}
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Fresh physical-uplink authority and expiring commands; no telemetry persistence."""
|
||||
|
||||
import copy
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
||||
|
||||
from .uplink_fallback import FallbackCommands, FallbackValue
|
||||
|
||||
PENDING = {
|
||||
"queued",
|
||||
"applying",
|
||||
"verifying",
|
||||
"rolling_back",
|
||||
"recovering",
|
||||
"unknown",
|
||||
"rollback_failed",
|
||||
}
|
||||
REPORTED = {
|
||||
"applying",
|
||||
"verifying",
|
||||
"rolling_back",
|
||||
"recovering",
|
||||
"rollback_failed",
|
||||
"applied",
|
||||
"rolled_back",
|
||||
"superseded",
|
||||
}
|
||||
|
||||
|
||||
class Candidate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: str = Field(pattern=r"^[a-fA-F0-9-]{36}$")
|
||||
label: str = Field(max_length=160)
|
||||
interface: str = Field(min_length=1, max_length=32)
|
||||
kind: Literal["wifi", "ethernet"]
|
||||
verified: bool
|
||||
available: bool = False
|
||||
active: bool = False
|
||||
|
||||
|
||||
class UplinkEvent(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
id: str = Field(pattern=r'^[a-f0-9]{32}$')
|
||||
at: float = Field(ge=0, allow_inf_nan=False)
|
||||
kind: Literal['fallback', 'manual_rollback']
|
||||
source: Literal['wifi', 'ethernet']
|
||||
target: Literal['wifi', 'ethernet']
|
||||
|
||||
|
||||
class Snapshot(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
supported: bool
|
||||
protocol: int = 1
|
||||
path_verified: bool = False
|
||||
reason: str = Field(default="", max_length=512)
|
||||
revision: str = Field(default="", max_length=64)
|
||||
current_id: str = Field(default="", max_length=36)
|
||||
candidates: list[Candidate] = Field(default_factory=list, max_length=16)
|
||||
operation: dict[str, Any] | None = None
|
||||
receipt: dict[str, Any] | None = None
|
||||
fallback: FallbackValue | None = None
|
||||
events: list[UplinkEvent] = Field(default_factory=list, max_length=8)
|
||||
|
||||
|
||||
class Uplinks:
|
||||
"""Called under the Fleet lock, including request admission and heartbeat."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
clock: Callable[[], float] = time.time,
|
||||
guard: Callable[[str, bool], None] = lambda _node, _active: None,
|
||||
) -> None:
|
||||
self.clock = clock
|
||||
self.guard = guard
|
||||
self.guarded: set[str] = set()
|
||||
self.latest: dict[str, dict[str, Any]] = {}
|
||||
self.operations: dict[str, dict[str, Any]] = {}
|
||||
self.fallback_commands = FallbackCommands(clock)
|
||||
|
||||
def release(self, node: str) -> None:
|
||||
if node in self.guarded and self.operations.get(node, {}).get("phase") not in PENDING:
|
||||
self.guard(node, False)
|
||||
self.guarded.discard(node)
|
||||
|
||||
def prune(self) -> None:
|
||||
now = self.clock()
|
||||
for node, op in list(self.operations.items()):
|
||||
if now > op["started"] + 180 and op["phase"] in ("queued", "applying", "verifying"):
|
||||
op.update(
|
||||
phase="unknown",
|
||||
message=(
|
||||
"Нет подтверждения борта. Откат выполняется на борту; "
|
||||
"дождитесь восстановления связи."
|
||||
),
|
||||
)
|
||||
self.release(node)
|
||||
if now > op["started"] + 86400 and op["phase"] not in PENDING:
|
||||
del self.operations[node]
|
||||
self.latest = {k: v for k, v in self.latest.items() if now - v["received"] < 600}
|
||||
|
||||
def busy(self, node: str) -> bool:
|
||||
self.prune()
|
||||
return (self.operations.get(node, {}).get("phase") in PENDING
|
||||
or self.fallback_commands.busy(node))
|
||||
|
||||
def heartbeat(self, row: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
|
||||
result = self.update(row, payload)
|
||||
setting = self.fallback_commands.heartbeat(row, self.latest.get(row['node_id']))
|
||||
return result or setting
|
||||
|
||||
def update(self, row: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
|
||||
self.prune()
|
||||
node = row["node_id"]
|
||||
try:
|
||||
state = Snapshot.model_validate(payload.get("uplink")).model_dump()
|
||||
except ValidationError:
|
||||
self.latest.pop(node, None)
|
||||
return {}
|
||||
runtime = payload["execution_binding"]["agent_instance_id"]
|
||||
binding = row["binding"]["binding_id"]
|
||||
scope = f"{binding}:{runtime}"
|
||||
if node not in self.latest and len(self.latest) >= 128:
|
||||
self.latest.pop(min(self.latest, key=lambda key: self.latest[key]["received"]))
|
||||
self.latest[node] = dict(
|
||||
value=state, runtime=runtime, binding=binding, received=self.clock()
|
||||
)
|
||||
op = self.operations.get(node)
|
||||
reported = state.get("operation") or {}
|
||||
phase = reported.get("phase")
|
||||
# The fresh authenticated helper state remains authoritative after Core
|
||||
# restart, including rollback started by a previous Node runtime.
|
||||
if (
|
||||
state["protocol"] == 2
|
||||
and phase in REPORTED
|
||||
and isinstance(reported.get("id"), str)
|
||||
and len(reported["id"]) == 32
|
||||
):
|
||||
if not op:
|
||||
op = dict(
|
||||
id=reported["id"],
|
||||
target=reported.get("target", ""),
|
||||
runtime=runtime,
|
||||
binding=binding,
|
||||
revision=state["revision"],
|
||||
started=self.clock(),
|
||||
expires_at=0,
|
||||
reported_only=True,
|
||||
phase=phase,
|
||||
message=str(reported.get("message", ""))[:512],
|
||||
)
|
||||
self.operations[node] = op
|
||||
if op["id"] == reported["id"]:
|
||||
op.update(phase=phase, message=str(reported.get("message", ""))[:512])
|
||||
if phase in PENDING and node not in self.guarded:
|
||||
self.guard(node, True)
|
||||
self.guarded.add(node)
|
||||
if not op:
|
||||
return {}
|
||||
if op["runtime"] != runtime or op["binding"] != binding:
|
||||
if op["id"] != reported.get("id") or phase not in REPORTED:
|
||||
op.update(
|
||||
phase="unknown",
|
||||
message=("Борт перезапустился или изменил привязку. "
|
||||
"Проверьте текущее подключение."),
|
||||
)
|
||||
self.release(node)
|
||||
return {}
|
||||
receipt = state.get("receipt") or {}
|
||||
if receipt.get("id") == op["id"] and receipt.get("phase") == "failed":
|
||||
op.update(
|
||||
phase="failed",
|
||||
message=str(receipt.get("message", "Подключение не применено."))[:512],
|
||||
)
|
||||
if (
|
||||
reported.get("id") == op["id"]
|
||||
and reported.get("binding") == scope
|
||||
and reported.get("target") == op["target"]
|
||||
):
|
||||
phase = reported.get("phase")
|
||||
if phase in (
|
||||
"applying",
|
||||
"verifying",
|
||||
"applied",
|
||||
"rolled_back",
|
||||
"rollback_failed",
|
||||
"recovering",
|
||||
"rolling_back",
|
||||
"superseded",
|
||||
):
|
||||
op.update(phase=phase, message=str(reported.get("message", ""))[:512])
|
||||
nonce = reported.get("nonce")
|
||||
if (
|
||||
state["protocol"] == 2
|
||||
and not op.get("reported_only")
|
||||
and reported.get("path_verified") is True
|
||||
and phase == "verifying"
|
||||
and isinstance(nonce, str)
|
||||
and len(nonce) == 32
|
||||
and self.clock() < op["started"] + 120
|
||||
):
|
||||
return {"uplink_ack": {"id": op["id"], "nonce": nonce}}
|
||||
self.release(node)
|
||||
if op["phase"] == "queued" and self.clock() < op["expires_at"]:
|
||||
return {
|
||||
"uplink_change": {
|
||||
k: op[k] for k in ("id", "target", "runtime", "revision", "expires_at")
|
||||
}
|
||||
}
|
||||
if op["phase"] == "queued" and self.clock() >= op["expires_at"]:
|
||||
op.update(
|
||||
phase="unknown",
|
||||
message="Борт не подтвердил выполнение команды. Обновите состояние подключения.",
|
||||
)
|
||||
self.release(node)
|
||||
return {}
|
||||
|
||||
def view(self, row: dict[str, Any]) -> dict[str, Any]:
|
||||
self.prune()
|
||||
node = row["node_id"]
|
||||
latest = self.latest.get(node)
|
||||
fresh = bool(
|
||||
latest
|
||||
and self.clock() - latest["received"] <= 20
|
||||
and row.get("enrollment") == "paired"
|
||||
and latest["binding"] == row.get("binding", {}).get("binding_id")
|
||||
)
|
||||
state = latest["value"] if latest else {}
|
||||
return {
|
||||
"available": fresh and state.get("supported", False) and state.get("protocol") == 2,
|
||||
"path_verified": fresh and state.get("path_verified", False),
|
||||
"reason": (
|
||||
state.get("reason", "")
|
||||
if state.get("protocol") == 2
|
||||
else "Обновите Node для проверки фактического пути связи."
|
||||
)
|
||||
if fresh
|
||||
else "Дождитесь актуальных данных борта с обновлённой версией Node.",
|
||||
"revision": state.get("revision", ""),
|
||||
"runtime": latest["runtime"] if fresh and latest else "",
|
||||
"current_id": state.get("current_id", ""),
|
||||
"candidates": copy.deepcopy(state.get("candidates", [])) if fresh else [],
|
||||
"operation": self.public_operation(node),
|
||||
'fallback': copy.deepcopy(state.get('fallback')) if fresh else None,
|
||||
'fallback_operation': self.fallback_commands.public(node),
|
||||
}
|
||||
|
||||
def set_fallback(self, row: dict[str, Any], body: dict[str, Any]) -> dict[str, Any]:
|
||||
if self.operations.get(row['node_id'], {}).get('phase') in PENDING:
|
||||
raise ValueError('Дождитесь завершения переключения.')
|
||||
return self.fallback_commands.start(row, self.view(row), body)
|
||||
|
||||
def public_operation(self, node: str) -> dict[str, Any] | None:
|
||||
op = self.operations.get(node)
|
||||
return {k: op[k] for k in ("id", "phase", "message")} if op else None
|
||||
|
||||
def events(self, row: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
latest = self.latest.get(row['node_id'])
|
||||
if (not latest or self.clock() - latest['received'] > 20
|
||||
or row.get('enrollment') != 'paired'
|
||||
or latest['binding'] != row.get('binding', {}).get('binding_id')):
|
||||
return []
|
||||
return copy.deepcopy(latest['value'].get('events', []))
|
||||
|
||||
def start(
|
||||
self, row: dict[str, Any], target: str, revision: str, runtime: str, identity: str
|
||||
) -> dict[str, Any] | None:
|
||||
node = row["node_id"]
|
||||
old = self.operations.get(node)
|
||||
if old and old["id"] == identity:
|
||||
if (old["target"], old["revision"], old["runtime"], old["binding"]) != (
|
||||
target,
|
||||
revision,
|
||||
runtime,
|
||||
row["binding"]["binding_id"],
|
||||
):
|
||||
raise ValueError("Конфликт команды переключения.")
|
||||
return self.public_operation(node)
|
||||
if self.busy(node):
|
||||
raise ValueError("Дождитесь завершения переключения.")
|
||||
view = self.view(row)
|
||||
if not view["available"] or view["revision"] != revision or view["runtime"] != runtime:
|
||||
raise ValueError("Подключения изменились или борт недоступен. Обновите выбор.")
|
||||
if not any(c["id"] == target and (c["available"] or c["verified"])
|
||||
for c in view["candidates"]):
|
||||
raise ValueError("Борт не подтвердил доступность выбранного подключения.")
|
||||
if (view["current_id"] == target and view["path_verified"]) or not view["current_id"]:
|
||||
raise ValueError("Выберите доступное резервное подключение.")
|
||||
if len(self.operations) >= 128 and node not in self.operations:
|
||||
raise ValueError("Слишком много одновременных сетевых операций.")
|
||||
self.guard(node, True)
|
||||
self.guarded.add(node)
|
||||
self.operations[node] = dict(
|
||||
id=identity,
|
||||
target=target,
|
||||
revision=revision,
|
||||
runtime=runtime,
|
||||
binding=row["binding"]["binding_id"],
|
||||
phase="queued",
|
||||
started=self.clock(),
|
||||
expires_at=int(self.clock()) + 30,
|
||||
message="Команда отправлена на борт.",
|
||||
)
|
||||
return self.public_operation(node)
|
||||
@@ -64,6 +64,9 @@ router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"])
|
||||
|
||||
from .fleet_router_api import register as register_router_equipment
|
||||
register_router_equipment(router, local_operator)
|
||||
from .fleet_uplink_api import register as register_uplinks
|
||||
register_uplinks(router, local_operator)
|
||||
|
||||
from .fleet_network_api import register as register_network_profiles
|
||||
register_network_profiles(router, local_operator)
|
||||
from .fleet_power_api import register as register_power
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Local operator surface for board-owned physical-network commands."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool
|
||||
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
|
||||
|
||||
class SelectUplink(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
target: str = Field(pattern=r"^[a-fA-F0-9-]{36}$")
|
||||
revision: str = Field(pattern=r"^[a-f0-9]{64}$")
|
||||
runtime: str = Field(min_length=1, max_length=80)
|
||||
operation_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
|
||||
|
||||
class SetFallback(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
enabled: StrictBool
|
||||
revision: int = Field(ge=0, le=2147483647, strict=True)
|
||||
runtime: str = Field(min_length=1, max_length=80)
|
||||
operation_id: str = Field(pattern=r'^[a-f0-9]{32}$')
|
||||
|
||||
|
||||
def register(router: APIRouter, local_operator: Callable[..., FleetRegistry]) -> None:
|
||||
@router.patch('/{vehicle_id}/uplink/fallback')
|
||||
def fallback(
|
||||
vehicle_id: str, body: SetFallback,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)],
|
||||
) -> dict[str, Any]:
|
||||
with fleet.lock:
|
||||
try:
|
||||
row = fleet.find(vehicle_id) # type: ignore[no-untyped-call]
|
||||
overlay = fleet.network_profiles.view(row['node_id']) # type: ignore[no-untyped-call]
|
||||
if (overlay.get('operation') or {}).get('state') in ('applying', 'rolling_back'):
|
||||
raise ValueError('Дождитесь завершения изменения связи с Core.')
|
||||
return fleet.uplinks.set_fallback(row, body.model_dump())
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/uplink")
|
||||
def view(
|
||||
vehicle_id: str,
|
||||
response: Response,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)],
|
||||
) -> dict[str, Any] | None:
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
with fleet.lock:
|
||||
try:
|
||||
return fleet.uplinks.view(fleet.find(vehicle_id)) # type: ignore[no-untyped-call]
|
||||
except ValueError as error:
|
||||
raise HTTPException(404, str(error)) from None
|
||||
|
||||
@router.post("/{vehicle_id}/uplink")
|
||||
def select(
|
||||
vehicle_id: str,
|
||||
body: SelectUplink,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)],
|
||||
) -> dict[str, Any] | None:
|
||||
with fleet.lock:
|
||||
try:
|
||||
row = fleet.find(vehicle_id) # type: ignore[no-untyped-call]
|
||||
overlay = fleet.network_profiles.view(row["node_id"]) # type: ignore[no-untyped-call]
|
||||
if (overlay.get("operation") or {}).get("state") in ("applying", "rolling_back"):
|
||||
raise ValueError("Дождитесь завершения изменения связи с Core.")
|
||||
return fleet.uplinks.start(
|
||||
row, body.target, body.revision, body.runtime, body.operation_id
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
Reference in New Issue
Block a user