build_debian_packages 6.4 KB

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