Files
leleka/scripts/build-linux-package.py
T

295 lines
15 KiB
Python

#!/usr/bin/env python3
"""Offline release assembly; production serving has no Python dependency."""
import argparse
import contextlib
import ctypes
import stat
import fcntl
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import uuid
REPO = Path(__file__).resolve().parents[1]
TARGET = 'x86_64-unknown-linux-musl'
NAME = 'leleka-api-linux-x86_64-musl'
LIMIT = 1024 ** 3
def run(args, **kwargs):
return subprocess.check_output([str(x) for x in args], text=True, **kwargs).strip()
def sha256(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def build_features(path, revision):
"""Read a bounded, exact-schema static CUDA feature receipt without following links."""
if path is None:
return None
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as source:
if not stat.S_ISREG(os.fstat(source.fileno()).st_mode):
raise ValueError('build feature receipt must be a regular file')
raw = source.read(65537)
if len(raw) > 65536:
raise ValueError('build feature receipt exceeds size limit')
try:
record = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as error:
raise ValueError('build feature receipt must be UTF-8 JSON') from error
if (not isinstance(record, dict) or set(record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(record['schema_version']) is not int or record['schema_version'] != 1 or
record['source_revision'] != revision or
not isinstance(record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
record['cuda_architectures'])):
raise ValueError('unsupported or source-mismatched build feature receipt')
canonical = (json.dumps(record, sort_keys=True, indent=2) + '\n').encode()
if raw != canonical:
raise ValueError('build feature receipt is not canonical JSON')
features = record['features']
if (not isinstance(features, dict) or set(features) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in features.values()) or
features['cuda'] is not True or features['cuda_static_runtime'] is not True or
features['cxx_static_runtime'] is not True or
features['kar_experts'] is not False or features['ple_trace'] is not False):
raise ValueError('build feature receipt violates the static CUDA PLE package contract')
return record, hashlib.sha256(raw).hexdigest()
def source_check(repo, revision):
if not re.fullmatch(r'[0-9a-f]{40}', revision):
raise ValueError('source revision must be a full lowercase Git SHA')
if run(['git', '-C', repo, 'rev-parse', 'HEAD']) != revision:
raise ValueError('source revision differs from checkout HEAD')
if run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=all']):
raise ValueError('source checkout must be clean before packaging; commit source changes or exclude generated files')
def snapshot(source, dest, expected):
if not re.fullmatch(r'[0-9a-f]{64}', expected):
raise ValueError('engine SHA256 must be 64 lowercase hexadecimal characters')
digest, size = hashlib.sha256(), 0
fd = os.open(source, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
with os.fdopen(fd, 'rb') as src, dest.open('xb') as dst:
if not stat.S_ISREG(os.fstat(src.fileno()).st_mode):
raise ValueError('engine must be a regular file')
while block := src.read(65536):
size += len(block)
if size > LIMIT:
raise ValueError('engine exceeds 1 GiB package limit')
digest.update(block)
dst.write(block)
if digest.hexdigest() != expected:
raise ValueError('engine SHA256 mismatch')
dest.chmod(0o700)
return size
def static_outer(binary):
headers = run(['readelf', '-lW', binary])
dynamic = run(['readelf', '-dW', binary])
if 'INTERP' in headers or '(NEEDED)' in dynamic:
raise ValueError('outer executable must be static musl (no INTERP/NEEDED)')
return {'program_headers': headers, 'dynamic_section': dynamic}
def loader_probe(binary, probe, audit, container=False):
if not container:
run([binary, 'provision', '--config', probe],
env={'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': '',
'NVIDIA_VISIBLE_DEVICES': 'void'}, timeout=30)
return {'environment': 'assembly-host'}
# Use the same immutable base as the runtime image. A CPU runner's libc
# need not satisfy the separately audited embedded engine's libc baseline.
spec = importlib.util.spec_from_file_location('runtime_image', REPO / 'scripts/build-runtime-image.py')
runtime = importlib.util.module_from_spec(spec)
spec.loader.exec_module(runtime)
runtime.docker('pull', '--platform', 'linux/amd64', runtime.BASE, timeout=300)
glibc = runtime.check_glibc({'engine_elf_audit': audit},
runtime.isolated_run(runtime.BASE, ['GNU_LIBC_VERSION'], entrypoint='getconf'))
image_id = runtime.docker('image', 'inspect', '--format', '{{.Id}}', runtime.BASE).stdout.strip()
name = 'strata-package-probe-' + uuid.uuid4().hex
staging_name = name + '-stage'
volume = name
try:
with tempfile.TemporaryDirectory(prefix='strata-package-probe-') as tmp:
copied = Path(tmp) / 'cli'
shutil.copyfile(binary, copied)
copied.chmod(0o755)
config = Path(tmp) / 'probe.json'
shutil.copyfile(probe, config)
config.chmod(0o644)
runtime.docker('volume', 'create', volume)
runtime.docker('create', '--name', staging_name, '--platform', 'linux/amd64',
'--network', 'none', '--cap-drop', 'ALL',
'--mount', 'type=volume,source=' + volume + ',target=/probe',
'--entrypoint', '/bin/true', runtime.BASE)
# The staging container is never started. The serving probe receives
# only a read-only volume, so docker cp cannot mutate its rootfs.
runtime.docker('cp', copied, staging_name + ':/probe/cli', timeout=180)
runtime.docker('cp', config, staging_name + ':/probe/probe.json')
runtime.docker('create', '--name', name, '--platform', 'linux/amd64',
'--network', 'none', '--read-only', '--user', '65532:65532',
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
'--tmpfs', '/tmp:rw,nosuid,nodev,size=1g',
'--mount', 'type=volume,source=' + volume + ',target=/probe,readonly',
'-e', 'CUDA_VISIBLE_DEVICES=', '-e', 'NVIDIA_VISIBLE_DEVICES=void',
'-e', 'LD_LIBRARY_PATH=', '--entrypoint', '/bin/sh', runtime.BASE,
'-c', 'for p in /dev/nvidia*; do if [ -e "$p" ]; then '
'echo "package probe refuses NVIDIA devices" >&2; exit 1; fi; done; '
'exec /probe/cli "$@"',
'package-probe', 'provision', '--config', '/probe/probe.json')
result = runtime.docker('start', '--attach', name, timeout=60, check=False)
code = runtime.docker('inspect', '--format', '{{.State.ExitCode}}', name).stdout.strip()
if result.returncode != 0 or code != '0':
raise ValueError('pinned runtime package provision failed: ' + result.stderr.strip())
finally:
original_failure = sys.exc_info()[0] is not None
errors = []
for command in [('rm', '-f', name), ('rm', '-f', staging_name), ('volume', 'rm', volume)]:
try:
cleaned = runtime.docker(*command, check=False)
if cleaned.returncode and 'No such ' not in cleaned.stderr:
errors.append(cleaned.stderr.strip())
except (OSError, subprocess.SubprocessError) as error:
errors.append(str(error))
if errors:
print('Package probe cleanup failed: ' + '; '.join(errors), file=sys.stderr)
if not original_failure:
raise ValueError('owned package probe cleanup failed')
return {'environment': 'pinned-runtime-container', 'base': runtime.BASE,
'image_id': image_id, 'glibc': glibc, 'user': '65532:65532', 'gpu_tested': False}
@contextlib.contextmanager
def lock(path):
# Caller-controlled build/output paths are private; keep the inode for reuse.
fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
finally:
os.close(fd)
def publish(source, output):
# Linux atomic no-replace protects even against a non-cooperating publisher.
libc = ctypes.CDLL(None, use_errno=True)
rename = getattr(libc, 'renameat2', None)
if rename is None:
raise ValueError('host libc must provide renameat2 for safe publication')
rename.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint]
rename.restype = ctypes.c_int
if rename(-100, os.fsencode(source), -100, os.fsencode(output), 1) != 0:
code = ctypes.get_errno()
raise OSError(code, os.strerror(code))
def assemble(args):
if platform.system() != 'Linux' or platform.machine() != 'x86_64':
raise ValueError('package assembly requires Linux x86_64')
source_check(REPO, args.revision)
features = build_features(getattr(args, 'build_features', None), args.revision)
if args.cpu_fixture and features is not None:
raise ValueError('CPU fixtures cannot claim CUDA build features')
output = args.output.absolute()
output.parent.mkdir(parents=True, exist_ok=True)
output = output.parent.resolve() / output.name
target_dir = args.cargo_target_dir.resolve()
if output == target_dir or output in target_dir.parents or target_dir in output.parents:
raise ValueError('package output and Cargo build directory must be disjoint')
target_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
with lock(output.parent / ('.' + output.name + '.package-lock')), lock(target_dir / '.package-lock'):
if os.path.lexists(output):
raise ValueError('output already exists; select a new versioned directory')
with tempfile.TemporaryDirectory(prefix='.' + output.name + '.stage-', dir=output.parent) as tmp:
stage = Path(tmp)
engine = stage / 'engine'
size = snapshot(args.engine.resolve(), engine, args.sha256)
if args.cpu_fixture:
audit = {'kind': 'cpu-fixture', 'gpu_tested': False}
else:
spec = importlib.util.spec_from_file_location('elf_audit', REPO / 'scripts/check-static-cuda-elf.py')
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)
audit = checker.inspect(engine)
env = dict(os.environ, STRATA_EMBED_ENGINE_PATH=str(engine),
STRATA_EMBED_ENGINE_SHA256=args.sha256,
STRATA_EMBED_ENGINE_REVISION=args.revision,
CARGO_TARGET_DIR=str(target_dir), CUDA_VISIBLE_DEVICES='')
env.pop('LD_LIBRARY_PATH', None)
subprocess.run(['cargo', 'build', '--manifest-path', str(REPO / 'control-plane/Cargo.toml'),
'--locked', '--release', '--target', TARGET, '--bin', 'leleka-api'],
env=env, check=True)
published = stage / 'package'
published.mkdir(mode=0o700)
binary = published / NAME
shutil.copyfile(target_dir / TARGET / 'release/leleka-api', binary)
binary.chmod(0o700)
outer = static_outer(binary)
probe_env = {'PATH': os.defpath, 'CUDA_VISIBLE_DEVICES': ''}
info = json.loads(run([binary, 'engine-info'], env=probe_env, timeout=30))
if not (info['embedded'] and info['sha256'] == args.sha256 and
info['declared_source_revision'] == args.revision and info['bytes'] == size and
info['target_os'] == 'linux' and info['target_arch'] == 'x86_64'):
raise ValueError('combined engine identity does not match pinned input')
probe = stage / 'probe.json'
probe.write_text(json.dumps({'engine': {'executable': '@embedded'}, 'engine_probe': True}))
loader = loader_probe(binary, probe, audit,
getattr(args, 'probe_in_runtime_image', False))
source_check(REPO, args.revision)
provenance = {'schema_version': 1, 'kind': 'cpu-fixture' if args.cpu_fixture else 'static-cuda-preview',
'source_revision': args.revision, 'target': TARGET, 'engine': info,
'engine_elf_audit': audit, 'outer_elf_audit': outer,
'loader_probe': loader,
'cargo_lock_sha256': sha256(REPO / 'Cargo.lock'),
'rustc': run(['rustc', '--version']), 'cargo': run(['cargo', '--version']),
'gpu_tested': False, 'model_tested': False, 'clean_node_tested': False,
'qualification': 'Exact payload identity, outer ELF and GPU-hidden loader help only; no inference.',
'source_provenance': 'Operator/CI-declared engine revision, not binary-to-source attestation.'}
if features is not None:
provenance['build_features'], provenance['build_features_sha256'] = features
(published / 'PROVENANCE.json').write_text(json.dumps(provenance, indent=2) + '\n')
(published / 'SHA256SUMS').write_text(''.join(f'{sha256(p)} {p.name}\n' for p in [binary, published / 'PROVENANCE.json']))
if os.path.lexists(output):
raise ValueError('output appeared during assembly; refusing replacement')
publish(published, output)
return {'output': str(output), 'kind': provenance['kind'], 'gpu_tested': False}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--engine', type=Path, required=True)
parser.add_argument('--sha256', required=True)
parser.add_argument('--revision', required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--cargo-target-dir', type=Path, required=True, help='dedicated build directory; do not run other Cargo commands here concurrently')
parser.add_argument('--cpu-fixture', action='store_true', help='explicit non-CUDA test artifact; never a GPU release')
parser.add_argument('--build-features', type=Path,
help='exact build feature receipt emitted by build-static-cuda.sh')
parser.add_argument('--probe-in-runtime-image', action='store_true',
help='execute actual provision in the pinned runtime base instead of the assembly host')
args = parser.parse_args()
try:
print(json.dumps(assemble(args)))
except (ValueError, OSError, subprocess.SubprocessError) as error:
parser.exit(1, f'Package assembly failed: {error}\n')
if __name__ == '__main__':
main()