build_debian_packages.py 6.6 KB

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