build_debian_packages.py 6.7 KB

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