You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

231 lines
7.3 KiB

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