Files
leleka/scripts/bootstrap-cuda-toolkit.py
T
Pavlo Ratushnyi 27b02c8b11
Linux / verify (pull_request) Failing after 36s
Linux / keyless-cuda (pull_request) Skipped
Linux / hosted-cuda-package (pull_request) Skipped
Linux / linux-static-cli (pull_request) Skipped
Linux / linux-cli-container (pull_request) Skipped
Linux / release-cli (pull_request) Skipped
fix: handle missing CUDA archive modes on Python 3.11
2026-10-06 03:26:56 +02:00

230 lines
11 KiB
Python

#!/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 inspect
import json
import os
from pathlib import Path, PurePosixPath
import platform
import shutil
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['release']!='13.0.1' or lock['manifest_url']!=BASE+'redistrib_13.0.1.json':
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 0<int(item['size'])<1024**3:
raise ValueError('component exceeds download budget')
def extract_members(source, destination, members, *, supports_filter=None):
"""Use tarfile's data policy on both new and older Python runtimes.
Python 3.11 runners may have neither ``extractall(filter=...)`` nor the
later ``tarfile.data_filter`` helper, so provide the same restricted data
policy locally. Never fall back to unfiltered extraction.
"""
if supports_filter is None:
supports_filter = 'filter' in inspect.signature(source.extractall).parameters
if supports_filter:
source.extractall(destination, members=members, filter='data')
return
safe_members = []
for member in members:
safe_member = safe_data_filter(member, destination)
if safe_member is not None:
safe_members.append(safe_member)
# tarfile 3.11's legacy chown path does not treat None ownership fields as
# "use current user". Pin filtered members to the extracting identity so
# archive ownership is ignored without relying on a Python 3.12 behavior.
for member in safe_members:
member.uid = os.geteuid()
member.gid = os.getegid()
member.uname = member.gname = ''
source.extractall(destination, members=safe_members, numeric_owner=True)
def safe_data_filter(member, destination):
"""Python 3.11-compatible equivalent of tarfile's restrictive data filter."""
name = member.name
if name.startswith('/') or os.path.isabs(name):
raise ValueError('absolute archive member path')
root = os.path.realpath(destination)
target = os.path.realpath(os.path.join(root, name))
if os.path.commonpath((target, root)) != root:
raise ValueError('archive member escapes extraction root')
filtered = copy.copy(member)
mode = member.mode
# Python 3.11's extractall() chmod path passes mode straight to os.chmod,
# so ``None`` (the data-filter convention for directories/symlinks) crashes.
# Give directories owner-only traversal/write permissions; this preserves
# the filter's security intent while remaining compatible with old tarfile.
if member.isdir():
mode = 0o700
elif member.isreg() or member.islnk():
mode = 0o600 if mode is None else mode & 0o755
if not mode & 0o100:
mode &= ~0o111
mode |= 0o600
elif member.issym():
mode = None
else:
raise ValueError('unsupported special archive member')
filtered.mode = mode
filtered.uid = filtered.gid = None
filtered.uname = filtered.gname = None
if member.issym() or member.islnk():
if os.path.isabs(member.linkname):
raise ValueError('absolute archive link target')
normalized = os.path.normpath(member.linkname)
filtered.linkname = normalized
if member.issym():
link_target = os.path.join(root, os.path.dirname(name), normalized)
else:
link_target = os.path.join(root, normalized)
resolved = os.path.realpath(link_target)
if os.path.commonpath((resolved, root)) != root:
raise ValueError('archive link escapes extraction root')
return filtered
def extract(archive, destination, root_name):
with tarfile.open(archive, 'r:xz') as source:
members=source.getmembers()
if len(members)>50000 or sum(x.size for x in members)>6*1024**3:
raise ValueError('archive expansion limit exceeded')
seen=set();links=set()
for item in members:
path=PurePosixPath(item.name)
if path.is_absolute() or '..' in path.parts or not path.parts or path.parts[0]!=root_name:
raise ValueError('archive path outside component root')
if item.name.rstrip('/') != str(path):
raise ValueError('non-canonical archive member path')
if item.name in seen:
raise ValueError('duplicate archive member')
seen.add(item.name)
if not (item.isdir() or item.isfile() or item.issym() or item.islnk()):
raise ValueError('unsupported archive member')
if item.issym() or item.islnk():
links.add(str(path))
# Prevent a later member from traversing through an archive-created
# symlink/hardlink parent, even when each link target is individually
# confined to the destination.
for item in members:
path=PurePosixPath(item.name)
if any(str(parent) in links for parent in path.parents):
raise ValueError('archive member descends through a link')
extract_members(source, destination, members)
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_13.0.1.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()