build_debian_packages 5.0 KB

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