"""Prepare a pinned Nav2 module in one bounded Worker-owned compiler container. No host installation, registry credentials, network changes, or activation. The immutable base, source, scripts and completed image are recorded together. """ import argparse import hashlib import json import subprocess import time from datetime import datetime, timezone from pathlib import Path def digest(path): with Path(path).open('rb') as stream: return hashlib.file_digest(stream, 'sha256').hexdigest() def docker(*args, timeout=60, check=True): return subprocess.run(['docker', *args], capture_output=True, text=True, timeout=timeout, check=check) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--runtime', type=Path, default=Path('D:/NDC_MISSIONCORE/runtime/simulation')) args = parser.parse_args() root = Path(__file__).resolve().parent lock = json.loads((root / 'source.lock.json').read_text()) if (args.runtime / 'state/active.json').exists(): raise RuntimeError('A simulation is active; build was not started') if digest(args.source) != lock['archive_sha256']: raise ValueError('Nav2 source archive identity changed') base = docker('image', 'inspect', lock['base_image'], '--format', '{{.Id}}').stdout.strip() if base != lock['base_image']: raise ValueError('Pinned Nav2 dependency image unavailable') files = {name: digest(root / name) for name in ('build.py', 'build.sh', 'entrypoint.sh', 'source.lock.json')} identity = hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest() name = 'ndc-mission-core-nav2-build-' + identity[:16] tag = 'ndc-mission-core-nav2:1.1.17-' + identity[:16] args.output.mkdir(parents=True, exist_ok=False) receipt = dict(started_utc=datetime.now(timezone.utc).isoformat(), files=files, source=lock, build_identity=identity, container_name=name, tag=tag, status='preparing', activated=False) receipt_path = args.output / 'build.json' def save(): receipt_path.write_text(json.dumps(receipt, indent=2) + '\n') save() container = None started = time.monotonic() try: container = docker( 'create', '--name', name, '--network', 'none', '--cpus', '4', '--memory', '8g', '--pids-limit', '512', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--label', 'com.nodedc.product=mission-core', '--label', 'com.nodedc.stack=ai-polygon', '--label', 'com.nodedc.role=nav2-build', '--label', 'com.nodedc.managed-by=ai-polygon-preparation', '--label', 'com.nodedc.build-sha256=' + identity, '--entrypoint', '/bin/bash', base, '-c', 'exec timeout --signal=TERM --kill-after=15s 1800 bash /ndc-build/build.sh', ).stdout.strip() receipt.update(container_id=container, status='building') save() docker('cp', str(root), container + ':/ndc-build') docker('cp', str(args.source.resolve()), container + ':/source.tar.gz', timeout=120) with (args.output / 'build.log').open('w') as log: subprocess.run(['docker', 'start', '-a', container], stdout=log, stderr=subprocess.STDOUT, timeout=1850, check=True) state = json.loads(docker('inspect', container).stdout)[0]['State'] if state['ExitCode'] != 0: raise RuntimeError('Nav2 compiler exited: ' + str(state)) docker('cp', container + ':/opt/ndc_nav2/packages.json', str(args.output / 'packages.json')) image = docker( 'commit', '--change', 'ENTRYPOINT ["/bin/bash", "/ndc-build/entrypoint.sh"]', '--change', 'CMD ["bash"]', '--change', 'WORKDIR /opt/ndc_nav2', '--change', 'LABEL com.nodedc.role=nav2-runtime', container, tag, timeout=180, ).stdout.strip() receipt.update(status='built', image=image, packages=json.loads((args.output / 'packages.json').read_text())) except BaseException as error: receipt.update(status='failed', error=type(error).__name__ + ': ' + str(error)) raise finally: if container: docker('rm', '-f', container, check=False) remaining = docker('ps', '-a', '--no-trunc', '-q', '--filter', 'id=' + container) receipt['owned_container_removed'] = not remaining.stdout.strip() receipt['elapsed_s'] = time.monotonic() - started receipt['finished_utc'] = datetime.now(timezone.utc).isoformat() save() if container and not receipt['owned_container_removed']: raise RuntimeError('Owned Nav2 build container cleanup was not confirmed') print(json.dumps(receipt)) if __name__ == '__main__': main()