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())
|
||||
Reference in New Issue
Block a user