build_debian_packages 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env python3
  2. # Build the Debian packages using Docker images.
  3. #
  4. # This script builds the Docker images and then executes them sequentially, each
  5. # one building a Debian package for the targeted operating system. It is
  6. # designed to be a "single command" to produce all the images.
  7. #
  8. # By default, builds for all known distributions, but a list of distributions
  9. # can be passed on the commandline for debugging.
  10. import argparse
  11. import json
  12. import os
  13. import signal
  14. import subprocess
  15. import sys
  16. import threading
  17. from concurrent.futures import ThreadPoolExecutor
  18. from typing import Optional, Sequence
  19. DISTS = (
  20. "debian:buster", # oldstable: EOL 2022-08
  21. "debian:bullseye",
  22. "debian:bookworm",
  23. "debian:sid",
  24. "ubuntu:bionic", # 18.04 LTS (our EOL forced by Py36 on 2021-12-23)
  25. "ubuntu:focal", # 20.04 LTS (our EOL forced by Py38 on 2024-10-14)
  26. "ubuntu:hirsute", # 21.04 (EOL 2022-01-05)
  27. "ubuntu:impish", # 21.10 (EOL 2022-07)
  28. )
  29. DESC = """\
  30. Builds .debs for synapse, using a Docker image for the build environment.
  31. By default, builds for all known distributions, but a list of distributions
  32. can be passed on the commandline for debugging.
  33. """
  34. projdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  35. class Builder(object):
  36. def __init__(
  37. self, redirect_stdout=False, docker_build_args: Optional[Sequence[str]] = None
  38. ):
  39. self.redirect_stdout = redirect_stdout
  40. self._docker_build_args = tuple(docker_build_args or ())
  41. self.active_containers = set()
  42. self._lock = threading.Lock()
  43. self._failed = False
  44. def run_build(self, dist, skip_tests=False):
  45. """Build deb for a single distribution"""
  46. if self._failed:
  47. print("not building %s due to earlier failure" % (dist,))
  48. raise Exception("failed")
  49. try:
  50. self._inner_build(dist, skip_tests)
  51. except Exception as e:
  52. print("build of %s failed: %s" % (dist, e), file=sys.stderr)
  53. self._failed = True
  54. raise
  55. def _inner_build(self, dist, skip_tests=False):
  56. tag = dist.split(":", 1)[1]
  57. # Make the dir where the debs will live.
  58. #
  59. # Note that we deliberately put this outside the source tree, otherwise
  60. # we tend to get source packages which are full of debs. (We could hack
  61. # around that with more magic in the build_debian.sh script, but that
  62. # doesn't solve the problem for natively-run dpkg-buildpakage).
  63. debsdir = os.path.join(projdir, "../debs")
  64. os.makedirs(debsdir, exist_ok=True)
  65. if self.redirect_stdout:
  66. logfile = os.path.join(debsdir, "%s.buildlog" % (tag,))
  67. print("building %s: directing output to %s" % (dist, logfile))
  68. stdout = open(logfile, "w")
  69. else:
  70. stdout = None
  71. # first build a docker image for the build environment
  72. build_args = (
  73. (
  74. "docker",
  75. "build",
  76. "--tag",
  77. "dh-venv-builder:" + tag,
  78. "--build-arg",
  79. "distro=" + dist,
  80. "-f",
  81. "docker/Dockerfile-dhvirtualenv",
  82. )
  83. + self._docker_build_args
  84. + ("docker",)
  85. )
  86. subprocess.check_call(
  87. build_args,
  88. stdout=stdout,
  89. stderr=subprocess.STDOUT,
  90. cwd=projdir,
  91. )
  92. container_name = "synapse_build_" + tag
  93. with self._lock:
  94. self.active_containers.add(container_name)
  95. # then run the build itself
  96. subprocess.check_call(
  97. [
  98. "docker",
  99. "run",
  100. "--rm",
  101. "--name",
  102. container_name,
  103. "--volume=" + projdir + ":/synapse/source:ro",
  104. "--volume=" + debsdir + ":/debs",
  105. "-e",
  106. "TARGET_USERID=%i" % (os.getuid(),),
  107. "-e",
  108. "TARGET_GROUPID=%i" % (os.getgid(),),
  109. "-e",
  110. "DEB_BUILD_OPTIONS=%s" % ("nocheck" if skip_tests else ""),
  111. "dh-venv-builder:" + tag,
  112. ],
  113. stdout=stdout,
  114. stderr=subprocess.STDOUT,
  115. )
  116. with self._lock:
  117. self.active_containers.remove(container_name)
  118. if stdout is not None:
  119. stdout.close()
  120. print("Completed build of %s" % (dist,))
  121. def kill_containers(self):
  122. with self._lock:
  123. active = list(self.active_containers)
  124. for c in active:
  125. print("killing container %s" % (c,))
  126. subprocess.run(
  127. [
  128. "docker",
  129. "kill",
  130. c,
  131. ],
  132. stdout=subprocess.DEVNULL,
  133. )
  134. with self._lock:
  135. self.active_containers.remove(c)
  136. def run_builds(builder, dists, jobs=1, skip_tests=False):
  137. def sig(signum, _frame):
  138. print("Caught SIGINT")
  139. builder.kill_containers()
  140. signal.signal(signal.SIGINT, sig)
  141. with ThreadPoolExecutor(max_workers=jobs) as e:
  142. res = e.map(lambda dist: builder.run_build(dist, skip_tests), dists)
  143. # make sure we consume the iterable so that exceptions are raised.
  144. for _ in res:
  145. pass
  146. if __name__ == "__main__":
  147. parser = argparse.ArgumentParser(
  148. description=DESC,
  149. )
  150. parser.add_argument(
  151. "-j",
  152. "--jobs",
  153. type=int,
  154. default=1,
  155. help="specify the number of builds to run in parallel",
  156. )
  157. parser.add_argument(
  158. "--no-check",
  159. action="store_true",
  160. help="skip running tests after building",
  161. )
  162. parser.add_argument(
  163. "--docker-build-arg",
  164. action="append",
  165. help="specify an argument to pass to docker build",
  166. )
  167. parser.add_argument(
  168. "--show-dists-json",
  169. action="store_true",
  170. help="instead of building the packages, just list the dists to build for, as a json array",
  171. )
  172. parser.add_argument(
  173. "dist",
  174. nargs="*",
  175. default=DISTS,
  176. help="a list of distributions to build for. Default: %(default)s",
  177. )
  178. args = parser.parse_args()
  179. if args.show_dists_json:
  180. print(json.dumps(DISTS))
  181. else:
  182. builder = Builder(
  183. redirect_stdout=(args.jobs > 1), docker_build_args=args.docker_build_arg
  184. )
  185. run_builds(
  186. builder,
  187. dists=args.dist,
  188. jobs=args.jobs,
  189. skip_tests=args.no_check,
  190. )