1
0

extract.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 ..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. short = Path(python_dest / f'bin/python{self.version.major}')
  124. short.unlink(missing_ok=True)
  125. short.symlink_to(flavoured_python)
  126. short = Path(python_dest / 'bin/python')
  127. short.unlink(missing_ok=True)
  128. short.symlink_to(f'python{self.version.major}')
  129. # Clone pip wrapper.
  130. with open(self.python_prefix / pip) as f:
  131. f.readline() # Skip shebang.
  132. body = f.read()
  133. with open(python_dest / pip, 'w') as f:
  134. f.write('#! /bin/sh\n')
  135. f.write(' '.join((
  136. '"exec"',
  137. f'"$(dirname $(readlink -f ${0}))/{flavoured_python}"',
  138. '"$0"',
  139. '"$@"\n'
  140. )))
  141. f.write(body)
  142. shutil.copymode(self.python_prefix / pip, python_dest / pip)
  143. short = Path(python_dest / f'bin/pip{self.version.major}')
  144. short.unlink(missing_ok=True)
  145. short.symlink_to(f'pip{self.version.short()}')
  146. short = Path(python_dest / 'bin/pip')
  147. short.unlink(missing_ok=True)
  148. short.symlink_to(f'pip{self.version.major}')
  149. # Clone Python packages.
  150. for folder in (packages, include):
  151. shutil.copytree(self.python_prefix / folder, python_dest / folder,
  152. symlinks=True, dirs_exist_ok=True)
  153. # Remove some clutters.
  154. log('PRUNE', '%s packages', python)
  155. shutil.rmtree(python_dest / packages / 'test', ignore_errors=True)
  156. for root, dirs, files in os.walk(python_dest / packages):
  157. root = Path(root)
  158. for d in dirs:
  159. if d == '__pycache__':
  160. shutil.rmtree(root / d, ignore_errors=True)
  161. for f in files:
  162. if f.endswith('.pyc'):
  163. (root / f).unlink()
  164. # Map binary dependencies.
  165. libs = self.ldd(self.python_prefix / f'bin/{flavoured_python}')
  166. path = Path(self.python_prefix / f'{packages}/lib-dynload')
  167. for module in glob.glob(str(path / "*.so")):
  168. l = self.ldd(module)
  169. libs.update(l)
  170. # Copy and patch binary dependencies.
  171. libdir = system_dest / 'lib'
  172. libdir.mkdir(exist_ok=True, parents=True)
  173. for (name, src) in libs.items():
  174. dst = libdir / name
  175. shutil.copy(src, dst, follow_symlinks=True)
  176. # Some libraries are read-only, which prevents overriding the
  177. # destination directory. Below, we change the permission of
  178. # destination files to read-write (for the owner).
  179. mode = dst.stat().st_mode
  180. if not (mode & stat.S_IWUSR):
  181. mode = mode | stat.S_IWUSR
  182. dst.chmod(mode)
  183. self.set_rpath(dst, '$ORIGIN')
  184. # Patch RPATHs of binary modules.
  185. log('LINK', '%s C-extensions', python)
  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. log('INSTALL', certifi.name)
  204. for src in glob.glob(str(site_packages / 'certifi*')):
  205. src = Path(src)
  206. dst = python_dest / f'{packages}/site-packages/{src.name}'
  207. if not dst.exists():
  208. shutil.copytree(src, dst, symlinks=True)
  209. cert_src = dst / 'cacert.pem'
  210. assert(cert_src.exists())
  211. else:
  212. raise NotImplementedError()
  213. # Copy Tcl & Tk data.
  214. tcltk_src = self.prefix / 'usr/local/lib'
  215. tx_version = []
  216. for match in glob.glob(str(tcltk_src / 'tk*')):
  217. path = Path(match)
  218. if path.is_dir():
  219. tx_version.append(LooseVersion(path.name[2:]))
  220. tx_version.sort()
  221. tx_version = tx_version[-1]
  222. log('INSTALL', f'Tcl/Tk{tx_version}')
  223. tcltk_dir = Path(system_dest / 'share/tcltk')
  224. tcltk_dir.mkdir(exist_ok=True, parents=True)
  225. for tx in ('tcl', 'tk'):
  226. name = f'{tx}{tx_version}'
  227. src = tcltk_src / name
  228. dst = tcltk_dir / name
  229. shutil.copytree(src, dst, symlinks=True, dirs_exist_ok=True)
  230. if appify:
  231. appifier = Appifier(
  232. appdir = str(destination),
  233. appdir_bin = str(system_dest / 'bin'),
  234. python_bin = str(python_dest / 'bin'),
  235. python_pkg = str(python_dest / packages),
  236. version = self.version,
  237. tk_version = tx_version,
  238. cert_src = cert_src
  239. )
  240. appifier.appify()
  241. def ldd(self, target: Path) -> Dict[str, Path]:
  242. '''Cross-platform implementation of ldd, using readelf.'''
  243. pattern = re.compile(r'[(]NEEDED[)]\s+Shared library:\s+\[([^\]]+)\]')
  244. dependencies = dict()
  245. def recurse(target: Path):
  246. result = subprocess.run(f'readelf -d {target}', shell=True,
  247. check=True, capture_output=True)
  248. stdout = result.stdout.decode()
  249. matches = pattern.findall(stdout)
  250. for match in matches:
  251. if (match not in dependencies) and (match not in self.excluded):
  252. path = self.locate_library(match)
  253. dependencies[match] = path
  254. subs = recurse(path)
  255. recurse(target)
  256. return dependencies
  257. def locate_library(self, name: str) -> Path:
  258. '''Locate a library given its qualified name.'''
  259. for dirname in self.library_path:
  260. path = dirname / name
  261. if path.exists():
  262. return path
  263. else:
  264. raise FileNotFoundError(name)
  265. def set_rpath(self, target, rpath):
  266. cmd = f'{self.patchelf} --print-rpath {target}'
  267. result = subprocess.run(cmd, shell=True, check=True,
  268. capture_output=True)
  269. current_rpath = result.stdout.decode().strip()
  270. if current_rpath != rpath:
  271. cmd = f"{self.patchelf} --set-rpath '{rpath}' {target}"
  272. subprocess.run(cmd, shell=True, check=True, capture_output=True)
  273. @dataclass(frozen=True)
  274. class ImageExtractor:
  275. '''Manylinux image extractor from layers.'''
  276. prefix: Path
  277. '''Manylinux image prefix.'''
  278. tag: Optional[str] = 'latest'
  279. '''Manylinux image tag.'''
  280. def default_destination(self):
  281. return self.prefix / f'extracted/{self.tag}'
  282. def extract(self, destination: Optional[Path]=None, *, cleanup=False):
  283. '''Extract Manylinux image.'''
  284. if destination is None:
  285. destination = self.default_destination()
  286. if cleanup:
  287. def cleanup(destination):
  288. shutil.rmtree(destination, ignore_errors=True)
  289. atexit.register(cleanup, destination)
  290. with open(self.prefix / f'tags/{self.tag}.json') as f:
  291. meta = json.load(f)
  292. layers = meta['layers']
  293. extracted = []
  294. extracted_file = destination / '.extracted'
  295. if destination.exists():
  296. clean_destination = True
  297. if extracted_file.exists():
  298. with extracted_file.open() as f:
  299. extracted = f.read().split(os.linesep)[:-1]
  300. for a, b in zip(layers, extracted):
  301. if a != b:
  302. break
  303. else:
  304. clean_destination = False
  305. if clean_destination:
  306. shutil.rmtree(destination, ignore_errors=True)
  307. for i, layer in enumerate(layers):
  308. try:
  309. if layer == extracted[i]:
  310. continue
  311. except IndexError:
  312. pass
  313. debug('EXTRACT', f'{layer}.tar.gz')
  314. filename = self.prefix / f'layers/{layer}.tar.gz'
  315. cmd = ''.join((
  316. f'trap \'chmod u+rw -R {destination}\' EXIT ; ',
  317. f'mkdir -p {destination} && ',
  318. f'tar -xzf {filename} -C {destination} && ',
  319. f'echo \'{layer}\' >> {extracted_file}'
  320. ))
  321. process = subprocess.run(f'/bin/bash -c "{cmd}"', shell=True,
  322. check=True, capture_output=True)