extract.py 13 KB

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