1
0

build_debian_packages 4.8 KB

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