setup.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # borgbackup - main setup code (extension building here, rest see pyproject.toml)
  2. import os
  3. import re
  4. import sys
  5. from collections import defaultdict
  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, Extension
  12. from setuptools.command.sdist import sdist
  13. try:
  14. from Cython.Build import cythonize
  15. cythonize_import_error_msg = None
  16. except ImportError as exc:
  17. # either there is no Cython installed or there is some issue with it.
  18. cythonize = None
  19. cythonize_import_error_msg = "ImportError: " + str(exc)
  20. sys.path += [os.path.dirname(__file__)]
  21. is_win32 = sys.platform.startswith("win32")
  22. is_openbsd = sys.platform.startswith("openbsd")
  23. # Number of threads to use for cythonize, not used on windows
  24. cpu_threads = multiprocessing.cpu_count() if multiprocessing and multiprocessing.get_start_method() != "spawn" else None
  25. # How the build process finds the system libs:
  26. #
  27. # 1. if BORG_{LIBXXX,OPENSSL}_PREFIX is set, it will use headers and libs from there.
  28. # 2. if not and pkg-config can locate the lib, the lib located by
  29. # pkg-config will be used. We use the pkg-config tool via the pkgconfig
  30. # python package, which must be installed before invoking setup.py.
  31. # if pkgconfig is not installed, this step is skipped.
  32. # 3. otherwise raise a fatal error.
  33. # Are we building on ReadTheDocs?
  34. on_rtd = os.environ.get("READTHEDOCS")
  35. # Extra cflags for all extensions, usually just warnings we want to enable explicitly
  36. cflags = ["-Wall", "-Wextra", "-Wpointer-arith"]
  37. compress_source = "src/borg/compress.pyx"
  38. crypto_ll_source = "src/borg/crypto/low_level.pyx"
  39. chunker_source = "src/borg/chunker.pyx"
  40. hashindex_source = "src/borg/hashindex.pyx"
  41. item_source = "src/borg/item.pyx"
  42. checksums_source = "src/borg/checksums.pyx"
  43. platform_posix_source = "src/borg/platform/posix.pyx"
  44. platform_linux_source = "src/borg/platform/linux.pyx"
  45. platform_syncfilerange_source = "src/borg/platform/syncfilerange.pyx"
  46. platform_darwin_source = "src/borg/platform/darwin.pyx"
  47. platform_freebsd_source = "src/borg/platform/freebsd.pyx"
  48. platform_windows_source = "src/borg/platform/windows.pyx"
  49. cython_sources = [
  50. compress_source,
  51. crypto_ll_source,
  52. chunker_source,
  53. hashindex_source,
  54. item_source,
  55. checksums_source,
  56. platform_posix_source,
  57. platform_linux_source,
  58. platform_syncfilerange_source,
  59. platform_freebsd_source,
  60. platform_darwin_source,
  61. platform_windows_source,
  62. ]
  63. if cythonize:
  64. Sdist = sdist
  65. else:
  66. class Sdist(sdist):
  67. def __init__(self, *args, **kwargs):
  68. raise Exception("Cython is required to run sdist")
  69. cython_c_files = [fn.replace(".pyx", ".c") for fn in cython_sources]
  70. if not on_rtd and not all(os.path.exists(path) for path in cython_c_files):
  71. raise ImportError("The GIT version of Borg needs a working Cython. " +
  72. "Install or fix Cython or use a released borg version. " +
  73. "Importing cythonize failed with: " + cythonize_import_error_msg)
  74. cmdclass = {"build_ext": build_ext, "sdist": Sdist}
  75. ext_modules = []
  76. if not on_rtd:
  77. def members_appended(*ds):
  78. result = defaultdict(list)
  79. for d in ds:
  80. for k, v in d.items():
  81. assert isinstance(v, list)
  82. result[k].extend(v)
  83. return result
  84. try:
  85. import pkgconfig as pc
  86. except ImportError:
  87. print("Warning: can not import pkgconfig python package.")
  88. pc = None
  89. def lib_ext_kwargs(pc, prefix_env_var, lib_name, lib_pkg_name, pc_version, lib_subdir="lib"):
  90. system_prefix = os.environ.get(prefix_env_var)
  91. if system_prefix:
  92. print(f"Detected and preferring {lib_pkg_name} [via {prefix_env_var}]")
  93. return dict(
  94. include_dirs=[os.path.join(system_prefix, "include")],
  95. library_dirs=[os.path.join(system_prefix, lib_subdir)],
  96. libraries=[lib_name],
  97. )
  98. if pc and pc.installed(lib_pkg_name, pc_version):
  99. print(f"Detected and preferring {lib_pkg_name} [via pkg-config]")
  100. return pc.parse(lib_pkg_name)
  101. raise Exception(
  102. f"Could not find {lib_name} lib/headers, please set {prefix_env_var} "
  103. f"or ensure {lib_pkg_name}.pc is in PKG_CONFIG_PATH."
  104. )
  105. crypto_extra_objects = []
  106. if is_win32:
  107. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "libcrypto", "libcrypto", ">=1.1.1", lib_subdir="")
  108. elif is_openbsd:
  109. # Use openssl (not libressl) because we need AES-OCB via EVP api. Link
  110. # it statically to avoid conflicting with shared libcrypto from the base
  111. # OS pulled in via dependencies.
  112. crypto_ext_lib = {"include_dirs": ["/usr/local/include/eopenssl30"]}
  113. crypto_extra_objects += ["/usr/local/lib/eopenssl30/libcrypto.a"]
  114. else:
  115. crypto_ext_lib = lib_ext_kwargs(pc, "BORG_OPENSSL_PREFIX", "crypto", "libcrypto", ">=1.1.1")
  116. crypto_ext_kwargs = members_appended(
  117. dict(sources=[crypto_ll_source]),
  118. crypto_ext_lib,
  119. dict(extra_compile_args=cflags),
  120. dict(extra_objects=crypto_extra_objects),
  121. )
  122. compress_ext_kwargs = members_appended(
  123. dict(sources=[compress_source]),
  124. lib_ext_kwargs(pc, "BORG_LIBLZ4_PREFIX", "lz4", "liblz4", ">= 1.7.0"),
  125. lib_ext_kwargs(pc, "BORG_LIBZSTD_PREFIX", "zstd", "libzstd", ">= 1.3.0"),
  126. dict(extra_compile_args=cflags),
  127. )
  128. checksums_ext_kwargs = members_appended(
  129. dict(sources=[checksums_source]),
  130. lib_ext_kwargs(pc, "BORG_LIBXXHASH_PREFIX", "xxhash", "libxxhash", ">= 0.7.3"),
  131. dict(extra_compile_args=cflags),
  132. )
  133. if sys.platform == "linux":
  134. linux_ext_kwargs = members_appended(
  135. dict(sources=[platform_linux_source]),
  136. lib_ext_kwargs(pc, "BORG_LIBACL_PREFIX", "acl", "libacl", ">= 2.2.47"),
  137. dict(extra_compile_args=cflags),
  138. )
  139. else:
  140. linux_ext_kwargs = members_appended(
  141. dict(sources=[platform_linux_source], libraries=["acl"], extra_compile_args=cflags)
  142. )
  143. # note: _chunker.c and _hashindex.c are relatively complex/large pieces of handwritten C code,
  144. # thus we undef NDEBUG for them, so the compiled code will contain and execute assert().
  145. ext_modules += [
  146. Extension("borg.crypto.low_level", **crypto_ext_kwargs),
  147. Extension("borg.compress", **compress_ext_kwargs),
  148. Extension("borg.hashindex", [hashindex_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  149. Extension("borg.item", [item_source], extra_compile_args=cflags),
  150. Extension("borg.chunker", [chunker_source], extra_compile_args=cflags, undef_macros=["NDEBUG"]),
  151. Extension("borg.checksums", **checksums_ext_kwargs),
  152. ]
  153. posix_ext = Extension("borg.platform.posix", [platform_posix_source], extra_compile_args=cflags)
  154. linux_ext = Extension("borg.platform.linux", **linux_ext_kwargs)
  155. syncfilerange_ext = Extension(
  156. "borg.platform.syncfilerange", [platform_syncfilerange_source], extra_compile_args=cflags
  157. )
  158. freebsd_ext = Extension("borg.platform.freebsd", [platform_freebsd_source], extra_compile_args=cflags)
  159. darwin_ext = Extension("borg.platform.darwin", [platform_darwin_source], extra_compile_args=cflags)
  160. windows_ext = Extension("borg.platform.windows", [platform_windows_source], extra_compile_args=cflags)
  161. if not is_win32:
  162. ext_modules.append(posix_ext)
  163. else:
  164. ext_modules.append(windows_ext)
  165. if sys.platform == "linux":
  166. ext_modules.append(linux_ext)
  167. ext_modules.append(syncfilerange_ext)
  168. elif sys.platform.startswith("freebsd"):
  169. ext_modules.append(freebsd_ext)
  170. elif sys.platform == "darwin":
  171. ext_modules.append(darwin_ext)
  172. # sometimes there's no need to cythonize
  173. # this breaks chained commands like 'clean sdist'
  174. cythonizing = (
  175. len(sys.argv) > 1
  176. and sys.argv[1] not in (("clean", "egg_info", "--help-commands", "--version"))
  177. and "--help" not in sys.argv[1:]
  178. )
  179. if cythonize and cythonizing:
  180. # 3str is the default in Cython3 and we do not support older Cython releases.
  181. # we only set this to avoid the related FutureWarning from Cython3.
  182. cython_opts = dict(compiler_directives={"language_level": "3str"})
  183. if not is_win32:
  184. # compile .pyx extensions to .c in parallel, does not work on windows
  185. cython_opts["nthreads"] = cpu_threads
  186. # generate C code from Cython for ALL supported platforms, so we have them in the sdist.
  187. # the sdist does not require Cython at install time, so we need all as C.
  188. cythonize([posix_ext, linux_ext, syncfilerange_ext, freebsd_ext, darwin_ext, windows_ext], **cython_opts)
  189. # generate C code from Cython for THIS platform (and for all platform-independent Cython parts).
  190. ext_modules = cythonize(ext_modules, **cython_opts)
  191. def long_desc_from_readme():
  192. with open("README.rst") as fd:
  193. long_description = fd.read()
  194. # remove header, but have one \n before first headline
  195. start = long_description.find("What is BorgBackup?")
  196. assert start >= 0
  197. long_description = "\n" + long_description[start:]
  198. # remove badges
  199. long_description = re.compile(r"^\.\. start-badges.*^\.\. end-badges", re.M | re.S).sub("", long_description)
  200. # remove unknown directives
  201. long_description = re.compile(r"^\.\. highlight:: \w+$", re.M).sub("", long_description)
  202. return long_description
  203. setup(cmdclass=cmdclass, ext_modules=ext_modules, long_description=long_desc_from_readme())