build_debian_packages 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 os
  12. import signal
  13. import subprocess
  14. import sys
  15. import threading
  16. from concurrent.futures import ThreadPoolExecutor
  17. DISTS = (
  18. "debian:buster",
  19. "debian:bullseye",
  20. "debian:sid",
  21. "ubuntu:bionic", # 18.04 LTS (our EOL forced by Py36 on 2021-12-23)
  22. "ubuntu:focal", # 20.04 LTS (our EOL forced by Py38 on 2024-10-14)
  23. "ubuntu:groovy", # 20.10 (EOL 2021-07-07)
  24. "ubuntu:hirsute", # 21.04 (EOL 2022-01-05)
  25. )
  26. DESC = '''\
  27. Builds .debs for synapse, using a Docker image for the build environment.
  28. By default, builds for all known distributions, but a list of distributions
  29. can be passed on the commandline for debugging.
  30. '''
  31. class Builder(object):
  32. def __init__(self, redirect_stdout=False):
  33. self.redirect_stdout = redirect_stdout
  34. self.active_containers = set()
  35. self._lock = threading.Lock()
  36. self._failed = False
  37. def run_build(self, dist, skip_tests=False):
  38. """Build deb for a single distribution"""
  39. if self._failed:
  40. print("not building %s due to earlier failure" % (dist, ))
  41. raise Exception("failed")
  42. try:
  43. self._inner_build(dist, skip_tests)
  44. except Exception as e:
  45. print("build of %s failed: %s" % (dist, e), file=sys.stderr)
  46. self._failed = True
  47. raise
  48. def _inner_build(self, dist, skip_tests=False):
  49. projdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  50. os.chdir(projdir)
  51. tag = dist.split(":", 1)[1]
  52. # Make the dir where the debs will live.
  53. #
  54. # Note that we deliberately put this outside the source tree, otherwise
  55. # we tend to get source packages which are full of debs. (We could hack
  56. # around that with more magic in the build_debian.sh script, but that
  57. # doesn't solve the problem for natively-run dpkg-buildpakage).
  58. debsdir = os.path.join(projdir, '../debs')
  59. os.makedirs(debsdir, exist_ok=True)
  60. if self.redirect_stdout:
  61. logfile = os.path.join(debsdir, "%s.buildlog" % (tag, ))
  62. print("building %s: directing output to %s" % (dist, logfile))
  63. stdout = open(logfile, "w")
  64. else:
  65. stdout = None
  66. # first build a docker image for the build environment
  67. subprocess.check_call([
  68. "docker", "build",
  69. "--tag", "dh-venv-builder:" + tag,
  70. "--build-arg", "distro=" + dist,
  71. "-f", "docker/Dockerfile-dhvirtualenv",
  72. "docker",
  73. ], stdout=stdout, stderr=subprocess.STDOUT)
  74. container_name = "synapse_build_" + tag
  75. with self._lock:
  76. self.active_containers.add(container_name)
  77. # then run the build itself
  78. subprocess.check_call([
  79. "docker", "run",
  80. "--rm",
  81. "--name", container_name,
  82. "--volume=" + projdir + ":/synapse/source:ro",
  83. "--volume=" + debsdir + ":/debs",
  84. "-e", "TARGET_USERID=%i" % (os.getuid(), ),
  85. "-e", "TARGET_GROUPID=%i" % (os.getgid(), ),
  86. "-e", "DEB_BUILD_OPTIONS=%s" % ("nocheck" if skip_tests else ""),
  87. "dh-venv-builder:" + tag,
  88. ], stdout=stdout, stderr=subprocess.STDOUT)
  89. with self._lock:
  90. self.active_containers.remove(container_name)
  91. if stdout is not None:
  92. stdout.close()
  93. print("Completed build of %s" % (dist, ))
  94. def kill_containers(self):
  95. with self._lock:
  96. active = list(self.active_containers)
  97. for c in active:
  98. print("killing container %s" % (c,))
  99. subprocess.run([
  100. "docker", "kill", c,
  101. ], stdout=subprocess.DEVNULL)
  102. with self._lock:
  103. self.active_containers.remove(c)
  104. def run_builds(dists, jobs=1, skip_tests=False):
  105. builder = Builder(redirect_stdout=(jobs > 1))
  106. def sig(signum, _frame):
  107. print("Caught SIGINT")
  108. builder.kill_containers()
  109. signal.signal(signal.SIGINT, sig)
  110. with ThreadPoolExecutor(max_workers=jobs) as e:
  111. res = e.map(lambda dist: builder.run_build(dist, skip_tests), dists)
  112. # make sure we consume the iterable so that exceptions are raised.
  113. for r in res:
  114. pass
  115. if __name__ == '__main__':
  116. parser = argparse.ArgumentParser(
  117. description=DESC,
  118. )
  119. parser.add_argument(
  120. '-j', '--jobs', type=int, default=1,
  121. help='specify the number of builds to run in parallel',
  122. )
  123. parser.add_argument(
  124. '--no-check', action='store_true',
  125. help='skip running tests after building',
  126. )
  127. parser.add_argument(
  128. 'dist', nargs='*', default=DISTS,
  129. help='a list of distributions to build for. Default: %(default)s',
  130. )
  131. args = parser.parse_args()
  132. run_builds(dists=args.dist, jobs=args.jobs, skip_tests=args.no_check)