build_debian_packages 6.4 KB

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