#!/usr/bin/env python3 """Assemble the Leleka release tarball (offline build tooling; production serving has no Python dependency). Inputs: a release build of the seven binaries (`cargo build --release --locked ...`, see docs/deploy.md), the repository tree (for templates, sealed PTX and docs) and a provenance record. Output, in --out: leleka-VERSION-COMMIT12-linux-x86_64.tar.xz bin/ share/ MANIFEST.json PROVENANCE.json SHA256SUMS install.sh leleka-VERSION-COMMIT12-linux-x86_64.tar.xz.sha256 The provenance record names the git commit, whether the tree was clean, and the local changes to the imported Strata source relative to the upstream commit in docs/upstream.md. Builds happen in WSL/Linux from an exported tree (no .git there), so the record is produced where git exists: python3 scripts/package-release.py provenance --repo . --out provenance.json python3 scripts/package-release.py package --repo . --target-dir ~/target --provenance provenance.json --out dist `package` alone also works inside a git checkout (it computes the provenance itself). Nothing here downloads anything; cuBLAS is not bundled (the NVIDIA redistributable is fetched by `leleka up`, or add --with-cublas DIR). """ import argparse import datetime import hashlib import io import json import os from pathlib import Path import re import shutil import subprocess import sys import tarfile RUNTIME_BINARIES = ['leleka', 'strata-next', 'leleka-inference', 'leleka-daemon', 'leleka-cli', 'leleka-seal-exec'] TEMPLATES = [ 'deploy/rust-runtime/leleka-daemon.service', 'deploy/rust-runtime/leleka-inference.service', 'deploy/rust-runtime/runtime.env.example', ] UPSTREAM_DOC = 'docs/upstream.md' SUBTREE = 'engine/strata' def run(args, cwd=None, check=True): result = subprocess.run([str(a) for a in args], cwd=cwd, capture_output=True, text=True) if check and result.returncode != 0: raise RuntimeError(f'{" ".join(map(str, args))} failed: {result.stderr.strip()}') return result.stdout.strip() def sha256(path): digest = hashlib.sha256() with open(path, 'rb') as source: for chunk in iter(lambda: source.read(1 << 20), b''): digest.update(chunk) return digest.hexdigest() def upstream_record(repo): text = (repo / UPSTREAM_DOC).read_text(encoding='utf-8') url = re.search(r'Upstream repository URL \| (\S+)', text) sha = re.search(r'Upstream commit SHA \| `([0-9a-f]{40})`', text) if not url or not sha: raise RuntimeError(f'{UPSTREAM_DOC} does not name the upstream repository and commit') return url.group(1), sha.group(1) def provenance(repo, allow_dirty=False): """Git commit, cleanliness, and the local changes to engine/strata relative to the recorded upstream commit.""" url, upstream_sha = upstream_record(repo) commit = run(['git', '-C', repo, 'rev-parse', 'HEAD']) status = run(['git', '-C', repo, 'status', '--porcelain', '--untracked-files=normal']) dirty_files = [line for line in status.splitlines() if line] # Windows checkouts report CRLF-only differences as modified; hash what git would actually record. diff_digest = hashlib.sha256(run(['git', '-C', repo, 'diff', 'HEAD', '--binary'], check=False).encode()).hexdigest() if dirty_files else None if dirty_files and not allow_dirty: raise RuntimeError(f'the tree has {len(dirty_files)} uncommitted change(s); commit them or pass --allow-dirty (the release is then marked dirty)') # Import commit(s): the first commit that touched the subtree. history = run(['git', '-C', repo, 'log', '--format=%H %s', '--reverse', '--', SUBTREE]).splitlines() import_commit = history[0].split(' ', 1)[0] if history else None subtree_tree = run(['git', '-C', repo, 'rev-parse', f'HEAD:{SUBTREE}']) record = { 'schema_version': 1, 'git_commit': commit, 'git_describe': run(['git', '-C', repo, 'describe', '--always', '--dirty', '--abbrev=12'], check=False), 'git_branch': run(['git', '-C', repo, 'rev-parse', '--abbrev-ref', 'HEAD'], check=False), 'dirty': bool(dirty_files), 'dirty_file_count': len(dirty_files), 'dirty_diff_sha256': diff_digest, 'cargo_lock_sha256': sha256(repo / 'Cargo.lock'), 'strata': { 'upstream_url': url, 'upstream_commit': upstream_sha, 'subtree_path': SUBTREE, 'subtree_tree_at_head': subtree_tree, 'import_commit': import_commit, 'commits_touching_subtree': len(history), 'local_patch_commits': [line.split(' ', 1) for line in history[1:]][:200], }, } # Local changes since the import (the committed ones), and against the upstream tree when it is present. if import_commit: stat = run(['git', '-C', repo, 'diff', '--shortstat', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False) diff = run(['git', '-C', repo, 'diff', '--binary', f'{import_commit}', 'HEAD', '--', SUBTREE], check=False) record['strata']['diff_since_import'] = { 'shortstat': stat or 'no change', 'diff_sha256': hashlib.sha256(diff.encode()).hexdigest(), } have_upstream = subprocess.run(['git', '-C', str(repo), 'cat-file', '-e', f'{upstream_sha}^{{commit}}'], capture_output=True).returncode == 0 if have_upstream: upstream_tree = run(['git', '-C', repo, 'rev-parse', f'{upstream_sha}^{{tree}}']) record['strata']['diff_vs_upstream'] = { 'upstream_tree': upstream_tree, 'shortstat': run(['git', '-C', repo, 'diff', '--shortstat', upstream_tree, f'HEAD:{SUBTREE}'], check=False) or 'identical', } else: record['strata']['diff_vs_upstream'] = { 'available': False, 'why': f'the upstream commit {upstream_sha} is not in this repository (fetch the strata-upstream remote to compare)', } return record def version_of(repo): text = (repo / 'crates/deploy/Cargo.toml').read_text(encoding='utf-8') return re.search(r'^version = "([^"]+)"', text, re.M).group(1) def tool_version(*args): return run(args, check=False).splitlines()[0] if run(args, check=False) else None def add_tree(tar, source_dir, arc_prefix, epoch): for path in sorted(source_dir.rglob('*')): if path.is_file(): add_file(tar, path, f'{arc_prefix}/{path.relative_to(source_dir).as_posix()}', epoch, executable=os.access(path, os.X_OK)) def add_file(tar, path, name, epoch, executable=False, data=None): info = tarfile.TarInfo(name) payload = data if data is not None else path.read_bytes() info.size = len(payload) info.mtime = epoch info.mode = 0o755 if executable else 0o644 info.uid = info.gid = 0 info.uname = info.gname = 'root' tar.addfile(info, io.BytesIO(payload)) def package(args): repo = Path(args.repo).resolve() target = Path(args.target_dir).expanduser().resolve() / 'release' out = Path(args.out).resolve() out.mkdir(parents=True, exist_ok=True) if args.provenance: record = json.loads(Path(args.provenance).read_text(encoding='utf-8')) else: record = provenance(repo, args.allow_dirty) if record.get('dirty') and not args.allow_dirty: raise RuntimeError('the provenance record says the tree was dirty; pass --allow-dirty to package it anyway (the manifest keeps the mark)') commit = record['git_commit'] version = args.version or version_of(repo) features = sorted(set(args.feature or ['sm86'])) name = f'leleka-{version}-{commit[:12]}-linux-x86_64' epoch = int(os.environ.get('SOURCE_DATE_EPOCH', datetime.datetime.now(datetime.timezone.utc).timestamp())) members = {} # archive path -> (bytes, executable) binaries = {} for binary in RUNTIME_BINARIES: path = target / binary if not path.is_file(): raise RuntimeError(f'{path} is missing; build it first (docs/deploy.md, "Build a release")') data = path.read_bytes() members[f'bin/{binary}'] = (data, True) binaries[binary] = hashlib.sha256(data).hexdigest() for template in TEMPLATES: members[f'share/leleka/templates/{Path(template).name}'] = ((repo / template).read_bytes(), False) for profile in sorted((repo / 'deploy/rust-runtime/profiles').glob('*.json')): members[f'share/leleka/profiles/{profile.name}'] = (profile.read_bytes(), False) for doc in ['docs/deploy.md', 'docs/upstream.md', 'docs/rust-runtime-run.md', 'docs/laptop-profile.md', 'docs/sm86-assets.md']: if (repo / doc).is_file(): members[f'share/leleka/docs/{Path(doc).name}'] = ((repo / doc).read_bytes(), False) members['install.sh'] = ((repo / 'deploy/rust-runtime/install.sh').read_bytes(), True) ptx_lines = [] if not args.no_ptx: sets = {'sm_120': [p for p in (repo / 'crates/cuda-driver').rglob('*.ptx') if 'ptx-sm86' not in p.parts], 'sm_86': sorted((repo / 'crates/cuda-driver/ptx-sm86').glob('*.ptx'))} for arch, files in sets.items(): for path in sorted(files): data = path.read_bytes() members[f'share/leleka/ptx/{arch}/{path.name}'] = (data, False) ptx_lines.append(f'{hashlib.sha256(data).hexdigest()} {arch}/{path.name}') if (repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').is_file(): members['share/leleka/ptx/sm_86-MANIFEST.json'] = ((repo / 'crates/cuda-driver/ptx-sm86/MANIFEST.json').read_bytes(), False) members['share/leleka/ptx/SHA256SUMS'] = (('\n'.join(ptx_lines) + '\n').encode(), False) if args.with_cublas: for path in sorted(Path(args.with_cublas).glob('libcublas*.so*')): members[f'lib/cublas/{path.name}'] = (path.read_bytes(), False) manifest = { 'schema_version': 1, 'name': 'leleka', 'version': version, 'git_commit': commit, 'dirty': bool(record.get('dirty')), 'features': features, 'binaries': binaries, 'built_with': { 'rustc': tool_version('rustc', '--version'), 'cargo': tool_version('cargo', '--version'), 'host': tool_version('uname', '-sr'), 'glibc': tool_version('ldd', '--version'), }, 'runtime_requirements': { 'os': 'linux x86_64, glibc', 'nvidia_driver_min': 595, 'cublas': 'libcublas.so.12 and libcublasLt.so.12 (CUDA 12; pinned redistributable 12.9.1.4 is fetched by `leleka up`)' if not args.with_cublas else 'bundled in lib/cublas (CUDA 12.9.1.4 redistributable, NVIDIA license applies)', 'gpu_architectures': ['sm_120'] + (['sm_86..sm_119 (companion PTX, feature sm86)'] if 'sm86' in features else []), }, 'ptx_included': not args.no_ptx, 'created_utc': datetime.datetime.fromtimestamp(epoch, datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'), } members['MANIFEST.json'] = ((json.dumps(manifest, indent=2, sort_keys=True) + '\n').encode(), False) members['PROVENANCE.json'] = ((json.dumps(record, indent=2, sort_keys=True) + '\n').encode(), False) sums = ''.join(f'{hashlib.sha256(data).hexdigest()} {path}\n' for path, (data, _) in sorted(members.items())) members['SHA256SUMS'] = (sums.encode(), False) tarball = out / f'{name}.tar' with tarfile.open(tarball, 'w', format=tarfile.PAX_FORMAT) as tar: for path, (data, executable) in sorted(members.items()): add_file(tar, None, f'{name}/{path}', epoch, executable, data) compressed = out / f'{name}.tar.xz' import lzma with open(tarball, 'rb') as source, lzma.open(compressed, 'wb', preset=6) as target_file: shutil.copyfileobj(source, target_file) tarball.unlink() digest = sha256(compressed) (out / f'{name}.tar.xz.sha256').write_text(f'{digest} {compressed.name}\n', encoding='ascii') # Verify what was written: the member list matches SHA256SUMS byte for byte. with tarfile.open(compressed, 'r:xz') as tar: names = {m.name for m in tar.getmembers() if m.isfile()} sums_member = tar.extractfile(f'{name}/SHA256SUMS').read().decode() for line in sums_member.splitlines(): expected, rel = line.split(' ', 1) actual = hashlib.sha256(tar.extractfile(f'{name}/{rel}').read()).hexdigest() if actual != expected: raise RuntimeError(f'verification failed for {rel}') assert names == {f'{name}/{p}' for p in members} print(json.dumps({'tarball': str(compressed), 'sha256': digest, 'bytes': compressed.stat().st_size, 'files': len(members), 'git_commit': commit, 'dirty': manifest['dirty'], 'features': features}, indent=2)) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest='command', required=True) prov = sub.add_parser('provenance', help='write the provenance record of a git checkout') prov.add_argument('--repo', default='.') prov.add_argument('--out', required=True) prov.add_argument('--allow-dirty', action='store_true') pack = sub.add_parser('package', help='assemble the tarball') pack.add_argument('--repo', default='.') pack.add_argument('--target-dir', required=True, help='cargo target dir that holds release/') pack.add_argument('--out', default='dist') pack.add_argument('--provenance', help='record made by the `provenance` command (needed when the tree has no .git)') pack.add_argument('--version') pack.add_argument('--feature', action='append', help='Cargo feature the runtime binaries were built with (repeatable; default: sm86)') pack.add_argument('--allow-dirty', action='store_true') pack.add_argument('--no-ptx', action='store_true', help='omit the sealed PTX files (they are embedded in the binaries anyway)') pack.add_argument('--with-cublas', help='directory with libcublas.so.12* / libcublasLt.so.12* to bundle') args = parser.parse_args() try: if args.command == 'provenance': record = provenance(Path(args.repo).resolve(), args.allow_dirty) Path(args.out).write_text(json.dumps(record, indent=2, sort_keys=True) + '\n', encoding='utf-8') print(f'wrote {args.out}: {record["git_commit"]} dirty={record["dirty"]}') else: package(args) except (RuntimeError, OSError) as error: print(f'package-release: {error}', file=sys.stderr) sys.exit(1) if __name__ == '__main__': main()