Files
leleka/scripts/build-cuda-engine-in-docker.py
T
Pavlo Ratushnyi 4125a0305f
Linux / verify (pull_request) Successful in 2m46s
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 19s
Linux / linux-static-cli (pull_request) Successful in 5m37s
Linux / release-cli (pull_request) Skipped
fix: emit valid CUDA toolchain metadata JSON
2026-10-06 05:51:30 +02:00

311 lines
16 KiB
Python

#!/usr/bin/env python3
"""Build and audit the CUDA engine in a pinned CPU-only Linux Docker container."""
import argparse
import hashlib
from io import BytesIO
import json
import os
from pathlib import Path
from pathlib import PurePosixPath
import re
import shutil
import ssl
import subprocess
import tarfile
import tempfile
import uuid
REPO = Path(__file__).resolve().parents[1].resolve()
DOCKERFILE = REPO / 'deploy/Dockerfile.cuda-builder'
BASE = 'ubuntu:24.04@sha256:f610ab94648195aa356059f5b41d6085c9d4d903c072430cdd1af7bdb646106b'
PLATFORM = 'linux/amd64'
CONTAINER_BUILD = r'''set -euo pipefail
test -x /opt/cuda/bin/nvcc
test -f /opt/cuda/lib/libcudart_static.a
shopt -s nullglob
devices=(/dev/nvidia*)
if (( ${#devices[@]} != 0 )); then
echo "CUDA builder unexpectedly sees NVIDIA device nodes: ${devices[*]}" >&2
exit 91
fi
test "${CUDA_VISIBLE_DEVICES+x}" = x && test -z "$CUDA_VISIBLE_DEVICES"
test "${NVIDIA_VISIBLE_DEVICES}" = void
mkdir -p /tmp/home /build/engine /build/output
python3 - <<'PY'
import json, os, subprocess
def capture(*args):
return subprocess.check_output(args, text=True, stderr=subprocess.STDOUT).strip()
data = {
'builder_base': os.environ['LELEKA_BUILDER_BASE'],
'builder_platform': 'linux/amd64',
'apt_snapshot': '20260917T000000Z',
'nvidia_device_nodes_visible': False,
'cuda_visible_devices': os.environ['CUDA_VISIBLE_DEVICES'],
'nvidia_visible_devices': os.environ['NVIDIA_VISIBLE_DEVICES'],
'nvcc': capture('/opt/cuda/bin/nvcc', '--version'),
'gcc': capture('gcc-13', '--version'),
'gxx': capture('g++-13', '--version'),
'cmake': capture('cmake', '--version'),
'ninja': capture('ninja', '--version'),
'make': capture('make', '--version'),
'packages': capture('dpkg-query', '-W', '-f=${Package}=${Version}\\n',
'ca-certificates', 'cmake', 'gcc-13', 'g++-13', 'git', 'make', 'ninja-build', 'python3', 'python3-numpy'),
}
with open(os.environ['LELEKA_TOOLCHAIN_METADATA'], 'w', encoding='utf-8') as stream:
json.dump(data, stream, indent=2)
stream.write(chr(10))
PY
scripts/build-static-cuda.sh
install -m 0755 /build/engine/strata "$LELEKA_ENGINE_OUTPUT"
'''
def digest(path):
h = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
h.update(block)
return h.hexdigest()
def extract_git_archive(archive, destination):
"""Extract only regular files/directories from git archive on old and new Python."""
root = destination.resolve()
with tarfile.open(fileobj=BytesIO(archive), mode='r:') as source:
members = source.getmembers()
seen = set()
checked = []
for member in members:
name = member.name
normalized_name = name.rstrip('/') if member.isdir() else name
path = PurePosixPath(normalized_name)
if (not normalized_name or path.is_absolute() or
any(part in ('', '.', '..') for part in normalized_name.split('/'))):
raise ValueError(f'unsafe path in committed source archive: {name!r}')
if not (member.isdir() or member.isfile()):
raise ValueError(f'unsupported entry in committed source archive: {name!r}')
target = root.joinpath(*path.parts)
if target == root or root not in target.parents:
raise ValueError(f'archive path escapes staging directory: {name!r}')
if path in seen:
raise ValueError(f'duplicate path in committed source archive: {name!r}')
seen.add(path)
checked.append((member, path, target))
directories = {root}
for member, path, target in checked:
if member.isdir():
directories.add(target)
continue
directories.update(parent for parent in target.parents if parent == root or root in parent.parents)
target.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
payload = source.extractfile(member)
if payload is None:
raise ValueError(f'missing file payload in committed source archive: {member.name!r}')
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0)
fd = os.open(target, flags, member.mode & 0o777 & ~0o6000)
with os.fdopen(fd, 'wb') as output, payload:
shutil.copyfileobj(payload, output)
for directory in sorted(directories, key=lambda item: len(item.parts), reverse=True):
if directory.is_dir():
directory.chmod(0o755)
def stage_tracked_source(destination):
changed = subprocess.run(['git', '-C', str(REPO), 'diff', '--quiet', 'HEAD', '--'], check=False)
if changed.returncode == 1:
raise ValueError('refusing to build from a checkout with tracked changes; commit the source first')
if changed.returncode < 0:
raise ValueError('git diff was interrupted while checking the source checkout')
if changed.returncode != 0:
raise subprocess.CalledProcessError(changed.returncode, changed.args)
archive = subprocess.check_output(['git', '-C', str(REPO), 'archive', '--format=tar', 'HEAD'])
try:
extract_git_archive(archive, destination)
except (OSError, tarfile.TarError, ValueError) as error:
raise ValueError(f'could not safely stage the committed source tree: {error}') from error
return subprocess.check_output(['git', '-C', str(REPO), 'rev-parse', 'HEAD'], text=True).strip(), hashlib.sha256(archive).hexdigest()
def outside_repo(path, label):
resolved = path.resolve()
repo = REPO.resolve()
if resolved == repo or repo in resolved.parents:
raise ValueError(f'{label} must stay outside the source checkout')
if any(char in str(resolved) for char in ',:\n'):
raise ValueError(f'{label} contains a character unsupported in Docker mount paths')
return resolved
def run(command):
subprocess.run([str(arg) for arg in command], check=True)
def capture(command):
return subprocess.check_output([str(arg) for arg in command], text=True).strip()
def runner_ca_bundle():
"""Return the runner's CA bundle for bootstrapping HTTPS in the base image."""
cafile = ssl.get_default_verify_paths().cafile
if not cafile:
raise ValueError('Linux runner has no default CA bundle path')
try:
path = Path(cafile).resolve(strict=True)
except OSError as error:
raise ValueError('Linux runner CA bundle is missing or unreadable') from error
if not path.is_file():
raise ValueError('Linux runner CA bundle is not a regular file')
contents = path.read_bytes()
if not contents or b'-----BEGIN CERTIFICATE-----' not in contents:
raise ValueError('Linux runner CA bundle is empty or invalid')
return contents
def build(args):
docker = shutil.which(args.docker) if '/' not in args.docker else args.docker
if not docker:
raise ValueError('Docker CLI is not available')
toolkit = args.toolkit.resolve(strict=True)
if not (toolkit / 'bin/nvcc').is_file() or not (toolkit / 'lib/libcudart_static.a').is_file():
raise ValueError('toolkit is missing nvcc or static CUDA runtime')
build_dir = outside_repo(args.build_dir, 'build directory')
engine_output = outside_repo(args.output, 'engine output')
metadata_output = outside_repo(args.metadata, 'metadata output')
for path in (toolkit, build_dir, engine_output.parent, metadata_output.parent):
if any(char in str(path) for char in ',:\n'):
raise ValueError('a Docker mount path contains an unsupported character')
output_roots = (engine_output.parent, metadata_output.parent)
if any(build_dir == output or build_dir in output.parents or output in build_dir.parents
for output in output_roots):
raise ValueError('build and output directories must not overlap')
if engine_output.exists() or metadata_output.exists():
raise ValueError('refusing to overwrite an existing build output')
if build_dir.exists() and any(build_dir.iterdir()):
raise ValueError('build directory must be fresh and empty')
build_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
engine_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
metadata_output.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
dockerfile = DOCKERFILE.read_text(encoding='utf-8')
match = re.search(r'^FROM --platform=linux/amd64 (\S+)$', dockerfile, re.M)
if not match or match.group(1) != BASE:
raise ValueError('CUDA builder Dockerfile must use the reviewed immutable amd64 base')
if not re.fullmatch(r'[A-Za-z0-9_.-]{1,46}', args.image_tag):
raise ValueError('invalid image tag')
nonce = uuid.uuid4().hex[:12]
tag = f'leleka-cuda-builder:{args.image_tag}-{nonce}'
image_built = False
container_id = None
staging_container_id = None
volume_names = {kind: f'leleka-cuda-{kind}-{args.image_tag}-{nonce}' for kind in ('source', 'toolkit', 'build')}
owned_volumes = []
source = build_dir / 'source'
try:
source.mkdir(mode=0o700)
source_commit, source_archive_sha256 = stage_tracked_source(source)
ca_bundle = runner_ca_bundle()
ca_bundle_sha256 = hashlib.sha256(ca_bundle).hexdigest()
with tempfile.TemporaryDirectory(prefix='leleka-cuda-docker-context-') as context_name:
context = Path(context_name)
image_context = context / 'image'
image_context.mkdir()
shutil.copyfile(DOCKERFILE, image_context / 'Dockerfile')
(image_context / 'runner-ca-certificates.crt').write_bytes(ca_bundle)
run([docker, 'build', '--platform', PLATFORM, '--pull', '--file', image_context / 'Dockerfile',
'--label', f'leleka.cuda-builder.run={args.image_tag}', '--tag', tag, image_context])
image_built = True
image_id = subprocess.check_output([docker, 'image', 'inspect', '--format', '{{.Id}}', tag], text=True).strip()
if not re.fullmatch(r'sha256:[0-9a-f]{64}', image_id):
raise ValueError('Docker returned an invalid builder image ID')
for kind, volume in volume_names.items():
created = capture([docker, 'volume', 'create', '--label', f'leleka.cuda-builder.run={args.image_tag}', volume])
if created != volume:
raise ValueError(f'Docker returned an unexpected {kind} volume name')
owned_volumes.append(volume)
staging_container_id = capture([
docker, 'create', '--platform', PLATFORM, '--network', 'none',
'--label', f'leleka.cuda-builder.run={args.image_tag}',
'--mount', f'type=volume,source={volume_names["source"]},target=/stage/source',
'--mount', f'type=volume,source={volume_names["toolkit"]},target=/stage/toolkit',
'--entrypoint', '/bin/true', tag
])
if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', staging_container_id):
raise ValueError('Docker returned an invalid staging container ID')
run([docker, 'cp', f'{source}/.', f'{staging_container_id}:/stage/source'])
run([docker, 'cp', f'{toolkit}/.', f'{staging_container_id}:/stage/toolkit'])
run([docker, 'rm', staging_container_id])
staging_container_id = None
uid, gid = os.getuid(), os.getgid()
container_id = capture([docker, 'create', '--platform', PLATFORM, '--network', 'bridge', '--read-only',
'--label', f'leleka.cuda-builder.run={args.image_tag}',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '512',
'--tmpfs', f'/tmp:rw,nosuid,nodev,size=1g,uid={uid},gid={gid}', '--user', f'{uid}:{gid}',
'--mount', f'type=volume,source={volume_names["source"]},target=/workspace,readonly',
'--mount', f'type=volume,source={volume_names["toolkit"]},target=/opt/cuda,readonly',
'--mount', f'type=volume,source={volume_names["build"]},target=/build',
'--workdir', '/workspace',
'--env', 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
'--env', 'HOME=/tmp/home', '--env', 'CUDA_VISIBLE_DEVICES=', '--env', 'NVIDIA_VISIBLE_DEVICES=void',
'--env', f'LELEKA_BUILDER_BASE={BASE}', '--env', 'LELEKA_ENGINE_OUTPUT=/build/output/strata',
'--env', 'LELEKA_TOOLCHAIN_METADATA=/build/output/CUDA-BUILDER.json',
'--env', 'CUDACXX=/opt/cuda/bin/nvcc', '--env', 'CUDAToolkit_ROOT=/opt/cuda',
'--env', 'CUDAHOSTCXX=/usr/bin/g++-13', '--env', 'CC=/usr/bin/gcc-13', '--env', 'CXX=/usr/bin/g++-13',
'--env', 'STRATA_BUILD_DIR=/build/engine', '--env', 'BUILD_JOBS=1', '--env', 'CUDA_ARCHITECTURES=120',
tag, '-lc', CONTAINER_BUILD])
if not re.fullmatch(r'[A-Fa-f0-9]{12,64}', container_id):
raise ValueError('Docker returned an invalid build container ID')
run([docker, 'start', '--attach', container_id])
run([docker, 'cp', f'{container_id}:/build/output/strata', engine_output])
run([docker, 'cp', f'{container_id}:/build/output/CUDA-BUILDER.json', metadata_output])
if not engine_output.is_file() or engine_output.is_symlink():
raise ValueError('Docker build did not produce a regular engine file')
engine_output.chmod(0o755)
container_metadata = json.loads(metadata_output.read_text(encoding='utf-8'))
expected = {'builder_base': BASE, 'builder_platform': PLATFORM,
'nvidia_device_nodes_visible': False, 'cuda_visible_devices': '', 'nvidia_visible_devices': 'void'}
if any(container_metadata.get(key) != value for key, value in expected.items()):
raise ValueError('container toolchain metadata violates CPU-only builder policy')
metadata = {'schema_version': 1, **container_metadata, 'source_commit': source_commit,
'source_archive_sha256': source_archive_sha256,
'runner_ca_bundle_sha256': ca_bundle_sha256, 'builder_image_id': image_id,
'engine_sha256': digest(engine_output), 'engine_bytes': engine_output.stat().st_size,
'gpu_tested': False, 'model_tested': False,
'qualification': 'CUDA compilation, ELF dependency audit and GPU-hidden --help only.'}
metadata_output.write_text(json.dumps(metadata, indent=2) + '\n', encoding='utf-8')
return metadata
finally:
if source.exists():
shutil.rmtree(source)
for owned_container in (container_id, staging_container_id):
if owned_container:
subprocess.run([docker, 'rm', '--force', owned_container], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for volume in owned_volumes:
subprocess.run([docker, 'volume', 'rm', '--force', volume], check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if image_built:
subprocess.run([docker, 'image', 'rm', tag], check=False, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--toolkit', type=Path, required=True, help='checksum-verified toolkit from bootstrap-cuda-toolkit.py')
parser.add_argument('--build-dir', type=Path, required=True, help='fresh private directory outside the checkout')
parser.add_argument('--output', type=Path, required=True, help='new engine file path outside the checkout')
parser.add_argument('--metadata', type=Path, required=True, help='new provenance JSON path outside the checkout')
parser.add_argument('--image-tag', required=True, help='unique CI run/attempt suffix for the temporary builder image')
parser.add_argument('--docker', default='docker', help='Docker CLI (used by tests)')
args = parser.parse_args()
try:
result = build(args)
print(json.dumps(result, sort_keys=True))
except (OSError, ValueError, subprocess.SubprocessError, json.JSONDecodeError) as error:
parser.exit(1, f'Docker CUDA build failed: {error}\n')
if __name__ == '__main__':
main()