setup.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. # borgbackup - main setup code (see also setup.cfg and other setup_*.py files)
  2. import os
  3. import sys
  4. from collections import defaultdict
  5. from glob import glob
  6. try:
  7. import multiprocessing
  8. except ImportError:
  9. multiprocessing = None
  10. from setuptools.command.build_ext import build_ext
  11. from setuptools import setup, find_packages, Extension, Command
  12. from setuptools.command.sdist import sdist
  13. try:
  14. from Cython.Build import cythonize
  15. except ImportError:
  16. cythonize = None
  17. sys.path += [os.path.dirname(__file__)]
  18. import setup_docs
  19. is_win32 = sys.platform.startswith('win32')
  20. is_openbsd = sys.platform.startswith('openbsd')
  21. # Number of threads to use for cythonize, not used on windows
  22. cpu_threads = multiprocessing.cpu_count() if multiprocessing and multiprocessing.get_start_method() != 'spawn' else None
  23. # How the build process finds the system libs:
  24. #
  25. # 1. if BORG_{LIBXXX,OPENSSL}_PREFIX is set, it will use headers and libs from there.
  26. # 2. if not and pkg-config can locate the lib, the lib located by
  27. # pkg-config will be used. We use the pkg-config tool via the pkgconfig
  28. # python package, which must be installed before invoking setup.py.
  29. # if pkgconfig is not installed, this step is skipped.
  30. # 3. otherwise raise a fatal error.
  31. # Are we building on ReadTheDocs?
  32. on_rtd = os.environ.get('READTHEDOCS')
  33. # Extra cflags for all extensions, usually just warnings we want to explicitly enable
  34. cflags = [
  35. '-Wall',
  36. '-Wextra',
  37. '-Wpointer-arith',
  38. ]
  39. compress_source = 'src/borg/compress.pyx'
  40. crypto_ll_source = 'src/borg/crypto/low_level.pyx'
  41. crypto_helpers = 'src/borg/crypto/_crypto_helpers.c'
  42. chunker_source = 'src/borg/chunker.pyx'
  43. hashindex_source = 'src/borg/hashindex.pyx'
  44. item_source = 'src/borg/item.pyx'
  45. checksums_source = 'src/borg/checksums.pyx'
  46. platform_posix_source = 'src/borg/platform/posix.pyx'
  47. platform_linux_source = 'src/borg/platform/linux.pyx'
  48. platform_syncfilerange_source = 'src/borg/platform/syncfilerange.pyx'
  49. platform_darwin_source = 'src/borg/platform/darwin.pyx'
  50. platform_freebsd_source = 'src/borg/platform/freebsd.pyx'
  51. platform_windows_source = 'src/borg/platform/windows.pyx'
  52. cython_sources = [
  53. compress_source,
  54. crypto_ll_source,
  55. chunker_source,
  56. hashindex_source,
  57. item_source,
  58. checksums_source,
  59. platform_posix_source,
  60. platform_linux_source,
  61. platform_syncfilerange_source,
  62. platform_freebsd_source,
  63. platform_darwin_source,
  64. platform_windows_source,
  65. ]
  66. if cythonize:
  67. Sdist = sdist
  68. else:
  69. class Sdist(sdist):
  70. def __init__(self, *args, **kwargs):
  71. raise Exception('Cython is required to run sdist')
  72. cython_c_files = [fn.replace('.pyx', '.c') for fn in cython_sources]
  73. if not on_rtd and not all(os.path.exists(path) for path in cython_c_files):
  74. raise ImportError('The GIT version of Borg needs Cython. Install Cython or use a released version.')
  75. def rm(file):
  76. try:
  77. os.unlink(file)
  78. print('rm', file)
  79. except FileNotFoundError:
  80. pass
  81. class Clean(Command):
  82. user_options = []
  83. def initialize_options(self):
  84. pass
  85. def finalize_options(self):
  86. pass
  87. def run(self):
  88. for source in cython_sources:
  89. genc = source.replace('.pyx', '.c')
  90. rm(genc)
  91. compiled_glob = source.replace('.pyx', '.cpython*')
  92. for compiled in sorted(glob(compiled_glob)):
  93. rm(compiled)
  94. cmdclass = {
  95. 'build_ext': build_ext,
  96. 'build_usage': setup_docs.build_usage,
  97. 'build_man': setup_docs.build_man,
  98. 'sdist': Sdist,
  99. 'clean2': Clean,
  100. }
  101. ext_modules = []
  102. if not on_rtd:
  103. def members_appended(*ds):
  104. result = defaultdict(list)
  105. for d in ds:
  106. for k, v in d.items():
  107. assert isinstance(v, list)
  108. result[k].extend(v)
  109. return result
  110. try:
  111. import pkgconfig as pc
  112. except ImportError:
  113. print('Warning: can not import pkgconfig python package.')
  114. pc = None
  115. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir='lib'):
  116. system_prefix = os.environ.get(prefix_env_var)
  117. if system_prefix:
  118. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  119. return dict(include_dirs=[os.path.join(system_prefix, 'include')],
  120. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  121. libraries=[lib_name])
  122. if pc and pc.installed(lib_pkg_name, pc_version):
  123. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  124. return pc.parse(lib_pkg_name)
  125. raise Exception(
  126. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  127. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  128. )
  129. crypto_ldflags = []
  130. if is_win32:
  131. crypto_ext_lib = lib_ext_kwargs(
  132. pc, 'BORG_OPENSSL_PREFIX', 'libcrypto', 'libcrypto', '>=1.1.1', lib_subdir='')
  133. elif is_openbsd:
  134. # use openssl (not libressl) because we need AES-OCB and CHACHA20-POLY1305 via EVP api
  135. crypto_ext_lib = lib_ext_kwargs(
  136. pc, 'BORG_OPENSSL_PREFIX', 'crypto', 'libecrypto11', '>=1.1.1')
  137. crypto_ldflags += ['-Wl,-rpath=/usr/local/lib/eopenssl11']
  138. else:
  139. crypto_ext_lib = lib_ext_kwargs(
  140. pc, 'BORG_OPENSSL_PREFIX', 'crypto', 'libcrypto', '>=1.1.1')
  141. crypto_ext_kwargs = members_appended(
  142. dict(sources=[crypto_ll_source, crypto_helpers]),
  143. crypto_ext_lib,
  144. dict(extra_compile_args=cflags),
  145. dict(extra_link_args=crypto_ldflags),
  146. )
  147. compress_ext_kwargs = members_appended(
  148. dict(sources=[compress_source]),
  149. lib_ext_kwargs(pc, 'BORG_LIBLZ4_PREFIX', 'lz4', 'liblz4', '>= 1.7.0'),
  150. lib_ext_kwargs(pc, 'BORG_LIBZSTD_PREFIX', 'zstd', 'libzstd', '>= 1.3.0'),
  151. dict(extra_compile_args=cflags),
  152. )
  153. checksums_ext_kwargs = members_appended(
  154. dict(sources=[checksums_source]),
  155. lib_ext_kwargs(pc, 'BORG_LIBXXHASH_PREFIX', 'xxhash', 'libxxhash', '>= 0.7.3'),
  156. lib_ext_kwargs(pc, 'BORG_LIBDEFLATE_PREFIX', 'deflate', 'libdeflate', '>= 1.5'),
  157. dict(extra_compile_args=cflags),
  158. )
  159. ext_modules += [
  160. Extension('borg.crypto.low_level', **crypto_ext_kwargs),
  161. Extension('borg.compress', **compress_ext_kwargs),
  162. Extension('borg.hashindex', [hashindex_source], extra_compile_args=cflags),
  163. Extension('borg.item', [item_source], extra_compile_args=cflags),
  164. Extension('borg.chunker', [chunker_source], extra_compile_args=cflags),
  165. Extension('borg.checksums', **checksums_ext_kwargs),
  166. ]
  167. posix_ext = Extension('borg.platform.posix', [platform_posix_source], extra_compile_args=cflags)
  168. linux_ext = Extension('borg.platform.linux', [platform_linux_source], libraries=['acl'], extra_compile_args=cflags)
  169. syncfilerange_ext = Extension('borg.platform.syncfilerange', [platform_syncfilerange_source], extra_compile_args=cflags)
  170. freebsd_ext = Extension('borg.platform.freebsd', [platform_freebsd_source], extra_compile_args=cflags)
  171. darwin_ext = Extension('borg.platform.darwin', [platform_darwin_source], extra_compile_args=cflags)
  172. windows_ext = Extension('borg.platform.windows', [platform_windows_source], extra_compile_args=cflags)
  173. if not is_win32:
  174. ext_modules.append(posix_ext)
  175. else:
  176. ext_modules.append(windows_ext)
  177. if sys.platform == 'linux':
  178. ext_modules.append(linux_ext)
  179. ext_modules.append(syncfilerange_ext)
  180. elif sys.platform.startswith('freebsd'):
  181. ext_modules.append(freebsd_ext)
  182. elif sys.platform == 'darwin':
  183. ext_modules.append(darwin_ext)
  184. # sometimes there's no need to cythonize
  185. # this breaks chained commands like 'clean sdist'
  186. cythonizing = len(sys.argv) > 1 and sys.argv[1] not in (
  187. ('clean', 'clean2', 'egg_info', '--help-commands', '--version')) and '--help' not in sys.argv[1:]
  188. if cythonize and cythonizing:
  189. cython_opts = dict(
  190. # default language_level will be '3str' starting from Cython 3.0.0,
  191. # but old cython versions (< 0.29) do not know that, thus we use 3 for now.
  192. compiler_directives={'language_level': 3},
  193. )
  194. if not is_win32:
  195. # compile .pyx extensions to .c in parallel, does not work on windows
  196. cython_opts['nthreads'] = cpu_threads
  197. # generate C code from Cython for ALL supported platforms, so we have them in the sdist.
  198. # the sdist does not require Cython at install time, so we need all as C.
  199. cythonize([posix_ext, linux_ext, syncfilerange_ext, freebsd_ext, darwin_ext, windows_ext], **cython_opts)
  200. # generate C code from Cython for THIS platform (and for all platform-independent Cython parts).
  201. ext_modules = cythonize(ext_modules, **cython_opts)
  202. setup(
  203. cmdclass=cmdclass,
  204. ext_modules=ext_modules,
  205. long_description=setup_docs.long_desc_from_readme()
  206. )