Files
NODEDC_MISSION_CORE/simulation/ai-polygon/nav2/prepare_kernels.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

81 lines
5.3 KiB
Python

"""Prepare existing geometry kernels and a narrow DWB track critic, offline."""
import argparse
import hashlib
import io
import json
import subprocess
import tarfile
import time
from datetime import datetime, timezone
from pathlib import Path
BASE = 'sha256:dc6daf1153157860a70dc4a62419da0d61a5dd3941c8f41282ab9f7413a9dac6'
def main():
parser=argparse.ArgumentParser()
parser.add_argument('--output',type=Path,required=True)
parser.add_argument('--ground',action='store_true',help='Build PCL in its existing terrain dependency image')
args=parser.parse_args()
root=Path(__file__).resolve().parents[1]/'navigation'
base = 'sha256:8517fd5d13406648907c87dd4adf771238c6a3a30fcedd555ca5a5287edebc16' if args.ground else BASE
sources={name:(root/name).read_bytes() for name in
(('pcl_ground.cpp',) if args.ground else ('support_native.cpp','terrain_connectivity.cpp'))}
if args.ground:
sources['CMakeLists.txt'] = (root/'pcl_ground.cmake').read_bytes()
if not args.ground:
for path in (root.parent/'nav2/rover_critics').iterdir():
if path.is_file(): sources['rover_critics/'+path.name]=path.read_bytes()
entrypoint = 'terrain_entrypoint.sh' if args.ground else 'runtime_entrypoint.sh'
sources['runtime_entrypoint.sh']=(root.parent/'nav2'/entrypoint).read_bytes()
files={name:hashlib.sha256(data).hexdigest() for name,data in sources.items()}
files['prepare_kernels.py']=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
identity=hashlib.sha256(json.dumps(dict(base=base,files=files),sort_keys=True).encode()).hexdigest()
args.output.mkdir(parents=True,exist_ok=False)
report=dict(base=base,files=files,identity=identity,utc=datetime.now(timezone.utc).isoformat(),activated=False)
cid=None;started=time.monotonic()
def docker(*args,timeout=30,check=True):
return subprocess.run(['docker',*args],capture_output=True,text=True,timeout=timeout,check=check)
try:
assert docker('image','inspect',base,'--format','{{.Id}}').stdout.strip()==base
assert not Path('D:/NDC_MISSIONCORE/runtime/simulation/state/active.json').exists()
command='mkdir -p /opt/missioncore && g++ -std=c++17 -O3 -shared -fPIC /sources/support_native.cpp -o /opt/missioncore/libsupport_surface.so && g++ -O3 -std=c++17 -ffp-contract=off -fno-fast-math -fPIC -shared /sources/terrain_connectivity.cpp -o /opt/missioncore/libterrain_connectivity.so'
command += ' && source /opt/ros/humble/setup.bash && source /opt/underlay_ws/install/setup.bash && source /opt/ndc_nav2/install/setup.bash && mkdir -p /opt/ndc_rover && cd /opt/ndc_rover && MAKEFLAGS=-j2 colcon build --base-paths /sources/rover_critics --packages-select ndc_rover_critics --parallel-workers 1 --cmake-args -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF'
if args.ground:
command = 'mkdir -p /opt/missioncore && cmake -S /sources -B /tmp/pcl-build -DCMAKE_BUILD_TYPE=Release && cmake --build /tmp/pcl-build -j2'
cid=docker('create','--name','ndc-mission-core-nav2-kernels-'+identity[:16],
'--network','none','--cpus','2','--memory','2g','--pids-limit','128','--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-kernel-preparation',
'--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=5s 90 bash -c '+__import__('shlex').quote(command)).stdout.strip()
report['container_id']=cid
payload=io.BytesIO()
with tarfile.open(fileobj=payload,mode='w') as archive:
for name,data in sources.items():
entry=tarfile.TarInfo('sources/'+name);entry.size=len(data)
archive.addfile(entry,io.BytesIO(data))
subprocess.run(['docker','cp','-',cid+':/'],input=payload.getvalue(),capture_output=True,check=True,timeout=10)
result=docker('start','-a',cid,timeout=100,check=False)
(args.output/'build.log').write_text(result.stdout+result.stderr)
if result.returncode:raise RuntimeError('Existing geometry kernels did not compile')
docker('cp',cid+':/opt/missioncore',str(args.output/'kernels'))
report['kernels']={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (args.output/'kernels').iterdir()}
tag=('ndc-mission-core-terrain:pcl-ground-' if args.ground else 'ndc-mission-core-nav2:1.1.17-rover-')+identity[:16]
image=docker('commit','--change','ENTRYPOINT ["/bin/bash", "/sources/runtime_entrypoint.sh"]',
'--change','CMD ["bash"]','--change','LABEL com.nodedc.role=nav2-runtime',cid,tag,timeout=120).stdout.strip()
report.update(image=image,tag=tag,status='built')
except BaseException as error:
report.update(status='failed',error=type(error).__name__+': '+str(error));raise
finally:
if cid:
docker('rm','-f',cid)
report['cleanup_confirmed']=not docker('ps','-aq','--filter','id='+cid).stdout.strip()
report['elapsed_s']=time.monotonic()-started
(args.output/'build.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report))
if __name__=='__main__':main()