build_debian_packages 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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:sid",
  21. "ubuntu:xenial",
  22. "ubuntu:bionic",
  23. "ubuntu:cosmic",
  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):
  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)
  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):
  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. "dh-venv-builder:" + tag,
  86. ], stdout=stdout, stderr=subprocess.STDOUT)
  87. with self._lock:
  88. self.active_containers.remove(container_name)
  89. if stdout is not None:
  90. stdout.close()
  91. print("Completed build of %s" % (dist, ))
  92. def kill_containers(self):
  93. with self._lock:
  94. active = list(self.active_containers)
  95. for c in active:
  96. print("killing container %s" % (c,))
  97. subprocess.run([
  98. "docker", "kill", c,
  99. ], stdout=subprocess.DEVNULL)
  100. with self._lock:
  101. self.active_containers.remove(c)
  102. def run_builds(dists, jobs=1):
  103. builder = Builder(redirect_stdout=(jobs > 1))
  104. def sig(signum, _frame):
  105. print("Caught SIGINT")
  106. builder.kill_containers()
  107. signal.signal(signal.SIGINT, sig)
  108. with ThreadPoolExecutor(max_workers=jobs) as e:
  109. res = e.map(builder.run_build, dists)
  110. # make sure we consume the iterable so that exceptions are raised.
  111. for r in res:
  112. pass
  113. if __name__ == '__main__':
  114. parser = argparse.ArgumentParser(
  115. description=DESC,
  116. )
  117. parser.add_argument(
  118. '-j', '--jobs', type=int, default=1,
  119. help='specify the number of builds to run in parallel',
  120. )
  121. parser.add_argument(
  122. 'dist', nargs='*', default=DISTS,
  123. help='a list of distributions to build for. Default: %(default)s',
  124. )
  125. args = parser.parse_args()
  126. run_builds(dists=args.dist, jobs=args.jobs)