setup.py 10 KB

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