#!/usr/bin/env python3 """Build-only pinned CUDA component bootstrap for an isolated Linux CPU runner. No driver installation, model access, root privileges or inference. NVIDIA's redistrib archives are assembly inputs, not a general-purpose CUDA installer. """ import argparse import copy import hashlib import json import os from pathlib import Path, PurePosixPath import platform import shutil import stat import tarfile import tempfile import time import urllib.request BASE = 'https://developer.download.nvidia.com/compute/cuda/redist/' COMPONENTS = {'cuda_nvcc','cuda_crt','cuda_cudart','cuda_cccl','cuda_culibos','libnvvm','libcublas'} def download(url, dest, expected, limit, exact=None): digest=hashlib.sha256();total=0;deadline=time.monotonic()+600 with urllib.request.urlopen(url, timeout=30) as response, dest.open('xb') as out: if not response.url.startswith(BASE): raise ValueError('archive redirect left the official redistrib origin') while block:=response.read(1024*1024): total+=len(block) if total>limit or time.monotonic()>deadline: raise ValueError('download size/time limit exceeded') digest.update(block);out.write(block) if digest.hexdigest()!=expected or (exact is not None and total!=exact): raise ValueError('NVIDIA component checksum/size mismatch') def validate_lock(lock, manifest): if lock['manifest_url']!=BASE+'redistrib_'+lock['release']+'.json' or not lock['release'].startswith('13.'): raise ValueError('unsupported toolkit release') if len(lock['components'])!=len(COMPONENTS) or {x['component'] for x in lock['components']}!=COMPONENTS: raise ValueError('unexpected CUDA component set') for item in lock['components']: reference=manifest[item['component']] if item['version']!=reference['version']: raise ValueError('component version mismatch') for key in ('relative_path','sha256','size'): if item[key]!=reference['linux-x86_64'][key]: raise ValueError('component differs from pinned official manifest') path=PurePosixPath(item['relative_path']) if path.is_absolute() or '..' in path.parts or not str(path).endswith('.tar.xz'): raise ValueError('invalid component path') if not 050000 or any(x.size<0 for x in members) or sum(x.size for x in members)>6*1024**3: raise ValueError('archive expansion limit exceeded') seen={} for item in members: raw_name=item.name if not raw_name or '\x00' in raw_name or '\\' in raw_name or raw_name.startswith('/'): raise ValueError('archive path outside component root') parts=raw_name.split('/') if parts[-1]=='' and item.isdir():parts.pop() if not parts or any(part in ('','.','..') for part in parts) or parts[0]!=root_name: raise ValueError('archive path outside component root') name='/'.join(parts) if name in seen: raise ValueError('duplicate archive member') if name==root_name and not item.isdir(): raise ValueError('component root is not a directory') if not (item.isdir() or item.isfile() or item.issym() or item.islnk()): raise ValueError('unsupported archive member') if item.mode & (stat.S_ISUID|stat.S_ISGID|stat.S_ISVTX): raise ValueError('archive member has privileged mode bits') clone=copy.copy(item);clone.name=name if item.issym() or item.islnk(): link=item.linkname if not link or '\x00' in link or '\\' in link or link.startswith('/'): raise ValueError('archive link outside component root') target=list(parts[:-1] if item.issym() else []) for part in link.split('/'): if part in ('','.'):continue if part=='..': if len(target)<=1:raise ValueError('archive link outside component root') target.pop() else:target.append(part) if not target or target[0]!=root_name: raise ValueError('archive link outside component root') if item.islnk():clone.linkname='/'.join(target) if item.isdir(): clone.mode=(item.mode & 0o755)|0o700 elif item.isfile(): clone.mode=(item.mode & 0o755)|0o600 if item.mode & 0o111:clone.mode|=0o100 # Never apply archive ownership. Numeric IDs are the builder's own # identity; tarfile 3.11's root-only chown path therefore stays put. clone.uid=os.geteuid();clone.gid=os.getegid();clone.uname=clone.gname='' seen[name]=(item,clone) for name,(item,_) in seen.items(): parts=name.split('/') for depth in range(1,len(parts)): parent='/'.join(parts[:depth]) if parent in seen and not seen[parent][0].isdir(): raise ValueError('archive member is nested under a non-directory') if item.islnk(): target=item.linkname if target not in seen or not (seen[target][0].isfile() or seen[target][0].islnk()): raise ValueError('archive hard link target is missing or unsupported') # Python 3.11 (Debian Bookworm) lacks tarfile's `filter=` argument. # Every member is normalized and validated above before the legacy # extractor sees it; links are constrained to the private component tree. destination.mkdir(mode=0o700,parents=True,exist_ok=True) if os.path.lexists(destination/root_name):raise ValueError('component root already exists') (destination/root_name).mkdir(mode=0o700) dirs=sorted((v[1] for v in seen.values() if v[0].isdir()),key=lambda x:(x.name.count('/'),x.name)) files=sorted((v[1] for v in seen.values() if v[0].isfile()),key=lambda x:x.name) symlinks=sorted((v[1] for v in seen.values() if v[0].issym()),key=lambda x:x.name) hardlinks={name:clone for name,(item,clone) in seen.items() if item.islnk()} ordered_hardlinks=[];visiting=set();emitted=set() def emit_hardlink(name): if name in emitted:return if name in visiting:raise ValueError('archive hard link cycle') visiting.add(name);target=hardlinks[name].linkname if target in hardlinks:emit_hardlink(target) visiting.remove(name);emitted.add(name);ordered_hardlinks.append(hardlinks[name]) for name in sorted(hardlinks):emit_hardlink(name) source.extractall(destination,members=dirs+files+ordered_hardlinks+symlinks,numeric_owner=True) return destination/root_name def merge(source, dest): # Only verified, safely extracted component trees are accepted here. if source.is_dir() and not source.is_symlink(): if dest.is_symlink() or (dest.exists() and not dest.is_dir()): raise ValueError('toolkit directory collision') dest.mkdir(mode=0o700, exist_ok=True) for child in source.iterdir():merge(child,dest/child.name) elif os.path.lexists(dest): if source.is_symlink() and dest.is_symlink() and os.readlink(source)==os.readlink(dest): return if source.is_file() and dest.is_file() and not source.is_symlink() and not dest.is_symlink(): with source.open('rb') as a,dest.open('rb') as b: if hashlib.file_digest(a,'sha256').digest()==hashlib.file_digest(b,'sha256').digest():return raise ValueError('conflicting CUDA component files') else: source.rename(dest) def resource_gate(parent): memory=int(next(x.split()[1] for x in Path('/proc/meminfo').read_text().splitlines() if x.startswith('MemTotal:')))*1024 free=shutil.disk_usage(parent).free if memory<6*1024**3 or free<12*1024**3: raise ValueError('hosted CUDA build requires at least 6GiB RAM and 12GiB free disk') return {'memory_bytes':memory,'free_disk_bytes':free,'compile_jobs':1,'gpu_used':False} def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--lock',type=Path,default=Path(__file__).resolve().parents[1]/'deploy/cuda-toolkit.lock.json') parser.add_argument('--output',required=True,type=Path) args=parser.parse_args() if platform.system()!='Linux' or platform.machine()!='x86_64': raise ValueError('bootstrap requires Linux x86_64') os.umask(0o077) output=args.output.absolute() if os.path.lexists(output):raise ValueError('toolkit output already exists; use a fresh private directory') resources=resource_gate(output.parent) lock=json.loads(args.lock.read_text()) with tempfile.TemporaryDirectory(prefix='.cuda-stage-',dir=output.parent) as temp: stage=Path(temp);prefix=stage/'toolkit';prefix.mkdir(mode=0o700) manifest=stage/'manifest.json' if lock['manifest_url']!=BASE+'redistrib_'+lock['release']+'.json':raise ValueError('unsupported manifest URL') download(lock['manifest_url'],manifest,lock['manifest_sha256'],1024**2) validate_lock(lock,json.loads(manifest.read_text())) for item in lock['components']: archive=stage/(item['component']+'.tar.xz') download(BASE+item['relative_path'],archive,item['sha256'],int(item['size']),int(item['size'])) extracted=extract(archive,stage,Path(item['relative_path']).name.removesuffix('.tar.xz')) for child in extracted.iterdir(): if child.is_dir() and not child.is_symlink():merge(child,prefix/child.name) else: licenses=prefix/'licenses'/item['component'];licenses.mkdir(parents=True,exist_ok=True) merge(child,licenses/child.name) shutil.rmtree(extracted);archive.unlink() # NVCC's 64-bit link search uses lib64; redistrib archives use lib. (prefix/'lib64').symlink_to('lib',target_is_directory=True) for path in prefix.rglob('*'): if path.is_symlink() and (not path.resolve().is_relative_to(prefix) or not path.exists()): raise ValueError('assembled toolkit has an invalid symlink') for name in ('bin/nvcc','nvvm/bin/cicc','include/cuda_runtime.h','lib/libcudart_static.a', 'lib/libcublas_static.a','lib/libcublasLt_static.a','lib/libculibos.a'): if not (prefix/name).is_file():raise ValueError('assembled toolkit missing '+name) (prefix/'TOOLKIT-PROVENANCE.json').write_text(json.dumps({'lock':lock,'resources':resources},indent=2)+'\n') if os.path.lexists(output):raise ValueError('toolkit destination appeared during bootstrap') prefix.rename(output) print(json.dumps({'toolkit':str(output),'release':lock['release'],**resources})) if __name__=='__main__':main()