extract.py 13 KB

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