1
0

extract.py 13 KB

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