relocate.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import glob
  2. import os
  3. import re
  4. import shutil
  5. import sys
  6. from ..utils.deps import EXCLUDELIST, PATCHELF, PREFIX, ensure_excludelist, \
  7. ensure_patchelf
  8. from ..utils.fs import copy_file, copy_tree, make_tree, remove_file, remove_tree
  9. from ..utils.log import debug, log
  10. from ..utils.system import ldd, system
  11. from ..utils.template import copy_template, load_template
  12. __all__ = ["cert_file_env_string", "patch_binary", "relocate_python",
  13. "tcltk_env_string"]
  14. def _copy_template(name, destination, **kwargs):
  15. path = os.path.join(PREFIX, 'data', name)
  16. copy_template(path, destination, **kwargs)
  17. def _get_tk_version(python_pkg):
  18. tkinter = glob.glob(python_pkg + '/lib-dynload/_tkinter*.so')
  19. if tkinter:
  20. tkinter = tkinter[0]
  21. for dep in ldd(tkinter):
  22. name = os.path.basename(dep)
  23. if name.startswith('libtk'):
  24. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  25. return match.group(1)
  26. else:
  27. raise RuntimeError('could not guess Tcl/Tk version')
  28. def tcltk_env_string(python_pkg):
  29. '''Environment for using AppImage's TCl/Tk
  30. '''
  31. tk_version = _get_tk_version(python_pkg)
  32. if tk_version:
  33. return '''
  34. # Export TCl/Tk
  35. export TCL_LIBRARY="${{APPDIR}}/usr/share/tcltk/tcl{tk_version:}"
  36. export TK_LIBRARY="${{APPDIR}}/usr/share/tcltk/tk{tk_version:}"
  37. export TKPATH="${{TK_LIBRARY}}"'''.format(
  38. tk_version=tk_version)
  39. else:
  40. return ''
  41. def cert_file_env_string(cert_file):
  42. '''Environment for using a bundled certificate
  43. '''
  44. if cert_file:
  45. return '''
  46. # Export SSL certificate
  47. export SSL_CERT_FILE="${{APPDIR}}{cert_file:}"'''.format(
  48. cert_file=cert_file)
  49. else:
  50. return ''
  51. _excluded_libs = None
  52. '''Appimage excluded libraries, i.e. assumed to be installed on the host
  53. '''
  54. def patch_binary(path, libdir, recursive=True):
  55. '''Patch the RPATH of a binary and and fetch its dependencies
  56. '''
  57. global _excluded_libs
  58. if _excluded_libs is None:
  59. ensure_excludelist()
  60. excluded = []
  61. with open(EXCLUDELIST) as f:
  62. for line in f:
  63. line = line.strip()
  64. if (not line) or line.startswith('#'):
  65. continue
  66. excluded.append(line.split(' ', 1)[0])
  67. _excluded_libs = excluded
  68. else:
  69. excluded = _excluded_libs
  70. ensure_patchelf()
  71. rpath = '\'' + system((PATCHELF, '--print-rpath', path)) + '\''
  72. relpath = os.path.relpath(libdir, os.path.dirname(path))
  73. relpath = '' if relpath == '.' else '/' + relpath
  74. expected = '\'$ORIGIN' + relpath + '\''
  75. if rpath != expected:
  76. system((PATCHELF, '--set-rpath', expected, path))
  77. deps = ldd(path)
  78. for dep in deps:
  79. name = os.path.basename(dep)
  80. if name in excluded:
  81. continue
  82. target = libdir + '/' + name
  83. if not os.path.exists(target):
  84. libname = os.path.basename(dep)
  85. copy_file(dep, target)
  86. if recursive:
  87. patch_binary(target, libdir, recursive=True)
  88. def set_executable_patch(version, pkgpath, patch):
  89. '''Set a runtime patch for sys.executable name
  90. '''
  91. # This patch needs to be executed before site.main() is called. A natural
  92. # option is to apply it directy to the site module. But, starting with
  93. # Python 3.11, the site module is frozen within Python executable. Then,
  94. # doing so would require to recompile Python. Thus, starting with 3.11 we
  95. # instead apply the patch to the encodings package. Indeed, the latter is
  96. # loaded before the site module, and it is not frozen (as for now).
  97. major, minor = [int(v) for v in version.split('.')]
  98. if (major >= 3) and (minor >= 11):
  99. path = os.path.join(pkgpath, 'encodings', '__init__.py')
  100. else:
  101. path = os.path.join(pkgpath, 'site.py')
  102. with open(path) as f:
  103. source = f.read()
  104. if '_initappimage' in source: return
  105. lines = source.split(os.linesep)
  106. if path.endswith('site.py'):
  107. # Insert the patch before the main function
  108. for i, line in enumerate(lines):
  109. if line.startswith('def main('): break
  110. else:
  111. # Append the patch at end of file
  112. i = len(lines)
  113. with open(patch) as f:
  114. patch = f.read()
  115. lines.insert(i, patch)
  116. lines.insert(i + 1, '')
  117. source = os.linesep.join(lines)
  118. with open(path, 'w') as f:
  119. f.write(source)
  120. def relocate_python(python=None, appdir=None):
  121. '''Bundle a Python install inside an AppDir
  122. '''
  123. if python is not None:
  124. if not os.path.exists(python):
  125. raise ValueError('could not access ' + python)
  126. if appdir is None:
  127. appdir = 'AppDir'
  128. # Set some key variables & paths
  129. if python:
  130. FULLVERSION = system((python, '-c',
  131. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"'))
  132. FULLVERSION = FULLVERSION.strip()
  133. else:
  134. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  135. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  136. PYTHON_X_Y = 'python' + VERSION
  137. PIP_X_Y = 'pip' + VERSION
  138. PIP_X = 'pip' + VERSION[0]
  139. APPDIR = os.path.abspath(appdir)
  140. APPDIR_BIN = APPDIR + '/usr/bin'
  141. APPDIR_LIB = APPDIR + '/usr/lib'
  142. APPDIR_SHARE = APPDIR + '/usr/share'
  143. if python:
  144. HOST_PREFIX = system((
  145. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  146. else:
  147. HOST_PREFIX = sys.prefix
  148. HOST_BIN = HOST_PREFIX + '/bin'
  149. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  150. HOST_LIB = HOST_PREFIX + '/lib'
  151. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  152. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  153. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  154. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  155. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  156. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  157. if not os.path.exists(HOST_INC):
  158. HOST_INC += 'm'
  159. PYTHON_INC += 'm'
  160. # Copy the running Python's install
  161. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  162. source = HOST_BIN + '/' + PYTHON_X_Y
  163. if not os.path.exists(source):
  164. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  165. make_tree(PYTHON_BIN)
  166. target = PYTHON_BIN + '/' + PYTHON_X_Y
  167. copy_file(source, target, update=True)
  168. copy_tree(HOST_PKG, PYTHON_PKG)
  169. copy_tree(HOST_INC, PYTHON_INC)
  170. make_tree(APPDIR_BIN)
  171. pip_source = HOST_BIN + '/' + PIP_X_Y
  172. if not os.path.exists(pip_source):
  173. pip_source = HOST_BIN + '/' + PIP_X
  174. if os.path.exists(pip_source):
  175. with open(pip_source) as f:
  176. f.readline()
  177. body = f.read()
  178. target = PYTHON_BIN + '/' + PIP_X_Y
  179. with open(target, 'w') as f:
  180. f.write('#! /bin/sh\n')
  181. f.write(' '.join((
  182. '"exec"',
  183. '"$(dirname $(readlink -f ${0}))/../../../usr/bin/' +
  184. PYTHON_X_Y + '"',
  185. '"$0"',
  186. '"$@"\n'
  187. )))
  188. f.write(body)
  189. shutil.copymode(pip_source, target)
  190. relpath = os.path.relpath(target, APPDIR_BIN)
  191. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  192. # Remove unrelevant files
  193. log('PRUNE', '%s packages', PYTHON_X_Y)
  194. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  195. remove_tree(PYTHON_PKG + '/test')
  196. remove_file(PYTHON_PKG + '/dist-packages')
  197. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  198. for path in matches:
  199. remove_tree(path)
  200. # Add a runtime patch for sys.executable, before site.main() execution
  201. log('PATCH', '%s sys.executable', PYTHON_X_Y)
  202. set_executable_patch(VERSION, PYTHON_PKG, PREFIX + '/data/_initappimage.py')
  203. # Set a hook for cleaning sys.path, after site.main() execution
  204. log('HOOK', '%s sys.path', PYTHON_X_Y)
  205. sitepkgs = PYTHON_PKG + '/site-packages'
  206. make_tree(sitepkgs)
  207. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  208. # Set RPATHs and bundle external libraries
  209. log('LINK', '%s C-extensions', PYTHON_X_Y)
  210. make_tree(APPDIR_LIB)
  211. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  212. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  213. for file_ in files:
  214. if not file_.endswith('.so'):
  215. continue
  216. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  217. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  218. patch_binary(file_, APPDIR_LIB, recursive=True)
  219. # Copy shared data for TCl/Tk
  220. tk_version = _get_tk_version(PYTHON_PKG)
  221. if tk_version is not None:
  222. tcltkdir = APPDIR_SHARE + '/tcltk'
  223. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  224. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  225. hostdir = '/usr/share/tcltk'
  226. if os.path.exists(hostdir):
  227. make_tree(APPDIR_SHARE)
  228. copy_tree(hostdir, tcltkdir)
  229. else:
  230. make_tree(tcltkdir)
  231. tclpath = '/usr/share/tcl' + tk_version
  232. if not tclpath:
  233. raise ValueError('could not find ' + tclpath)
  234. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  235. tkpath = '/usr/share/tk' + tk_version
  236. if not tkpath:
  237. raise ValueError('could not find ' + tkpath)
  238. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  239. # Copy any SSL certificate
  240. cert_file = os.getenv('SSL_CERT_FILE')
  241. if cert_file:
  242. # Package certificates as well for SSL
  243. # (see https://github.com/niess/python-appimage/issues/24)
  244. dirname, basename = os.path.split(cert_file)
  245. make_tree('AppDir' + dirname)
  246. copy_file(cert_file, 'AppDir' + cert_file)
  247. log('INSTALL', basename)
  248. # Bundle the python wrapper
  249. wrapper = APPDIR_BIN + '/' + PYTHON_X_Y
  250. if not os.path.exists(wrapper):
  251. log('INSTALL', '%s wrapper', PYTHON_X_Y)
  252. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  253. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  254. dictionary = {'entrypoint': entrypoint,
  255. 'shebang': '#! /bin/bash',
  256. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  257. 'cert-file': cert_file_env_string(cert_file)}
  258. _copy_template('python-wrapper.sh', wrapper, **dictionary)
  259. # Set or update symlinks to python
  260. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  261. versions = [os.path.basename(python)[6:] for python in pythons]
  262. latest2, latest3 = '0.0', '0.0'
  263. for version in versions:
  264. if version.startswith('2') and version >= latest2:
  265. latest2 = version
  266. elif version.startswith('3') and version >= latest3:
  267. latest3 = version
  268. if latest2 == VERSION:
  269. python2 = APPDIR_BIN + '/python2'
  270. remove_file(python2)
  271. os.symlink(PYTHON_X_Y, python2)
  272. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  273. if has_pip:
  274. pip2 = APPDIR_BIN + '/pip2'
  275. remove_file(pip2)
  276. os.symlink(PIP_X_Y, pip2)
  277. if latest3 == '0.0':
  278. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  279. python = APPDIR_BIN + '/python'
  280. remove_file(python)
  281. os.symlink('python2', python)
  282. if has_pip:
  283. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  284. pip = APPDIR_BIN + '/pip'
  285. remove_file(pip)
  286. os.symlink('pip2', pip)
  287. else:
  288. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  289. if has_pip:
  290. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  291. elif latest3 == VERSION:
  292. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  293. python3 = APPDIR_BIN + '/python3'
  294. remove_file(python3)
  295. os.symlink(PYTHON_X_Y, python3)
  296. python = APPDIR_BIN + '/python'
  297. remove_file(python)
  298. os.symlink('python3', python)
  299. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  300. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  301. pip3 = APPDIR_BIN + '/pip3'
  302. remove_file(pip3)
  303. os.symlink(PIP_X_Y, pip3)
  304. pip = APPDIR_BIN + '/pip'
  305. remove_file(pip)
  306. os.symlink('pip3', pip)
  307. # Bundle the entry point
  308. apprun = APPDIR + '/AppRun'
  309. if not os.path.exists(apprun):
  310. log('INSTALL', 'AppRun')
  311. relpath = os.path.relpath(wrapper, APPDIR)
  312. os.symlink(relpath, APPDIR + '/AppRun')
  313. # Bundle the desktop file
  314. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  315. desktop = os.path.join(APPDIR, desktop_name)
  316. if not os.path.exists(desktop):
  317. log('INSTALL', desktop_name)
  318. apps = 'usr/share/applications'
  319. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  320. if not os.path.exists(appfile):
  321. make_tree(os.path.join(APPDIR, apps))
  322. _copy_template('python.desktop', appfile, version=VERSION,
  323. fullversion=FULLVERSION)
  324. os.symlink(os.path.join(apps, desktop_name), desktop)
  325. # Bundle icons
  326. icons = 'usr/share/icons/hicolor/256x256/apps'
  327. icon = os.path.join(APPDIR, 'python.png')
  328. if not os.path.exists(icon):
  329. log('INSTALL', 'python.png')
  330. make_tree(os.path.join(APPDIR, icons))
  331. copy_file(PREFIX + '/data/python.png',
  332. os.path.join(APPDIR, icons, 'python.png'))
  333. os.symlink(os.path.join(icons, 'python.png'), icon)
  334. diricon = os.path.join(APPDIR, '.DirIcon')
  335. if not os.path.exists(diricon):
  336. os.symlink('python.png', diricon)
  337. # Bundle metadata
  338. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  339. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  340. meta_file = os.path.join(meta_dir, meta_name)
  341. if not os.path.exists(meta_file):
  342. log('INSTALL', meta_name)
  343. make_tree(meta_dir)
  344. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  345. fullversion=FULLVERSION)