1
0

build_debian_packages 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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:stretch",
  19. "debian:buster",
  20. "debian:bullseye",
  21. "debian:sid",
  22. "ubuntu:xenial",
  23. "ubuntu:bionic",
  24. "ubuntu:focal",
  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):
  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)
  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):
  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. "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):
  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(builder.run_build, 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. 'dist', nargs='*', default=DISTS,
  124. help='a list of distributions to build for. Default: %(default)s',
  125. )
  126. args = parser.parse_args()
  127. run_builds(dists=args.dist, jobs=args.jobs)