1
0

relocate.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 patch_site(path, patch):
  89. '''Patch the site.py module for running Python from an AppImage
  90. '''
  91. with open(path) as f:
  92. source = f.read()
  93. if '_initappimage' in source: return
  94. lines = source.split(os.linesep)
  95. for i, line in enumerate(lines):
  96. if line.startswith('def main('): break
  97. else:
  98. return
  99. with open(patch) as f:
  100. patch = f.read()
  101. lines.insert(i, patch)
  102. lines.insert(i + 1, '')
  103. source = os.linesep.join(lines)
  104. with open(path, 'w') as f:
  105. f.write(source)
  106. def relocate_python(python=None, appdir=None):
  107. '''Bundle a Python install inside an AppDir
  108. '''
  109. if python is not None:
  110. if not os.path.exists(python):
  111. raise ValueError('could not access ' + python)
  112. if appdir is None:
  113. appdir = 'AppDir'
  114. # Set some key variables & paths
  115. if python:
  116. FULLVERSION = system((python, '-c',
  117. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"'))
  118. FULLVERSION = FULLVERSION.strip()
  119. else:
  120. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  121. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  122. PYTHON_X_Y = 'python' + VERSION
  123. PIP_X_Y = 'pip' + VERSION
  124. PIP_X = 'pip' + VERSION[0]
  125. APPDIR = os.path.abspath(appdir)
  126. APPDIR_BIN = APPDIR + '/usr/bin'
  127. APPDIR_LIB = APPDIR + '/usr/lib'
  128. APPDIR_SHARE = APPDIR + '/usr/share'
  129. if python:
  130. HOST_PREFIX = system((
  131. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  132. else:
  133. HOST_PREFIX = sys.prefix
  134. HOST_BIN = HOST_PREFIX + '/bin'
  135. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  136. HOST_LIB = HOST_PREFIX + '/lib'
  137. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  138. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  139. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  140. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  141. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  142. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  143. if not os.path.exists(HOST_INC):
  144. HOST_INC += 'm'
  145. PYTHON_INC += 'm'
  146. # Copy the running Python's install
  147. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  148. source = HOST_BIN + '/' + PYTHON_X_Y
  149. if not os.path.exists(source):
  150. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  151. make_tree(PYTHON_BIN)
  152. target = PYTHON_BIN + '/' + PYTHON_X_Y
  153. copy_file(source, target, update=True)
  154. relpath = os.path.relpath(target, APPDIR_BIN)
  155. make_tree(APPDIR_BIN)
  156. os.symlink(relpath, APPDIR_BIN + '/' + PYTHON_X_Y)
  157. copy_tree(HOST_PKG, PYTHON_PKG)
  158. copy_tree(HOST_INC, PYTHON_INC)
  159. pip_source = HOST_BIN + '/' + PIP_X_Y
  160. if not os.path.exists(pip_source):
  161. pip_source = HOST_BIN + '/' + PIP_X
  162. if os.path.exists(pip_source):
  163. with open(pip_source) as f:
  164. f.readline()
  165. body = f.read()
  166. target = PYTHON_BIN + '/' + PIP_X_Y
  167. with open(target, 'w') as f:
  168. f.write('#! /bin/sh\n')
  169. f.write(' '.join((
  170. '"exec"',
  171. '"$(dirname $(readlink -f ${0}))/' + PYTHON_X_Y + '"',
  172. '"$0"',
  173. '"$@"\n'
  174. )))
  175. f.write(body)
  176. shutil.copymode(pip_source, target)
  177. relpath = os.path.relpath(target, APPDIR_BIN)
  178. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  179. # Remove unrelevant files
  180. log('PRUNE', '%s packages', PYTHON_X_Y)
  181. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  182. remove_tree(PYTHON_PKG + '/test')
  183. remove_file(PYTHON_PKG + '/dist-packages')
  184. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  185. for path in matches:
  186. remove_tree(path)
  187. # Set or update symlinks to python
  188. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  189. versions = [os.path.basename(python)[6:] for python in pythons]
  190. latest2, latest3 = '0.0', '0.0'
  191. for version in versions:
  192. if version.startswith('2') and version >= latest2:
  193. latest2 = version
  194. elif version.startswith('3') and version >= latest3:
  195. latest3 = version
  196. if latest2 == VERSION:
  197. python2 = APPDIR_BIN + '/python2'
  198. remove_file(python2)
  199. os.symlink(PYTHON_X_Y, python2)
  200. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  201. if has_pip:
  202. pip2 = APPDIR_BIN + '/pip2'
  203. remove_file(pip2)
  204. os.symlink(PIP_X_Y, pip2)
  205. if latest3 == '0.0':
  206. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  207. python = APPDIR_BIN + '/python'
  208. remove_file(python)
  209. os.symlink('python2', python)
  210. if has_pip:
  211. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  212. pip = APPDIR_BIN + '/pip'
  213. remove_file(pip)
  214. os.symlink('pip2', pip)
  215. else:
  216. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  217. if has_pip:
  218. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  219. elif latest3 == VERSION:
  220. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  221. python3 = APPDIR_BIN + '/python3'
  222. remove_file(python3)
  223. os.symlink(PYTHON_X_Y, python3)
  224. python = APPDIR_BIN + '/python'
  225. remove_file(python)
  226. os.symlink('python3', python)
  227. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  228. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  229. pip3 = APPDIR_BIN + '/pip3'
  230. remove_file(pip3)
  231. os.symlink(PIP_X_Y, pip3)
  232. pip = APPDIR_BIN + '/pip'
  233. remove_file(pip)
  234. os.symlink('pip3', pip)
  235. # Patch the site.py module
  236. log('PATCH', '%s site.py', PYTHON_X_Y)
  237. sitepath = PYTHON_PKG + '/site.py'
  238. patch_site(sitepath, PREFIX + '/data/site-patch.py')
  239. # Set a hook in Python for cleaning the path detection
  240. log('HOOK', '%s site-packages', PYTHON_X_Y)
  241. sitepkgs = PYTHON_PKG + '/site-packages'
  242. make_tree(sitepkgs)
  243. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  244. # Set RPATHs and bundle external libraries
  245. log('LINK', '%s C-extensions', PYTHON_X_Y)
  246. make_tree(APPDIR_LIB)
  247. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  248. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  249. for file_ in files:
  250. if not file_.endswith('.so'):
  251. continue
  252. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  253. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  254. patch_binary(file_, APPDIR_LIB, recursive=True)
  255. # Copy shared data for TCl/Tk
  256. tk_version = _get_tk_version(PYTHON_PKG)
  257. if tk_version is not None:
  258. tcltkdir = APPDIR_SHARE + '/tcltk'
  259. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  260. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  261. hostdir = '/usr/share/tcltk'
  262. if os.path.exists(hostdir):
  263. make_tree(APPDIR_SHARE)
  264. copy_tree(hostdir, tcltkdir)
  265. else:
  266. make_tree(tcltkdir)
  267. tclpath = '/usr/share/tcl' + tk_version
  268. if not tclpath:
  269. raise ValueError('could not find ' + tclpath)
  270. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  271. tkpath = '/usr/share/tk' + tk_version
  272. if not tkpath:
  273. raise ValueError('could not find ' + tkpath)
  274. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  275. # Copy any SSL certificate
  276. cert_file = os.getenv('SSL_CERT_FILE')
  277. if cert_file:
  278. # Package certificates as well for SSL
  279. # (see https://github.com/niess/python-appimage/issues/24)
  280. dirname, basename = os.path.split(cert_file)
  281. make_tree('AppDir' + dirname)
  282. copy_file(cert_file, 'AppDir' + cert_file)
  283. log('INSTALL', basename)
  284. # Bundle the entry point
  285. apprun = APPDIR + '/AppRun'
  286. if not os.path.exists(apprun):
  287. log('INSTALL', 'AppRun')
  288. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  289. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  290. dictionary = {'entrypoint': entrypoint,
  291. 'shebang': '#! /bin/bash',
  292. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  293. 'cert-file': cert_file_env_string(cert_file)}
  294. _copy_template('apprun.sh', apprun, **dictionary)
  295. # Bundle the desktop file
  296. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  297. desktop = os.path.join(APPDIR, desktop_name)
  298. if not os.path.exists(desktop):
  299. log('INSTALL', desktop_name)
  300. apps = 'usr/share/applications'
  301. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  302. if not os.path.exists(appfile):
  303. make_tree(os.path.join(APPDIR, apps))
  304. _copy_template('python.desktop', appfile, version=VERSION,
  305. fullversion=FULLVERSION)
  306. os.symlink(os.path.join(apps, desktop_name), desktop)
  307. # Bundle icons
  308. icons = 'usr/share/icons/hicolor/256x256/apps'
  309. icon = os.path.join(APPDIR, 'python.png')
  310. if not os.path.exists(icon):
  311. log('INSTALL', 'python.png')
  312. make_tree(os.path.join(APPDIR, icons))
  313. copy_file(PREFIX + '/data/python.png',
  314. os.path.join(APPDIR, icons, 'python.png'))
  315. os.symlink(os.path.join(icons, 'python.png'), icon)
  316. diricon = os.path.join(APPDIR, '.DirIcon')
  317. if not os.path.exists(diricon):
  318. os.symlink('python.png', diricon)
  319. # Bundle metadata
  320. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  321. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  322. meta_file = os.path.join(meta_dir, meta_name)
  323. if not os.path.exists(meta_file):
  324. log('INSTALL', meta_name)
  325. make_tree(meta_dir)
  326. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  327. fullversion=FULLVERSION)