Local preservation snapshot, not a new deployment or simulation acceptance.
251 lines
11 KiB
Python
251 lines
11 KiB
Python
"""Run-owned additive Docker stack. Caller must hold Core's GPU reservation."""
|
|
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
sys.path.insert(0, str(ROOT.parents[1] / "src"))
|
|
NAVIGATION_NAME = "ndc-mission-core-ai-module-simulation-cmu-navigation"
|
|
NAV2_NAME = "ndc-mission-core-ai-module-simulation-nav2-navigation"
|
|
TERRAIN_NAME = "ndc-mission-core-ai-module-observed-terrain"
|
|
NAMES = (
|
|
"ndc-ai-polygon-ddrnet",
|
|
"ndc-ai-polygon-segformer",
|
|
"ndc-ai-polygon-cityscapes",
|
|
"ndc-ai-polygon-mapillary",
|
|
"ndc-ai-polygon-sam3",
|
|
"ndc-ai-polygon-rfdetr",
|
|
NAVIGATION_NAME,
|
|
NAV2_NAME,
|
|
TERRAIN_NAME,
|
|
)
|
|
|
|
|
|
def sha256(path):
|
|
with Path(path).open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def docker(*args, check=True, timeout=120):
|
|
return subprocess.run(
|
|
["docker", *args], check=check, capture_output=True, text=True, timeout=timeout
|
|
)
|
|
|
|
|
|
def wait_for_docker(status, sleep=time.sleep):
|
|
"""Desktop's engine may start after the login task; don't exhaust task retries.
|
|
|
|
Only engine availability is retried. Missing pinned assets and invalid
|
|
identities still fail the subsequent preflight, with their original error.
|
|
"""
|
|
from local_state import write_json
|
|
|
|
while True:
|
|
try:
|
|
response = docker("version", "--format", "{{.Server.Version}}", check=False, timeout=8)
|
|
if response.returncode == 0 and response.stdout.strip():
|
|
return
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
write_json(status, {"state": "waiting-docker", "utc": datetime.now(UTC).isoformat()})
|
|
sleep(3)
|
|
|
|
|
|
class ModelStack:
|
|
def __init__(self):
|
|
self.profile_path = ROOT / "models.worker-006.json"
|
|
self.profile = json.loads(self.profile_path.read_text())
|
|
self.ids = []
|
|
|
|
def preflight(self, selection=None):
|
|
from k1link.simulation.ai_polygon.composition import compose
|
|
|
|
graph = compose(ROOT, selection) # Admission before any Isaac boot.
|
|
selected = {node.module.module_id for node in graph.nodes}
|
|
providers = {
|
|
'simulation-ddrnet-goose': 'ddrnet-goose-pytorch-reference',
|
|
'simulation-rf-detr': 'rf_detr_large',
|
|
'simulation-segformer-ade': 'segformer-b2-ade150',
|
|
'simulation-segformer-cityscapes': 'segformer-b2-cityscapes19',
|
|
'simulation-mask2former-mapillary': 'mask2former-mapillary65',
|
|
'simulation-sam3-surfaces': 'sam3-litetext-surfaces',
|
|
}
|
|
required = {providers[module] for module in selected if module in providers}
|
|
models = [model for model in self.profile['models'] if model['id'] in required]
|
|
if {model['id'] for model in models} != required:
|
|
raise RuntimeError('Selected simulation model descriptor is missing')
|
|
if 'simulation-cmu-navigation' in selected:
|
|
models.append(self.profile['navigation'])
|
|
if 'simulation-nav2-navigation' in selected:
|
|
models.extend((self.profile['nav2'],
|
|
dict(image=self.profile['nav2']['terrain_image'])))
|
|
for model in models:
|
|
for key in ("checkpoint", "runner"):
|
|
if key in model and sha256(model[key]) != model[key + "_sha256"]:
|
|
raise RuntimeError("Simulation model identity changed: " + model["id"])
|
|
actual = docker(
|
|
"image", "inspect", model["image"], "--format", "{{.Id}}"
|
|
).stdout.strip()
|
|
if actual != model["image"]:
|
|
raise RuntimeError("Simulation model image is unavailable")
|
|
if ('simulation-ddrnet-goose' in selected
|
|
and sha256(self.profile["labels"]) != self.profile["labels_sha256"]):
|
|
raise RuntimeError("GOOSE label table changed")
|
|
|
|
def start(self, cancelled=None, on_acquired=None, selection=None, inputs_path=None):
|
|
from k1link.simulation.ai_polygon.composition import compose
|
|
|
|
graph = compose(ROOT, selection)
|
|
services = {
|
|
"simulation-ddrnet-goose": "ddrnet",
|
|
"simulation-segformer-ade": "segformer",
|
|
"simulation-segformer-cityscapes": "cityscapes",
|
|
"simulation-mask2former-mapillary": "mapillary",
|
|
"simulation-sam3-surfaces": "sam3",
|
|
"simulation-rf-detr": "detector",
|
|
}
|
|
module_ids = [node.module.module_id for node in graph.nodes]
|
|
installed = {
|
|
*services,
|
|
"simulation-cmu-navigation",
|
|
"simulation-nav2-navigation",
|
|
"simulation-waypoint-mission",
|
|
"simulation-declared-route",
|
|
}
|
|
if set(module_ids) - installed:
|
|
raise ValueError("Uninstalled simulation provider")
|
|
if "simulation-nav2-navigation" in module_ids and inputs_path is None:
|
|
raise ValueError("Nav2 requires immutable run inputs")
|
|
self.preflight(selection)
|
|
for name in NAMES:
|
|
if docker("container", "inspect", name, check=False).returncode == 0:
|
|
raise RuntimeError(
|
|
"An existing simulation container requires reconciliation: " + name
|
|
)
|
|
if cancelled and cancelled():
|
|
raise InterruptedError("Model startup cancelled")
|
|
try:
|
|
selected = [services[module] for module in module_ids if module in services]
|
|
docker("compose", "-f", str(ROOT / "compose.models.yaml"), "up", "-d", *selected)
|
|
if "simulation-nav2-navigation" in module_ids:
|
|
self.start_nav2(graph, inputs_path)
|
|
if "simulation-cmu-navigation" in module_ids:
|
|
input_mount = []
|
|
if inputs_path is not None:
|
|
input_mount = [
|
|
"--mount",
|
|
f"type=bind,source={Path(inputs_path).resolve()},target=/run-inputs.json,readonly",
|
|
"-e",
|
|
"MISSIONCORE_RUN_INPUTS=/run-inputs.json",
|
|
]
|
|
docker(
|
|
"run",
|
|
"-d",
|
|
"--name",
|
|
NAVIGATION_NAME,
|
|
"--restart",
|
|
"no",
|
|
"--label",
|
|
"com.nodedc.product=mission-core",
|
|
"--label",
|
|
"com.nodedc.stack=ai-polygon",
|
|
"--label",
|
|
"com.nodedc.role=ai-module",
|
|
"--label",
|
|
"com.nodedc.managed-by=ai-polygon-worker",
|
|
"--label",
|
|
"com.nodedc.composition-sha256=" + graph.sha256,
|
|
"--cpus",
|
|
"3",
|
|
"--memory",
|
|
"2g",
|
|
"-p",
|
|
"127.0.0.1:18093:8010",
|
|
"--mount",
|
|
f"type=bind,source={ROOT},target=/adapter,readonly",
|
|
*input_mount,
|
|
self.profile["navigation"]["image"],
|
|
)
|
|
finally:
|
|
# Capture immutable IDs even after a partial Compose start.
|
|
for name in NAMES:
|
|
result = docker("container", "inspect", name, check=False)
|
|
if result.returncode == 0:
|
|
row = json.loads(result.stdout)[0]
|
|
if row["Config"]["Labels"].get("com.nodedc.stack") == "ai-polygon":
|
|
self.ids.append(row["Id"])
|
|
if on_acquired:
|
|
on_acquired(list(self.ids))
|
|
deadline = time.monotonic() + 120
|
|
while time.monotonic() < deadline:
|
|
if cancelled and cancelled():
|
|
raise InterruptedError("Model startup cancelled")
|
|
ready = True
|
|
for port, path in (
|
|
(18091, "/ready"),
|
|
(18092, "/v2/models/rf_detr_large/versions/1/ready"),
|
|
(18093, "/ready"),
|
|
):
|
|
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
|
|
try:
|
|
connection.request("GET", path)
|
|
response = connection.getresponse()
|
|
response.read(65536)
|
|
ready &= response.status == 200
|
|
except OSError:
|
|
ready = False
|
|
finally:
|
|
connection.close()
|
|
if ready:
|
|
return
|
|
time.sleep(0.5)
|
|
raise TimeoutError("Simulation models did not become ready")
|
|
|
|
def start_nav2(self, graph, inputs_path):
|
|
if inputs_path is None:
|
|
raise ValueError("Nav2 requires immutable run inputs")
|
|
common = ["--restart", "no", "--read-only", "--cpus", "3", "--memory", "2g",
|
|
"--pids-limit", "256", "--cap-drop", "ALL", "--security-opt", "no-new-privileges",
|
|
"--tmpfs", "/tmp:rw,size=256m",
|
|
"--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=ai-polygon",
|
|
"--label", "com.nodedc.role=ai-module", "--label", "com.nodedc.managed-by=ai-polygon-worker",
|
|
"--label", "com.nodedc.composition-sha256="+graph.sha256,
|
|
"-e", "ROS_LOCALHOST_ONLY=1", "-e", "ROS_DOMAIN_ID=83",
|
|
"-e", "ROS_LOG_DIR=/tmp/ros-logs", "-e", "PYTHONDONTWRITEBYTECODE=1",
|
|
"-e", "PYTHONPATH=/adapter", "--mount", f"type=bind,source={ROOT},target=/adapter,readonly",
|
|
"--mount", f"type=bind,source={Path(inputs_path).resolve()},target=/run-inputs.json,readonly",
|
|
"-e", "MISSIONCORE_RUN_INPUTS=/run-inputs.json"]
|
|
# Two immutable dependency environments, one private ROS namespace.
|
|
# The terrain container hosts the loopback-bound HTTP port; only the
|
|
# Nav2 adapter in the shared namespace listens on that port.
|
|
docker("run", "-d", "--name", TERRAIN_NAME, "--ipc", "shareable",
|
|
"-p", "127.0.0.1:18093:8010", *common, "--entrypoint", "/bin/bash",
|
|
self.profile['nav2']['terrain_image'], "-c",
|
|
"source /opt/ros/humble/setup.bash && source /opt/cmu/install/setup.bash "
|
|
"&& exec python3 /adapter/nav2/terrain_node.py")
|
|
docker("run", "-d", "--name", NAV2_NAME, "--network", "container:"+TERRAIN_NAME,
|
|
"--ipc", "container:"+TERRAIN_NAME, *common,
|
|
self.profile['nav2']['image'],
|
|
"python3", "/adapter/nav2/server.py")
|
|
|
|
def stop(self):
|
|
failures = []
|
|
for identity in self.ids:
|
|
result = docker("container", "rm", "-f", identity, check=False)
|
|
if (
|
|
result.returncode
|
|
and docker("container", "inspect", identity, check=False).returncode == 0
|
|
):
|
|
failures.append(identity)
|
|
if failures:
|
|
raise RuntimeError("Simulation GPU resources were not released")
|
|
self.ids.clear()
|
|
# Only our now-unused network; Docker refuses removal if another endpoint uses it.
|
|
docker("network", "rm", "ndc-ai-polygon-models", check=False)
|