"""Exact-identity Docker lifecycle for the separately packaged mapping module.""" import json import subprocess import time from pathlib import Path from local_state import read_json, write_json def docker(*args, check=True): result = subprocess.run( ["docker", *map(str, args)], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, ) if check and result.returncode: raise RuntimeError("Infrastructure Docker operation failed: " + result.stderr[-1000:]) return result def inspect_owned(name, key): result = docker("container", "inspect", name, check=False) if result.returncode: # Prove absence from a successful daemon listing; a dead daemon is not absence. ids = docker("ps", "-aq", "--filter", "name=^/" + name + "$").stdout.strip() if ids: raise RuntimeError("Cannot inspect analysis container") return None row = json.loads(result.stdout)[0] labels = row["Config"].get("Labels") or {} if ( labels.get("com.nodedc.analysis") != key or labels.get("com.nodedc.stack") != "urban-mapping" ): raise RuntimeError("Analysis container identity changed") return row def cleanup(marker): record = read_json(marker) if not record: return for name in list(record["containers"]): row = inspect_owned(name, record["key"]) if row: docker("rm", "-f", row["Id"]) if inspect_owned(name, record["key"]): raise RuntimeError("Analysis container was not released") # Retain only unresolved ownership, not every historical stage. Exit # receipts hold history; rescanning it made long pipelines quadratic. record["containers"].remove(name) write_json(marker, record) def resource_arguments(resources=None): """Bound one owned container; never alter Docker or host-wide limits.""" values={"cpus":4,"memory_gib":16} if resources is not None: if not isinstance(resources,dict) or set(resources)-set(values): raise ValueError("Unsupported infrastructure resource profile") values.update(resources) for key,lower,upper in [("cpus",1,12),("memory_gib",8,32)]: if type(values[key])is not int or not lower<=values[key]<=upper: raise ValueError("Infrastructure resource limit out of bounds: "+key) return ["--cpus",str(values["cpus"]),"--memory",str(values["memory_gib"])+"g"] def run_container(marker, phase, image, mounts, command, output, pulse, timeout, *, gpu=True, executable=None, environment=None, volumes=(), readonly=False, resources=None): resource_args = resource_arguments(resources) record = read_json(marker) name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase if name not in record["containers"]: record["containers"].append(name) write_json(marker, record) # Persist intent before Docker creation. previous = inspect_owned(name, record["key"]) if previous: raise RuntimeError("Unreconciled analysis container") config = json.loads(docker("image", "inspect", image).stdout)[0]["Config"] inherited = next( (e.partition("=")[2] for e in config.get("Env", []) if e.startswith("PYTHONPATH=")), "" ) pythonpath = "/geometry:/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e" if inherited: pythonpath += ":" + inherited args = [ "create", "--name", name, "--network", "none", *resource_args, "--shm-size", "1g", "--label", "com.nodedc.product=mission-core", "--label", "com.nodedc.stack=urban-mapping", "--label", "com.nodedc.role=" + phase, "--label", "com.nodedc.managed-by=infrastructure-worker", "--label", "com.nodedc.analysis=" + record["key"], "-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "PYTHONFAULTHANDLER=1", "-e", "OMP_NUM_THREADS=4", "-e", "PYTHONPATH=" + pythonpath, ] if gpu: args += ["--gpus", "all"] if readonly: args += ["--read-only", "--pids-limit", "512", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--tmpfs", "/tmp:rw,exec,size=1g"] for variable, value in (environment or {}).items(): if variable == "PYTHONPATH": value = value + (":" + inherited if inherited else "") args += ["-e", variable + "=" + str(value)] for volume, destination in volumes: if not volume.startswith("ndc-"): raise ValueError("Analysis cache volume requires owned namespace") args += ["--mount", "type=volume,source=" + volume + ",target=" + destination] for source, destination, readonly in mounts: args += [ "--mount", "type=bind,source=" + str(Path(source).resolve()) + ",target=" + destination + (",readonly" if readonly else ""), ] exe = executable or ("/usr/bin/python3" if phase == "survey" else "/opt/conda/envs/goose/bin/python") args += ["--entrypoint", exe, image, *command] cid = docker(*args).stdout.strip() row = inspect_owned(name, record["key"]) if not row or row["Id"] != cid: raise RuntimeError("Docker create identity mismatch") deadline = time.monotonic() + timeout try: docker("start", cid) while True: pulse() row = inspect_owned(name, record["key"]) if not row: raise RuntimeError("Analysis container disappeared") if not row["State"]["Running"]: logs = docker("logs", "--tail", "2000", cid, check=False) (output / (phase + ".log")).write_text(logs.stdout + logs.stderr, encoding="utf-8") write_json(output / (phase + "-exit.json"), row["State"]) if row["State"]["ExitCode"]: state = row["State"] raise RuntimeError( f"Analysis {phase} exited {state['ExitCode']}; OOM={state['OOMKilled']}" ) return if time.monotonic() >= deadline: raise TimeoutError("Infrastructure analysis exceeded its bounded runtime") time.sleep(1) finally: cleanup(marker)