extract.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import atexit
  2. from dataclasses import dataclass, field
  3. from distutils.version import LooseVersion
  4. import glob
  5. import json
  6. import os
  7. import re
  8. from pathlib import Path
  9. import shutil
  10. import stat
  11. import subprocess
  12. from typing import Dict, List, Optional
  13. from .config import Arch, PythonImpl, PythonVersion
  14. from ..appimage import Appifier
  15. from ..utils.deps import ensure_excludelist, ensure_patchelf, EXCLUDELIST, \
  16. PATCHELF
  17. from ..utils.log import debug, log
  18. @dataclass(frozen=True)
  19. class PythonExtractor:
  20. '''Python extractor from an extracted Manylinux image.'''
  21. arch: Arch
  22. '''Target architecture'''
  23. prefix: Path
  24. '''Target image path'''
  25. tag: str
  26. '''Python binary tag'''
  27. excludelist: Optional[Path] = None
  28. '''Exclude list for shared libraries.'''
  29. patchelf: Optional[Path] = None
  30. '''Patchelf executable.'''
  31. excluded: List[str] = field(init=False)
  32. '''Excluded shared libraries.'''
  33. impl: PythonImpl = field(init=False)
  34. '''Python implementation'''
  35. library_path: List[str] = field(init=False)
  36. '''Search paths for libraries (LD_LIBRARY_PATH)'''
  37. python_prefix: Path = field(init=False)
  38. '''Python installation prefix'''
  39. version: PythonVersion = field(init=False)
  40. '''Python version'''
  41. def __post_init__(self):
  42. # Locate Python installation.
  43. link = os.readlink(self.prefix / f'opt/python/{self.tag}')
  44. if not link.startswith('/'):
  45. raise NotImplementedError()
  46. object.__setattr__(self, 'python_prefix', self.prefix / link[1:])
  47. # Parse implementation and version.
  48. head, tail = Path(link).name.split('-', 1)
  49. if head == 'cpython':
  50. impl = PythonImpl.CPYTHON
  51. version = PythonVersion.from_str(tail)
  52. else:
  53. raise NotImplementedError()
  54. object.__setattr__(self, 'impl', impl)
  55. object.__setattr__(self, 'version', version)
  56. # Set libraries search path.
  57. paths = []
  58. if self.arch in (Arch.AARCH64, Arch.X86_64):
  59. paths.append(self.prefix / 'lib64')
  60. paths.append(self.prefix / 'usr/lib64')
  61. if self.arch == Arch.X86_64:
  62. paths.append(self.prefix / 'lib/x86_64-linux-gnu')
  63. paths.append(self.prefix / 'usr/lib/x86_64-linux-gnu')
  64. else:
  65. paths.append(self.prefix / 'lib/aarch64-linux-gnu')
  66. paths.append(self.prefix / 'usr/lib/aarch64-linux-gnu')
  67. elif self.arch == Arch.I686:
  68. paths.append(self.prefix / 'lib')
  69. paths.append(self.prefix / 'usr/lib')
  70. paths.append(self.prefix / 'lib/i386-linux-gnu')
  71. paths.append(self.prefix / 'usr/lib/i386-linux-gnu')
  72. else:
  73. raise NotImplementedError()
  74. paths.append(self.prefix / 'usr/local/lib')
  75. ssl = glob.glob(str(self.prefix / 'opt/_internal/openssl-*'))
  76. if ssl:
  77. paths.append(Path(ssl[0]) / 'lib')
  78. mpdecimal = glob.glob(str(self.prefix / 'opt/_internal/mpdecimal-*'))
  79. if mpdecimal:
  80. paths.append(Path(mpdecimal[0]) / 'lib')
  81. object.__setattr__(self, 'library_path', paths)
  82. # Set excluded libraries.
  83. if self.excludelist:
  84. excludelist = Path(self.excludelist)
  85. else:
  86. ensure_excludelist()
  87. excludelist = Path(EXCLUDELIST)
  88. excluded = set()
  89. with excludelist.open() as f:
  90. for line in f:
  91. line = line.strip()
  92. if line and not line.startswith('#'):
  93. excluded.add(line)
  94. excluded.add('ld-linux-aarch64.so.1') # patch for aarch64.
  95. object.__setattr__(self, 'excluded', excluded)
  96. # Set patchelf, if not provided.
  97. if self.patchelf is None:
  98. ensure_patchelf()
  99. object.__setattr__(self, 'patchelf', PATCHELF)
  100. else:
  101. assert(self.patchelf.exists())
  102. def extract(
  103. self,
  104. destination: Path,
  105. *,
  106. appify: Optional[bool]=False,
  107. python_prefix: Optional[str]=None,
  108. system_prefix: Optional[str]=None,
  109. ):
  110. '''Extract Python runtime.'''
  111. python = f'python{self.version.short()}'
  112. flavoured_python = f'python{self.version.flavoured()}'
  113. runtime = f'bin/{flavoured_python}'
  114. packages = f'lib/{flavoured_python}'
  115. pip = f'bin/pip{self.version.short()}'
  116. if python_prefix is None:
  117. python_prefix = f'opt/{flavoured_python}'
  118. if system_prefix is None:
  119. system_prefix = 'usr'
  120. python_dest = destination / python_prefix
  121. system_dest = destination / system_prefix
  122. # Locate include files.
  123. include = glob.glob(str(self.python_prefix / 'include/*'))
  124. if include:
  125. include = Path(include[0]).name
  126. include = f'include/{include}'
  127. else:
  128. raise NotImplementedError()
  129. # Clone Python runtime.
  130. log('CLONE',
  131. f'{python} from {self.python_prefix.relative_to(self.prefix)}')
  132. (python_dest / 'bin').mkdir(exist_ok=True, parents=True)
  133. shutil.copy(self.python_prefix / runtime, python_dest / runtime)
  134. # Clone pip wrapper.
  135. with open(self.python_prefix / pip) as f:
  136. f.readline() # Skip shebang.
  137. body = f.read()
  138. with open(python_dest / pip, 'w') as f:
  139. f.write('#! /bin/sh\n')
  140. f.write(' '.join((
  141. '"exec"',
  142. f'"$(dirname $(readlink -f ${0}))/{flavoured_python}"',
  143. '"$0"',
  144. '"$@"\n'
  145. )))
  146. f.write(body)
  147. shutil.copymode(self.python_prefix / pip, python_dest / pip)
  148. # Clone Python packages.
  149. for folder in (packages, include):
  150. shutil.copytree(self.python_prefix / folder, python_dest / folder,
  151. symlinks=True, dirs_exist_ok=True)
  152. # Remove some clutters.
  153. log('PRUNE', '%s packages', python)
  154. shutil.rmtree(python_dest / packages / 'test', ignore_errors=True)
  155. for root, dirs, files in os.walk(python_dest / packages):
  156. root = Path(root)
  157. for d in dirs:
  158. if d == '__pycache__':
  159. shutil.rmtree(root / d, ignore_errors=True)
  160. for f in files:
  161. if f.endswith('.pyc'):
  162. (root / f).unlink()
  163. # Map binary dependencies.
  164. libs = self.ldd(self.python_prefix / f'bin/{flavoured_python}')
  165. path = Path(self.python_prefix / f'{packages}/lib-dynload')
  166. for module in glob.glob(str(path / "*.so")):
  167. l = self.ldd(module)
  168. libs.update(l)
  169. # Copy and patch binary dependencies.
  170. libdir = system_dest / 'lib'
  171. libdir.mkdir(exist_ok=True, parents=True)
  172. for (name, src) in libs.items():
  173. dst = libdir / name
  174. shutil.copy(src, dst, follow_symlinks=True)
  175. # Some libraries are read-only, which prevents overriding the
  176. # destination directory. Below, we change the permission of
  177. # destination files to read-write (for the owner).
  178. mode = dst.stat().st_mode
  179. if not (mode & stat.S_IWUSR):
  180. mode = mode | stat.S_IWUSR
  181. dst.chmod(mode)
  182. self.set_rpath(dst, '$ORIGIN')
  183. # Patch RPATHs of binary modules.
  184. log('LINK', '%s C-extensions', python)
  185. path = Path(python_dest / f'{packages}/lib-dynload')
  186. for module in glob.glob(str(path / "*.so")):
  187. src = Path(module)
  188. dst = os.path.relpath(libdir, src.parent)
  189. self.set_rpath(src, f'$ORIGIN/{dst}')
  190. # Patch RPATHs of Python runtime.
  191. src = python_dest / runtime
  192. dst = os.path.relpath(libdir, src.parent)
  193. self.set_rpath(src, f'$ORIGIN/{dst}')
  194. # Copy SSL certificates (i.e. clone certifi).
  195. certs = self.prefix / 'opt/_internal/certs.pem'
  196. if certs.is_symlink():
  197. dst = self.prefix / str(certs.readlink())[1:]
  198. certifi = dst.parent
  199. assert(certifi.name == 'certifi')
  200. site_packages = certifi.parent
  201. assert(site_packages.name == 'site-packages')
  202. log('INSTALL', certifi.name)
  203. for src in glob.glob(str(site_packages / 'certifi*')):
  204. src = Path(src)
  205. dst = python_dest / f'{packages}/site-packages/{src.name}'
  206. if not dst.exists():
  207. shutil.copytree(src, dst, symlinks=True)
  208. cert_src = dst / 'cacert.pem'
  209. assert(cert_src.exists())
  210. else:
  211. raise NotImplementedError()
  212. # Copy Tcl & Tk data.
  213. tx_version = []
  214. for match in glob.glob(str(system_dest / 'lib/libtk*')):
  215. path = system_dest / f'lib/{match}'
  216. tx_version.append(LooseVersion(path.name[5:8]))
  217. if tx_version:
  218. tx_version.sort()
  219. tx_version = tx_version[-1]
  220. for location in ('usr/local/lib', 'usr/share', 'usr/share/tcltk'):
  221. tcltk_src = self.prefix / location
  222. path = tcltk_src / f'tk{tx_version}'
  223. if path.exists() and path.is_dir():
  224. break
  225. else:
  226. raise ValueError(f'could not locate Tcl/Tk{tx_version}')
  227. log('INSTALL', f'Tcl/Tk{tx_version}')
  228. tcltk_dir = Path(system_dest / 'share/tcltk')
  229. tcltk_dir.mkdir(exist_ok=True, parents=True)
  230. for tx in ('tcl', 'tk'):
  231. name = f'{tx}{tx_version}'
  232. src = tcltk_src / name
  233. dst = tcltk_dir / name
  234. shutil.copytree(src, dst, symlinks=True, dirs_exist_ok=True)
  235. if appify:
  236. appifier = Appifier(
  237. appdir = str(destination),
  238. appdir_bin = str(system_dest / 'bin'),
  239. python_bin = str(python_dest / 'bin'),
  240. python_pkg = str(python_dest / packages),
  241. version = self.version,
  242. tk_version = tx_version,
  243. cert_src = cert_src
  244. )
  245. appifier.appify()
  246. def ldd(self, target: Path) -> Dict[str, Path]:
  247. '''Cross-platform implementation of ldd, using readelf.'''
  248. pattern = re.compile(r'[(]NEEDED[)]\s+Shared library:\s+\[([^\]]+)\]')
  249. dependencies = dict()
  250. def recurse(target: Path):
  251. result = subprocess.run(f'readelf -d {target}', shell=True,
  252. check=True, capture_output=True)
  253. stdout = result.stdout.decode()
  254. matches = pattern.findall(stdout)
  255. for match in matches:
  256. if (match not in dependencies) and (match not in self.excluded):
  257. path = self.locate_library(match)
  258. dependencies[match] = path
  259. recurse(path)
  260. recurse(target)
  261. return dependencies
  262. def locate_library(self, name: str) -> Path:
  263. '''Locate a library given its qualified name.'''
  264. for dirname in self.library_path:
  265. path = dirname / name
  266. if path.exists():
  267. return path
  268. else:
  269. raise FileNotFoundError(name)
  270. def set_rpath(self, target, rpath):
  271. cmd = f'{self.patchelf} --print-rpath {target}'
  272. result = subprocess.run(cmd, shell=True, check=True,
  273. capture_output=True)
  274. current_rpath = result.stdout.decode().strip()
  275. if current_rpath != rpath:
  276. cmd = f"{self.patchelf} --set-rpath '{rpath}' {target}"
  277. subprocess.run(cmd, shell=True, check=True, capture_output=True)
  278. @dataclass(frozen=True)
  279. class ImageExtractor:
  280. '''Manylinux image extractor from layers.'''
  281. prefix: Path
  282. '''Manylinux image prefix.'''
  283. tag: Optional[str] = 'latest'
  284. '''Manylinux image tag.'''
  285. def default_destination(self):
  286. return self.prefix / f'extracted/{self.tag}'
  287. def extract(self, destination: Optional[Path]=None, *, clean=False):
  288. '''Extract Manylinux image.'''
  289. if destination is None:
  290. destination = self.default_destination()
  291. if clean:
  292. def clean(destination):
  293. shutil.rmtree(destination, ignore_errors=True)
  294. atexit.register(clean, destination)
  295. log('EXTRACT', f'{self.prefix.name}:{self.tag}')
  296. with open(self.prefix / f'tags/{self.tag}.json') as f:
  297. meta = json.load(f)
  298. layers = meta['layers']
  299. extracted = []
  300. extracted_file = destination / '.extracted'
  301. if destination.exists():
  302. clean_destination = True
  303. if extracted_file.exists():
  304. with extracted_file.open() as f:
  305. extracted = f.read().split(os.linesep)[:-1]
  306. for a, b in zip(layers, extracted):
  307. if a != b:
  308. break
  309. else:
  310. clean_destination = False
  311. if clean_destination:
  312. shutil.rmtree(destination, ignore_errors=True)
  313. for i, layer in enumerate(layers):
  314. try:
  315. if layer == extracted[i]:
  316. continue
  317. except IndexError:
  318. pass
  319. debug('EXTRACT', f'{layer}.tar.gz')
  320. filename = self.prefix / f'layers/{layer}.tar.gz'
  321. cmd = ''.join((
  322. f'trap \'chmod u+rw -R {destination}\' EXIT ; ',
  323. f'mkdir -p {destination} && ',
  324. f'tar -xzf {filename} --exclude=dev -C {destination} && ',
  325. f'echo \'{layer}\' >> {extracted_file}'
  326. ))
  327. r = subprocess.run(f'/bin/bash -c "{cmd}"', shell=True,
  328. capture_output=True)
  329. if r.returncode != 0:
  330. raise ValueError(r.stderr.decode())