Files
leleka/scripts/build-runtime-image.py
T
Pavlo Ratushnyi bbc8018e8b
Linux / keyless-cuda-gate (pull_request) Skipped
Desktop foundation / core (ubuntu-latest) (pull_request) Successful in 2m50s
Linux / verify (pull_request) Successful in 6m33s
Linux / keyless-cuda (pull_request) Skipped
Linux / static-cuda-package (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-cli-container (pull_request) Successful in 1m34s
Linux / linux-static-cli (pull_request) Successful in 6m26s
Linux / release-cli (pull_request) Skipped
Bound runtime image probe waits and cleanup
2026-10-08 00:53:28 +02:00

292 lines
14 KiB
Python

#!/usr/bin/env python3
"""Build-time only: verify a combined package and assemble a private OCI image."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import uuid
REPO = Path(__file__).resolve().parents[1]
NAME = 'strata-next-linux-x86_64-musl'
FILES = {NAME, 'PROVENANCE.json', 'SHA256SUMS'}
# Official Ubuntu 26.04 linux/amd64 manifest, observed 2026-10-04; glibc is probed.
BASE = 'ubuntu@sha256:88a381d5b5eeb2b35d3ad70925a362c37ce569daf43ede89ff818ec20e4d3794'
PROBE_INFRA_TIMEOUT = 120
PROBE_APP_TIMEOUT = 30
PROBE_OUTPUT_LIMIT = 64 * 1024
def digest(path):
with path.open('rb') as source:
return hashlib.file_digest(source, 'sha256').hexdigest()
def frozen_file(source, dest, limit):
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('package entries must be regular files')
total = 0
while block := src.read(65536):
total += len(block)
if total > limit:
raise ValueError('package entry exceeds size limit')
dst.write(block)
def freeze(package, stage, receipt_sha, cpu_fixture):
if not re.fullmatch(r'[0-9a-f]{64}', receipt_sha):
raise ValueError('receipt SHA256 must be 64 lowercase hex characters')
if {p.name for p in package.iterdir()} != FILES:
raise ValueError('package must contain exactly binary, provenance and SHA256SUMS')
for name in FILES:
frozen_file(package / name, stage / name, 1024**3 if name == NAME else 1024**2)
if digest(stage / 'SHA256SUMS') != receipt_sha:
raise ValueError('pinned receipt SHA256 mismatch')
hashes = {}
for line in (stage / 'SHA256SUMS').read_text().splitlines():
match = re.fullmatch(r'([0-9a-f]{64}) (strata-next-linux-x86_64-musl|PROVENANCE.json)', line)
if not match or match[2] in hashes:
raise ValueError('invalid or duplicate receipt entry')
hashes[match[2]] = match[1]
if set(hashes) != {NAME, 'PROVENANCE.json'}:
raise ValueError('incomplete receipt')
if any(digest(stage / name) != sha for name, sha in hashes.items()):
raise ValueError('package file checksum mismatch')
p = json.loads((stage / 'PROVENANCE.json').read_text())
kind = 'cpu-fixture' if cpu_fixture else 'static-cuda-preview'
if (not isinstance(p, dict) or type(p.get('schema_version')) is not int or p['schema_version'] != 1 or p.get('kind') != kind or
p.get('target') != 'x86_64-unknown-linux-musl' or
not re.fullmatch(r'[0-9a-f]{40}', p.get('source_revision', ''))):
raise ValueError('unsupported package provenance or explicit fixture mode mismatch')
feature_record = p.get('build_features')
feature_sha = p.get('build_features_sha256')
if feature_record is not None or feature_sha is not None:
if (not isinstance(feature_record, dict) or set(feature_record) != {
'schema_version', 'source_revision', 'cuda_architectures', 'features'} or
type(feature_record['schema_version']) is not int or feature_record['schema_version'] != 1 or
feature_record['source_revision'] != p['source_revision'] or
not isinstance(feature_record['cuda_architectures'], str) or
not re.fullmatch(r'[0-9]+(?:-(?:real|virtual))?(?:;[0-9]+(?:-(?:real|virtual))?)*',
feature_record['cuda_architectures']) or
not isinstance(feature_sha, str) or
not re.fullmatch(r'[0-9a-f]{64}', feature_sha)):
raise ValueError('invalid static CUDA build feature provenance')
feature_values = feature_record['features']
if (not isinstance(feature_values, dict) or set(feature_values) != {
'cuda', 'cuda_static_runtime', 'cxx_static_runtime', 'kar_ple', 'kar_experts', 'ple_trace'} or
any(type(value) is not bool for value in feature_values.values()) or
feature_values['cuda'] is not True or feature_values['cuda_static_runtime'] is not True or
feature_values['cxx_static_runtime'] is not True or
feature_values['kar_experts'] is not False or feature_values['ple_trace'] is not False):
raise ValueError('invalid static CUDA feature selection')
canonical = (json.dumps(feature_record, sort_keys=True, indent=2) + '\n').encode()
if hashlib.sha256(canonical).hexdigest() != feature_sha:
raise ValueError('static CUDA build feature digest mismatch')
elif not cpu_fixture:
raise ValueError('CUDA package lacks an explicit build feature receipt')
engine = p.get('engine', {})
if (engine.get('embedded') is not True or engine.get('target_os') != 'linux' or
engine.get('target_arch') != 'x86_64' or
engine.get('declared_source_revision') != p['source_revision'] or
type(engine.get('bytes')) is not int or not 0 < engine['bytes'] <= 1024**3 or
not re.fullmatch(r'[0-9a-f]{64}', engine.get('sha256', ''))):
raise ValueError('invalid embedded engine identity')
if not cpu_fixture:
audit = p.get('engine_elf_audit', {})
if audit.get('toolkit_shared_libraries') is not False or audit.get('host_glibc_required') is not True:
raise ValueError('missing static CUDA ELF audit')
version(audit.get('minimum_glibc', ''))
return p
def version(value):
if not isinstance(value, str) or not re.fullmatch(r'[0-9]+\.[0-9]+(?:\.[0-9]+)?', value):
raise ValueError('invalid glibc version')
return tuple(map(int, value.split('.'))) + (0,) * (3 - len(value.split('.')))
def check_glibc(provenance, output):
match = re.fullmatch(r'glibc ([0-9]+\.[0-9]+(?:\.[0-9]+)?)\s*', output)
if not match:
raise ValueError('base does not report GNU glibc')
minimum = provenance.get('engine_elf_audit', {}).get('minimum_glibc', '0.0')
if version(match[1]) < version(minimum):
raise ValueError(f'base glibc {match[1]} is below engine requirement {minimum}; choose a compatible pinned base or rebuild engine')
return match[1]
def docker(*args, timeout=30, check=True):
return subprocess.run(['docker', *map(str, args)], capture_output=True, text=True,
check=check, timeout=timeout)
def _bounded_output(value, stream):
if not isinstance(value, str) or len(value.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
raise ValueError(f'isolated CLI {stream} exceeds {PROBE_OUTPUT_LIMIT}-byte limit')
return value
def _report_best_effort(message):
try:
print(message, file=sys.stderr, flush=True)
except BaseException:
pass
def _safe_report(message):
try:
_report_best_effort(message)
except BaseException:
pass
def _diagnose_owned_container(name):
for label, args in (
('inspect', ('inspect', '--format', '{{json .State}}', name)),
('logs', ('logs', '--tail', '40', name)),
):
try:
result = docker(*args, timeout=8, check=False)
output = (result.stdout or '') + (result.stderr or '')
if len(output.encode('utf-8')) > PROBE_OUTPUT_LIMIT:
output = '[earlier output truncated]\n' + output[-PROBE_OUTPUT_LIMIT:]
_safe_report(
f'Owned runtime-image probe {label} (exit {result.returncode}):\n{output}')
except BaseException as error:
_safe_report(
f'Owned runtime-image probe {label} unavailable: {type(error).__name__}')
def isolated_run(image, arguments, *, entrypoint=None):
name = 'strata-image-probe-' + uuid.uuid4().hex
args = ['create', '--name', name, '--platform', 'linux/amd64', '--network', 'none',
'--read-only', '--user', '65532:65532', '--cap-drop', 'ALL',
'--security-opt', 'no-new-privileges', '-e', 'CUDA_VISIBLE_DEVICES=',
'-e', 'NVIDIA_VISIBLE_DEVICES=void']
if entrypoint:
args += ['--entrypoint', entrypoint]
primary_error = None
try:
created = docker(*args, image, *arguments, timeout=PROBE_INFRA_TIMEOUT)
_bounded_output(created.stdout, 'create output')
docker('start', name, timeout=PROBE_INFRA_TIMEOUT)
waited = docker('wait', name, timeout=PROBE_APP_TIMEOUT, check=False)
_bounded_output(waited.stdout, 'wait status')
_bounded_output(waited.stderr, 'wait stderr')
if waited.returncode:
raise subprocess.CalledProcessError(
waited.returncode, ['docker', 'wait', name],
output=waited.stdout, stderr=waited.stderr)
if not re.fullmatch(r'(?:0|[1-9][0-9]{0,2})\n?', waited.stdout):
raise ValueError('docker wait returned a malformed CLI exit status')
exit_status = int(waited.stdout.rstrip('\n'))
if exit_status > 255:
raise ValueError('docker wait returned a CLI exit status outside 0..255')
logs = docker('logs', name, timeout=30, check=False)
stdout = _bounded_output(logs.stdout, 'stdout')
stderr = _bounded_output(logs.stderr, 'stderr')
if logs.returncode:
raise subprocess.CalledProcessError(
logs.returncode, ['docker', 'logs', name], output=stdout, stderr=stderr)
if exit_status:
raise subprocess.CalledProcessError(
exit_status, ['docker', 'container', 'probe', name],
output=stdout, stderr=stderr)
if stderr:
_report_best_effort(f'Runtime-image probe stderr:\n{stderr}')
return stdout
except BaseException as error:
primary_error = error
try:
_diagnose_owned_container(name)
except BaseException as diagnostic_error:
_safe_report(
f'Owned runtime-image probe diagnostics failed: {type(diagnostic_error).__name__}')
raise
finally:
cleanup_error = None
try:
result = docker('rm', '-f', name, timeout=10, check=False)
if result.returncode:
cleanup_error = subprocess.CalledProcessError(
result.returncode, ['docker', 'rm', '-f', name],
output=result.stdout, stderr=result.stderr)
except BaseException as error:
cleanup_error = error
if cleanup_error is not None:
if primary_error is None:
raise cleanup_error
_safe_report(
f'Owned runtime-image probe cleanup failed after '
f'{type(primary_error).__name__}: {type(cleanup_error).__name__}')
def assemble(args):
if not re.fullmatch(r'[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}', args.base):
raise ValueError('base must be an explicit lowercase repository@sha256 digest')
image = None
success = False
with tempfile.TemporaryDirectory(prefix='strata-oci-') as tmp:
stage = Path(tmp)
p = freeze(args.package, stage, args.receipt_sha256, args.cpu_fixture)
shutil.copyfile(REPO / 'deploy/Dockerfile.runtime', stage / 'Dockerfile')
# Pull before timed probes, so network latency cannot masquerade as ABI failure.
docker('pull', '--platform', 'linux/amd64', args.base, timeout=300)
glibc = check_glibc(p, isolated_run(args.base, ['GNU_LIBC_VERSION'], entrypoint='getconf'))
iid = stage / '.image-id'
try:
docker('build', '--platform', 'linux/amd64', '--network', 'none',
'--build-arg', 'BASE=' + args.base, '--build-arg', 'BUILD_ID=' + uuid.uuid4().hex,
'--build-arg', 'PACKAGE_KIND=' + p['kind'], '--iidfile', iid, stage, timeout=300)
image = iid.read_text().strip()
if not re.fullmatch(r'sha256:[0-9a-f]{64}', image):
raise ValueError('invalid built image identity')
info = json.loads(isolated_run(image, ['engine-info']))
if info != p['engine']:
raise ValueError('image embedded metadata differs from pinned package')
isolated_run(image, ['engine-help'])
result = {'schema_version': 1, 'image': image, 'base': args.base, 'base_glibc': glibc,
'package_receipt_sha256': args.receipt_sha256, 'source_revision': p['source_revision'],
'kind': p['kind'], 'gpu_tested': False, 'model_tested': False,
'qualification': 'Non-root GPU-hidden embedded identity and loader help only.'}
if p.get('build_features') is not None:
result['build_features'] = p['build_features']['features']
result['build_features_sha256'] = p['build_features_sha256']
success = True
return result
finally:
if not success:
# The unique build label makes this image ours, never a caller's tag.
if image is None and iid.exists():
image = iid.read_text().strip()
if image and re.fullmatch(r'sha256:[0-9a-f]{64}', image):
docker('image', 'rm', image, check=False)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--package', type=Path, required=True)
parser.add_argument('--receipt-sha256', required=True, help='trusted SHA256 of package SHA256SUMS')
parser.add_argument('--base', default=BASE)
parser.add_argument('--cpu-fixture', action='store_true')
args = parser.parse_args()
os.umask(0o077)
try:
print(json.dumps(assemble(args)))
except (ValueError, OSError, subprocess.SubprocessError, KeyError, TypeError) as error:
parser.exit(1, f'Runtime image assembly failed: {error}\n')
if __name__ == '__main__':
main()