Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
425 lines
16 KiB
Python
425 lines
16 KiB
Python
#!/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())
|