build_debian_packages.py 6.6 KB

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