feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
"""Bounded operator-host A1 collection. Never sends arm, hold or drive requests."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def exchange(url, body=None):
|
||||
raw = None if body is None else json.dumps(body).encode()
|
||||
request = Request(url, data=raw, headers={"Content-Type": "application/json"})
|
||||
with urlopen(request, timeout=4) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def collect(vehicle, output, seconds, *, previous_id=None, allow_operator=False,
|
||||
stop_after_control_idle_s=None):
|
||||
if not 1 <= seconds <= 1800:
|
||||
raise ValueError("Duration must be 1..1800 seconds")
|
||||
if stop_after_control_idle_s is not None and (
|
||||
not allow_operator or type(stop_after_control_idle_s) is not int
|
||||
or not 1 <= stop_after_control_idle_s <= 120
|
||||
):
|
||||
raise ValueError("Operator-stop collection requires allowed control and 1..120 s tail")
|
||||
url = "http://127.0.0.1:8000/api/v1/fleet/" + quote(vehicle, safe="") + "/rover"
|
||||
state = exchange(url)
|
||||
if state.get("controlling") and not allow_operator:
|
||||
raise ValueError("Operator control is active; no passive qualification started")
|
||||
path = Path(output)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
identifier, after, count, gaps, written = None, 0, 0, 0, 0
|
||||
started = time.monotonic()
|
||||
outcome, error, final = "complete", None, None
|
||||
control_seen, idle_since, termination = False, None, "duration_limit"
|
||||
digest = hashlib.sha256()
|
||||
with path.open("xb") as handle:
|
||||
|
||||
def write(value):
|
||||
nonlocal written
|
||||
raw = (
|
||||
json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n"
|
||||
).encode()
|
||||
if written + len(raw) > 64 * 1024 * 1024:
|
||||
raise ValueError("Capture byte limit reached")
|
||||
handle.write(raw)
|
||||
digest.update(raw)
|
||||
written += len(raw)
|
||||
|
||||
def drain():
|
||||
nonlocal after, count, gaps
|
||||
# At most two pages each cycle; browser and control never await this collector.
|
||||
for _ in range(2):
|
||||
page = exchange(
|
||||
url
|
||||
+ "/diagnostics/local?capture_id="
|
||||
+ identifier
|
||||
+ "&limit=500&after="
|
||||
+ str(after)
|
||||
)
|
||||
if page["first_sequence"] > after + 1:
|
||||
gaps += page["first_sequence"] - after - 1
|
||||
write(
|
||||
{
|
||||
"source": "collector",
|
||||
"event": "ring_gap",
|
||||
"after": after,
|
||||
"before": page["first_sequence"],
|
||||
}
|
||||
)
|
||||
after = page["first_sequence"] - 1
|
||||
for row in page["frames"]:
|
||||
write(row)
|
||||
after = row["record_sequence"]
|
||||
count += 1
|
||||
if after >= page["sequence"]:
|
||||
return page
|
||||
return page
|
||||
|
||||
try:
|
||||
capture = exchange(
|
||||
url + "/diagnostics/local",
|
||||
{
|
||||
"enabled": True,
|
||||
"duration_s": max(10, int(seconds) + 30),
|
||||
"capture_id": previous_id,
|
||||
},
|
||||
)
|
||||
identifier = capture["id"]
|
||||
write(
|
||||
{
|
||||
"type": "session_start",
|
||||
"schema": "missioncore.local-capture/v1",
|
||||
"id": identifier,
|
||||
"at_utc": datetime.now(UTC).isoformat(),
|
||||
"duration_s": seconds,
|
||||
"motor_commands": False,
|
||||
"allow_operator_control": allow_operator,
|
||||
"stop_after_control_idle_s": stop_after_control_idle_s,
|
||||
"capture": capture,
|
||||
}
|
||||
)
|
||||
print(json.dumps({"started": identifier, "output": str(path)}), flush=True)
|
||||
while time.monotonic() - started < seconds:
|
||||
tick = time.monotonic()
|
||||
page = drain()
|
||||
state = exchange(url)
|
||||
write(
|
||||
{
|
||||
"source": "collector",
|
||||
"event": "observation",
|
||||
"at_utc": datetime.now(UTC).isoformat(),
|
||||
"monotonic_ms": time.monotonic() * 1000,
|
||||
"value": state,
|
||||
}
|
||||
)
|
||||
if state.get("controlling") and not allow_operator:
|
||||
raise ValueError("Operator began control; passive qualification ended")
|
||||
if not page["active"]:
|
||||
raise ValueError("Local capture expired or stopped externally")
|
||||
if state.get("controlling"):
|
||||
control_seen, idle_since = True, None
|
||||
elif state.get("fresh") and control_seen:
|
||||
if idle_since is None:
|
||||
idle_since = time.monotonic()
|
||||
if (stop_after_control_idle_s is not None
|
||||
and time.monotonic() - idle_since >= stop_after_control_idle_s):
|
||||
termination = "operator_stopped"
|
||||
break
|
||||
else:
|
||||
# A stale/missing snapshot is not a confirmed completed session.
|
||||
idle_since = None
|
||||
time.sleep(
|
||||
max(
|
||||
0,
|
||||
min(1 - (time.monotonic() - tick), seconds - (time.monotonic() - started)),
|
||||
)
|
||||
)
|
||||
except BaseException as exc:
|
||||
outcome, error = "incomplete", type(exc).__name__
|
||||
finally:
|
||||
if identifier:
|
||||
try:
|
||||
final = exchange(
|
||||
url + "/diagnostics/local", {"enabled": False, "capture_id": identifier}
|
||||
)
|
||||
# A stopped generation is immutable; drain its remaining bounded ring.
|
||||
for _ in range(7):
|
||||
final = drain()
|
||||
if after >= final["sequence"]:
|
||||
break
|
||||
if after < final["sequence"]:
|
||||
outcome, error = "incomplete", "UndrainedTail"
|
||||
except Exception as exc:
|
||||
outcome, error = "incomplete", type(exc).__name__
|
||||
try:
|
||||
write(
|
||||
{
|
||||
"type": "session_end",
|
||||
"id": identifier,
|
||||
"outcome": outcome,
|
||||
"error_type": error,
|
||||
"termination": termination,
|
||||
"control_seen": control_seen,
|
||||
"events": count,
|
||||
"collector_gaps": gaps,
|
||||
"local_status": {k: v for k, v in final.items() if k != "frames"}
|
||||
if final
|
||||
else None,
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
outcome, error = "incomplete", type(exc).__name__
|
||||
manifest = {
|
||||
"id": identifier,
|
||||
"outcome": outcome,
|
||||
"error_type": error,
|
||||
"termination": termination,
|
||||
"control_seen": control_seen,
|
||||
"events": count,
|
||||
"collector_gaps": gaps,
|
||||
"bytes": written,
|
||||
"sha256": digest.hexdigest(),
|
||||
"motor_commands": False,
|
||||
}
|
||||
path.with_suffix(path.suffix + ".manifest.json").write_text(json.dumps(manifest, indent=2))
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--vehicle", required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
parser.add_argument("--seconds", type=int, default=60)
|
||||
parser.add_argument("--previous-id")
|
||||
parser.add_argument(
|
||||
"--allow-operator-control",
|
||||
action="store_true",
|
||||
help="Observe user-operated control; never originate a command",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--stop-after-control-idle", type=int,
|
||||
help="Close after this fresh idle tail following operator control (1..120 s)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
result = collect(
|
||||
args.vehicle,
|
||||
args.output,
|
||||
args.seconds,
|
||||
previous_id=args.previous_id,
|
||||
allow_operator=args.allow_operator_control,
|
||||
stop_after_control_idle_s=args.stop_after_control_idle,
|
||||
)
|
||||
print(json.dumps(result), flush=True)
|
||||
return 0 if result["outcome"] == "complete" else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Package exact Node sources for isolated, opt-in Worker 006 qualification."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
NODE = ROOT / "apps/node-agent"
|
||||
NETEM_IMAGE = "sha256:264a1dac982cafa1594654a728ba487fdddf04fc05476daba377f2b04bd2f917"
|
||||
IMAGE = "sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "outputs/link-budget-qualification")
|
||||
parser.add_argument("--suite", choices=["budget", "transport", "contention"], default="budget")
|
||||
parser.add_argument("--run-pattern")
|
||||
parser.add_argument("--skip-pattern", default="")
|
||||
args = parser.parse_args()
|
||||
output = args.output
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
toolchain = json.loads((NODE / "packaging/linux-toolchains.json").read_text())["files"][0]
|
||||
compiler = NODE / "build/linux-toolchains" / toolchain["name"]
|
||||
assert hashlib.sha256(compiler.read_bytes()).hexdigest() == toolchain["sha256"]
|
||||
sources = {
|
||||
str(p.relative_to(NODE)): p
|
||||
for p in (NODE / "internal").rglob("*")
|
||||
if p.is_file() and p.suffix in {".go", ".json"}
|
||||
}
|
||||
sources["go.mod"] = NODE / "go.mod"
|
||||
qualification = {
|
||||
"budget": "link_budget_load_test.go",
|
||||
"contention": "rover_contention_test.go",
|
||||
"transport": "rover_transport_test.go",
|
||||
}[args.suite]
|
||||
sources["internal/node/worker_" + qualification] = ROOT / "tests/qualification" / qualification
|
||||
if args.suite in ("transport", "contention"):
|
||||
sources["internal/node/worker_rover_datagram_test.go"] = (
|
||||
ROOT / "tests/qualification/rover_datagram_test.go"
|
||||
)
|
||||
if args.suite == "contention":
|
||||
sources["internal/node/worker_rover_transport_test.go"] = (
|
||||
ROOT / "tests/qualification/rover_transport_test.go"
|
||||
)
|
||||
sources["internal/node/worker_rover_connect_test.go"] = (
|
||||
ROOT / "tests/qualification/rover_connect_test.go"
|
||||
)
|
||||
fixtures = {
|
||||
f"plugins/{plugin}/{name}": ROOT / "plugins" / plugin / name
|
||||
for plugin in ("vesc", "usb-can")
|
||||
for name in ("runtime/__init__.py", "packaging/prepare.py")
|
||||
}
|
||||
image = NETEM_IMAGE if args.suite == "contention" else IMAGE
|
||||
go_timeout = "180s" if args.suite == "contention" else "90s"
|
||||
capability = (
|
||||
"--cap-add NET_ADMIN --env MISSION_CORE_ISOLATED_NETEM=1 "
|
||||
if args.suite == "contention" else ""
|
||||
)
|
||||
selection = {
|
||||
"budget": ("^(TestWorker|TestMedia|TestLink|TestBudgetReader|TestDev|TestRoverStream"
|
||||
"|TestHeartbeat|TestOldHeartbeat)"),
|
||||
"contention": (
|
||||
"^(TestWorkerContentionMatrix|TestWorkerTransport|TestRover|TestLink|TestCommand)"
|
||||
),
|
||||
"transport": ("^(TestWorkerTransport|TestRoverStream|TestRoverLocalDelivery"
|
||||
"|TestDelayedHTTPClock|TestObservationClock)"),
|
||||
}[args.suite]
|
||||
selection = args.run_pattern or selection
|
||||
manifest = {
|
||||
"schema": "missioncore.worker-link-qualification/v1",
|
||||
"image": image,
|
||||
"network_scope": "isolated-loopback-only" if args.suite == "contention" else "none",
|
||||
"capability": "NET_ADMIN" if args.suite == "contention" else None,
|
||||
"suite": args.suite,
|
||||
"selection": selection,
|
||||
"skip": args.skip_pattern,
|
||||
"builder_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
"toolchain": toolchain,
|
||||
"sources": {k: hashlib.sha256(p.read_bytes()).hexdigest() for k, p in sources.items()},
|
||||
"source_root": "apps/node-agent",
|
||||
"fixtures": {k: hashlib.sha256(p.read_bytes()).hexdigest() for k, p in fixtures.items()},
|
||||
"limits": {"cpus": 2, "memory": "2g", "pids": 256, "seconds": 240, "network": "none"},
|
||||
}
|
||||
identity = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()[:20]
|
||||
folder = output / ("worker-" + identity)
|
||||
folder.mkdir(exist_ok=False)
|
||||
with tarfile.open(folder / "source.tar", "w") as tar:
|
||||
for name, p in sorted(sources.items()):
|
||||
tar.add(p, arcname="apps/node-agent/" + name, recursive=False)
|
||||
for name, p in sorted(fixtures.items()):
|
||||
tar.add(p, arcname=name, recursive=False)
|
||||
(folder / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
(folder / "run.sh").write_text("""#!/bin/sh
|
||||
set -eu
|
||||
mkdir -p /work/source /work/toolchain /work/cache /work/tmp
|
||||
tar --no-same-owner -xzf /input/go.tar.gz -C /work/toolchain
|
||||
tar --no-same-owner -xf /input/source.tar -C /work/source
|
||||
export GOROOT=/work/toolchain/go GOCACHE=/work/cache GOTMPDIR=/work/tmp
|
||||
export GOPROXY=off GOTOOLCHAIN=local CGO_ENABLED=0 GOMAXPROCS=2
|
||||
cd /work/source/apps/node-agent
|
||||
selection=@SELECTION@
|
||||
skip=@SKIP@
|
||||
timeout 240 /work/toolchain/go/bin/go test -p 1 -count=1 -timeout=@GO_TIMEOUT@ -v \\
|
||||
./internal/node -run "$selection" -skip "$skip"
|
||||
""".replace("@SELECTION@", shlex.quote(selection)).replace("@GO_TIMEOUT@", go_timeout)
|
||||
.replace("@SKIP@", shlex.quote(args.skip_pattern)))
|
||||
files = {
|
||||
name: hashlib.sha256((folder / name).read_bytes()).hexdigest()
|
||||
for name in ["source.tar", "manifest.json", "run.sh"]
|
||||
}
|
||||
files["go.tar.gz"] = toolchain["sha256"]
|
||||
(folder / "files.json").write_text(json.dumps(files, indent=2) + "\n")
|
||||
# The script owns this one container. It mounts only immutable test inputs,
|
||||
# has no GPU/host sockets/credentials or network and always removes itself.
|
||||
runner_script = (
|
||||
"""$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$files = Get-Content (Join-Path $root 'files.json') -Raw | ConvertFrom-Json
|
||||
foreach ($entry in $files.PSObject.Properties) {
|
||||
$hash = (Get-FileHash (Join-Path $root $entry.Name) -Algorithm SHA256).Hash.ToLower()
|
||||
if ($hash -ne $entry.Value) { throw 'Qualification input changed' }
|
||||
}
|
||||
$name = 'ndc-mission-core-link-budget-"""
|
||||
+ identity
|
||||
+ "'\n"
|
||||
+ """$started = [DateTime]::UtcNow.ToString('o')
|
||||
try {
|
||||
$ErrorActionPreference = 'Continue'
|
||||
& docker run --rm --pull never --name $name `
|
||||
--label com.nodedc.product=mission-core --label com.nodedc.role=qualification `
|
||||
--network none --cap-drop ALL @CAPABILITY@--security-opt no-new-privileges `
|
||||
--cpus 2 --memory 2g --pids-limit 256 --read-only `
|
||||
--tmpfs /work:rw,exec,size=1536m --tmpfs /tmp:rw,size=16m `
|
||||
--mount "type=bind,source=$root,target=/input,readonly" --entrypoint /bin/sh """
|
||||
+ image
|
||||
+ """ /input/run.sh 2>&1 | Out-File (Join-Path $root 'result.log') -Encoding utf8
|
||||
$exit = $LASTEXITCODE
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@{
|
||||
started_at=$started;finished_at=[DateTime]::UtcNow.ToString('o')
|
||||
exit_code=$exit;container=$name
|
||||
result_sha256=(Get-FileHash (Join-Path $root 'result.log') -Algorithm SHA256).Hash.ToLower()
|
||||
} | ConvertTo-Json | Set-Content (Join-Path $root 'result.json') -Encoding utf8
|
||||
if ($exit -ne 0) { throw 'Worker qualification failed; preserve result.log' }
|
||||
} finally {
|
||||
$ErrorActionPreference = 'Continue'
|
||||
& docker rm -f $name 2>$null | Out-Null
|
||||
}
|
||||
"""
|
||||
)
|
||||
(folder / "run.ps1").write_text(runner_script.replace("@CAPABILITY@", capability))
|
||||
print(
|
||||
json.dumps(
|
||||
{"id": identity, "folder": str(folder), "toolchain": str(compiler), "files": files}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,424 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded live runtime evidence; no motor-authority or camera-capture commands.
|
||||
|
||||
Optional disposable viewing peer, owned DEV sessions, and read-only /proc sampling.
|
||||
Never retain images, SDP, endpoints, credentials or packet payloads in evidence.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import datetime
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
BOARD_SAMPLE = r"""import json,time
|
||||
from pathlib import Path
|
||||
for i in range(900):
|
||||
out={"utc":time.time(),"mono":time.monotonic(),"kind":"board"}
|
||||
out["cpu"]=Path("/proc/stat").read_text().splitlines()[0]
|
||||
out["load"]=Path("/proc/loadavg").read_text().strip()
|
||||
out["pressure"]={k:Path("/proc/pressure/"+k).read_text().strip() for k in ("cpu","memory","io")}
|
||||
out["net"]={}
|
||||
for row in Path("/proc/net/dev").read_text().splitlines()[2:]:
|
||||
interface, data = row.split(":")
|
||||
if interface.strip() in ("wlp2s0", "tailscale0"):
|
||||
out["net"][interface.strip()] = [int(x) for x in data.split()]
|
||||
out["services"]={}
|
||||
for service in ("mission-core-node","mission-core-vesc","mission-core-insta360"):
|
||||
root=Path("/sys/fs/cgroup/system.slice/"+service+".service")
|
||||
try:out["services"][service]={"cpu":root.joinpath("cpu.stat").read_text().strip(),"memory":int(root.joinpath("memory.current").read_text())}
|
||||
except OSError:out["services"][service]={"unavailable":True}
|
||||
print(json.dumps(out,separators=(",",":")),flush=True)
|
||||
time.sleep(1)
|
||||
"""
|
||||
|
||||
|
||||
def request(base, path, body=None):
|
||||
raw = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(
|
||||
base + path, data=raw, headers={"Content-Type": "application/json"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=15) as reply:
|
||||
return json.load(reply)
|
||||
|
||||
|
||||
def stamp():
|
||||
return {"utc": time.time(), "mono": time.monotonic()}
|
||||
|
||||
|
||||
async def run(args):
|
||||
import aioice.ice
|
||||
from aiortc import RTCConfiguration, RTCPeerConnection, RTCSessionDescription
|
||||
|
||||
host_addresses = aioice.ice.get_host_addresses
|
||||
networks = tuple(
|
||||
ipaddress.ip_network(v)
|
||||
for v in ("127.0.0.0/8", "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10")
|
||||
)
|
||||
# Match the product's IPv4/private-only admission; a Mac VPN IPv6
|
||||
# candidate is not a valid X4 offer. This affects only this probe process.
|
||||
aioice.ice.get_host_addresses = lambda use_ipv4, use_ipv6: [
|
||||
v
|
||||
for v in host_addresses(use_ipv4=True, use_ipv6=False)
|
||||
if any(ipaddress.ip_address(v) in n for n in networks)
|
||||
]
|
||||
root = args.output.resolve()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
started = stamp()
|
||||
manifest = {
|
||||
"schema": "missioncore.passive-runtime/v1",
|
||||
"id": uuid.uuid4().hex,
|
||||
"started": started,
|
||||
"motor_commands": False,
|
||||
"viewing_peer": not (args.telemetry_only or args.no_viewer),
|
||||
"phase_seconds": args.seconds,
|
||||
"source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
"limitations": [
|
||||
"Existing operator viewer is measured separately; no additional peer."
|
||||
if args.no_viewer
|
||||
else "Additional viewing peer; existing operator viewer is preserved.",
|
||||
"Frame arrival gaps are not capture-to-screen latency.",
|
||||
"SSH sampler is low-volume but shares the network.",
|
||||
],
|
||||
}
|
||||
pc = RTCPeerConnection(RTCConfiguration(iceServers=[]))
|
||||
tasks, peer, device, owned, ssh = [], None, None, None, None
|
||||
phase = "setup"
|
||||
frames, last_frame = 0, None
|
||||
events = root.joinpath("samples.jsonl").open("x")
|
||||
board_file = root.joinpath("board.jsonl").open("xb")
|
||||
board_error = root.joinpath("board.stderr").open("xb")
|
||||
|
||||
def emit(kind, **fields):
|
||||
events.write(
|
||||
json.dumps({**stamp(), "kind": kind, "phase": phase, **fields}, separators=(",", ":"))
|
||||
+ "\n"
|
||||
)
|
||||
events.flush()
|
||||
|
||||
async def api(path="", body=None):
|
||||
return await asyncio.to_thread(request, args.core, path, body)
|
||||
|
||||
rover = "/" + args.vehicle + "/rover"
|
||||
operations = "/" + args.vehicle + "/devices/operations"
|
||||
|
||||
async def operation(action, parameters):
|
||||
if action not in {"offer", "close-peer"}:
|
||||
raise ValueError("Passive probe cannot execute device commands")
|
||||
now = datetime.datetime.now(datetime.UTC)
|
||||
identifier = "op_" + uuid.uuid4().hex
|
||||
command = {
|
||||
"api_version": "missioncore.nodedc/plugin-sdk/v0alpha2",
|
||||
"kind": "OperationRequest",
|
||||
"operation_id": identifier,
|
||||
"idempotency_key": identifier,
|
||||
"session": {
|
||||
"session_id": device["snapshot"]["context"]["session_id"],
|
||||
"device_id": device["id"],
|
||||
},
|
||||
"action_id": action,
|
||||
"requested_at": now.isoformat(),
|
||||
"deadline_at": (now + datetime.timedelta(seconds=20)).isoformat(),
|
||||
"parameters": parameters,
|
||||
}
|
||||
emit("view_operation", action=action, operation_id=identifier)
|
||||
result = await api(operations, command)
|
||||
deadline = time.monotonic() + 30
|
||||
while result["state"] in {"running", "queued"} and time.monotonic() < deadline:
|
||||
await asyncio.sleep(0.5)
|
||||
result = await api(operations + "/" + identifier)
|
||||
if result["state"] != "complete":
|
||||
raise RuntimeError(
|
||||
"Viewing operation failed: " + str(result.get("error", result["state"]))
|
||||
)
|
||||
return result.get("result")
|
||||
|
||||
async def stop_owned():
|
||||
nonlocal owned
|
||||
if owned is None:
|
||||
return
|
||||
current = await api(rover + "/diagnostics")
|
||||
if current["id"] == owned and current["active"]:
|
||||
await api(rover + "/diagnostics", {"enabled": False})
|
||||
deadline = time.monotonic() + 600
|
||||
while time.monotonic() < deadline:
|
||||
current = await api(rover + "/diagnostics")
|
||||
if current["id"] != owned:
|
||||
raise RuntimeError("DEV ownership changed")
|
||||
if not current["active"] and not current["closing"]:
|
||||
emit(
|
||||
"capture_closed",
|
||||
capture_id=owned,
|
||||
storage=current.get("node", {}).get("storage"),
|
||||
)
|
||||
owned = None
|
||||
return
|
||||
await asyncio.sleep(1)
|
||||
raise RuntimeError("Owned DEV tail has not closed")
|
||||
|
||||
@pc.on("track")
|
||||
def track(value):
|
||||
async def consume():
|
||||
nonlocal frames, last_frame
|
||||
try:
|
||||
while True:
|
||||
frame = await value.recv()
|
||||
now = time.monotonic()
|
||||
frames += 1
|
||||
emit(
|
||||
"video_frame",
|
||||
width=frame.width,
|
||||
height=frame.height,
|
||||
gap_ms=None if last_frame is None else (now - last_frame) * 1000,
|
||||
)
|
||||
last_frame = now
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception as error:
|
||||
emit("video_ended", error=type(error).__name__)
|
||||
|
||||
tasks.append(asyncio.create_task(consume()))
|
||||
|
||||
channel = pc.createDataChannel("sensor", ordered=False, maxRetransmits=0)
|
||||
|
||||
@channel.on("message")
|
||||
def message(value):
|
||||
try:
|
||||
emit("media", value=json.loads(value))
|
||||
except (TypeError, ValueError):
|
||||
emit("invalid_media")
|
||||
|
||||
async def keepalive():
|
||||
while True:
|
||||
if channel.readyState == "open":
|
||||
channel.send("keepalive")
|
||||
channel.send("view:secondary")
|
||||
await asyncio.sleep(2)
|
||||
|
||||
try:
|
||||
initial = await api(rover)
|
||||
if not args.telemetry_only and (
|
||||
not initial.get("fresh")
|
||||
or initial.get("controlling")
|
||||
or initial.get("snapshot", {}).get("control_active")
|
||||
):
|
||||
raise RuntimeError("Fresh inactive rover required")
|
||||
dev = await api(rover + "/diagnostics")
|
||||
if not args.telemetry_only and (dev["active"] or dev["closing"]):
|
||||
raise RuntimeError("Preserve another DEV capture")
|
||||
if not args.telemetry_only:
|
||||
fleet = await api()
|
||||
vehicle = next(v for v in fleet["items"] if v["id"] == args.vehicle)
|
||||
device = next(
|
||||
v for v in vehicle["sensor_state"]["items"] if v.get("kind") == "insta360.x4"
|
||||
)
|
||||
if not device["online"] or device["snapshot"]["acquisition"] != "streaming":
|
||||
raise RuntimeError("Existing camera preview required; probe never starts capture")
|
||||
ssh = subprocess.Popen(
|
||||
["ssh", "-F", str(args.ssh_config.resolve()), args.ssh_host, "python3 -u -"],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=board_file,
|
||||
stderr=board_error,
|
||||
)
|
||||
ssh.stdin.write(BOARD_SAMPLE.encode())
|
||||
ssh.stdin.close()
|
||||
if not (args.telemetry_only or args.no_viewer):
|
||||
pc.addTransceiver("video", direction="recvonly")
|
||||
await pc.setLocalDescription(await pc.createOffer())
|
||||
answer = await operation(
|
||||
"offer", {"sdp": pc.localDescription.sdp, "layer": "preview", "primary": False}
|
||||
)
|
||||
peer = answer["peer_id"]
|
||||
await pc.setRemoteDescription(RTCSessionDescription(sdp=answer["sdp"], type="answer"))
|
||||
tasks.append(asyncio.create_task(keepalive()))
|
||||
phases = (
|
||||
[("baseline", None)]
|
||||
if args.baseline_only
|
||||
else [
|
||||
("baseline", None),
|
||||
(
|
||||
"local",
|
||||
dict(
|
||||
live=False,
|
||||
core_trace=False,
|
||||
motor_samples=True,
|
||||
network=True,
|
||||
live_kbps=16,
|
||||
core_kbps=16,
|
||||
),
|
||||
),
|
||||
(
|
||||
"core_trace",
|
||||
dict(
|
||||
live=False,
|
||||
core_trace=True,
|
||||
motor_samples=True,
|
||||
network=True,
|
||||
live_kbps=8,
|
||||
core_kbps=8,
|
||||
),
|
||||
),
|
||||
(
|
||||
"live",
|
||||
dict(
|
||||
live=True,
|
||||
core_trace=False,
|
||||
motor_samples=True,
|
||||
network=True,
|
||||
live_kbps=8,
|
||||
core_kbps=8,
|
||||
),
|
||||
),
|
||||
]
|
||||
)
|
||||
if args.dev_matrix:
|
||||
|
||||
def options(*, core=False, live=False, rate=8):
|
||||
return dict(
|
||||
live=live,
|
||||
core_trace=core,
|
||||
motor_samples=True,
|
||||
network=True,
|
||||
live_kbps=rate,
|
||||
core_kbps=rate,
|
||||
)
|
||||
|
||||
phases = [
|
||||
("baseline", None),
|
||||
("local", options()),
|
||||
("core_trace_8", options(core=True)),
|
||||
("live_8", options(live=True)),
|
||||
("core_live_8", options(core=True, live=True)),
|
||||
("core_live_64", options(core=True, live=True, rate=64)),
|
||||
("baseline_repeat", None),
|
||||
]
|
||||
manifest["limitations"].append(
|
||||
"Stationary passive comparison: not audit T1-T6 with a neutral control session."
|
||||
)
|
||||
for phase_name, options in phases:
|
||||
phase = phase_name
|
||||
if options:
|
||||
current = await api(rover + "/diagnostics")
|
||||
if current["active"] or current["closing"]:
|
||||
raise RuntimeError("Preserve another DEV capture")
|
||||
capture = await api(rover + "/diagnostics", {"enabled": True, "options": options})
|
||||
owned = capture["id"]
|
||||
emit("capture_started", capture_id=owned, options=options)
|
||||
deadline = time.monotonic() + args.seconds
|
||||
while time.monotonic() < deadline:
|
||||
at = time.monotonic()
|
||||
value = await api(rover)
|
||||
emit(
|
||||
"rover",
|
||||
elapsed_ms=(time.monotonic() - at) * 1000,
|
||||
value=value,
|
||||
peer_state=pc.connectionState,
|
||||
frames=frames,
|
||||
)
|
||||
if not args.telemetry_only and (
|
||||
value.get("controlling") or value.get("snapshot", {}).get("control_active")
|
||||
):
|
||||
raise RuntimeError("Operator control became active; passive comparison stopped")
|
||||
if owned:
|
||||
dev = await api(rover + "/diagnostics")
|
||||
if dev["id"] != owned:
|
||||
raise RuntimeError("DEV ownership changed")
|
||||
emit(
|
||||
"dev",
|
||||
capture_id=owned,
|
||||
active=dev["active"],
|
||||
closing=dev["closing"],
|
||||
rows=len(dev.get("frames", [])),
|
||||
dropped=dev.get("dropped"),
|
||||
node=dev.get("node"),
|
||||
)
|
||||
await asyncio.sleep(max(0, 0.5 - (time.monotonic() - at)))
|
||||
await stop_owned()
|
||||
manifest["outcome"] = "complete"
|
||||
except Exception as error:
|
||||
manifest["outcome"] = "interrupted"
|
||||
manifest["error"] = str(error)
|
||||
finally:
|
||||
phase = "cleanup"
|
||||
try:
|
||||
await stop_owned()
|
||||
except Exception as error:
|
||||
manifest["capture_cleanup_error"] = str(error)
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
await pc.close()
|
||||
aioice.ice.get_host_addresses = host_addresses
|
||||
if peer:
|
||||
try:
|
||||
await operation("close-peer", {"peer_id": peer})
|
||||
except Exception as error:
|
||||
manifest["peer_cleanup_error"] = str(error)
|
||||
if ssh:
|
||||
ssh.terminate()
|
||||
try:
|
||||
ssh.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
ssh.kill()
|
||||
ssh.wait(timeout=5)
|
||||
manifest["collector_exit"] = ssh.returncode
|
||||
board_file.close()
|
||||
board_error.close()
|
||||
events.close()
|
||||
manifest["finished"] = stamp()
|
||||
manifest["frames"] = frames
|
||||
manifest["files"] = {
|
||||
p.name: {
|
||||
"bytes": p.stat().st_size,
|
||||
"sha256": hashlib.sha256(p.read_bytes()).hexdigest(),
|
||||
}
|
||||
for p in root.iterdir()
|
||||
if p.is_file()
|
||||
}
|
||||
root.joinpath("manifest.json").write_text(json.dumps(manifest, indent=2))
|
||||
print(json.dumps(manifest, ensure_ascii=False), flush=True)
|
||||
return 0 if manifest["outcome"] == "complete" else 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--core", default="http://127.0.0.1:8000/api/v1/fleet")
|
||||
parser.add_argument("--vehicle", required=True)
|
||||
parser.add_argument("--ssh-config", type=Path, required=True)
|
||||
parser.add_argument("--ssh-host", default="rover-006")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--seconds", type=int, default=45)
|
||||
parser.add_argument("--baseline-only", action="store_true")
|
||||
parser.add_argument(
|
||||
"--no-viewer",
|
||||
action="store_true",
|
||||
help="No offer or secondary viewer; observe the existing browser separately",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dev-matrix",
|
||||
action="store_true",
|
||||
help="Passive DEV direction/rate comparison; never arms a neutral session",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--telemetry-only",
|
||||
action="store_true",
|
||||
help="Read-only baseline: no viewer or DEV operations; operator control may continue",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.dev_matrix and (args.baseline_only or args.telemetry_only):
|
||||
parser.error("DEV matrix cannot be combined with baseline-only or telemetry-only")
|
||||
if args.telemetry_only and not args.baseline_only:
|
||||
parser.error("Telemetry-only requires baseline-only")
|
||||
if not 10 <= args.seconds <= 90:
|
||||
parser.error("Phase must last 10..90 seconds")
|
||||
return asyncio.run(run(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user