1
0

build_debian_packages 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. "ubuntu:groovy",
  26. )
  27. DESC = '''\
  28. Builds .debs for synapse, using a Docker image for the build environment.
  29. By default, builds for all known distributions, but a list of distributions
  30. can be passed on the commandline for debugging.
  31. '''
  32. class Builder(object):
  33. def __init__(self, redirect_stdout=False):
  34. self.redirect_stdout = redirect_stdout
  35. self.active_containers = set()
  36. self._lock = threading.Lock()
  37. self._failed = False
  38. def run_build(self, dist):
  39. """Build deb for a single distribution"""
  40. if self._failed:
  41. print("not building %s due to earlier failure" % (dist, ))
  42. raise Exception("failed")
  43. try:
  44. self._inner_build(dist)
  45. except Exception as e:
  46. print("build of %s failed: %s" % (dist, e), file=sys.stderr)
  47. self._failed = True
  48. raise
  49. def _inner_build(self, dist):
  50. projdir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  51. os.chdir(projdir)
  52. tag = dist.split(":", 1)[1]
  53. # Make the dir where the debs will live.
  54. #
  55. # Note that we deliberately put this outside the source tree, otherwise
  56. # we tend to get source packages which are full of debs. (We could hack
  57. # around that with more magic in the build_debian.sh script, but that
  58. # doesn't solve the problem for natively-run dpkg-buildpakage).
  59. debsdir = os.path.join(projdir, '../debs')
  60. os.makedirs(debsdir, exist_ok=True)
  61. if self.redirect_stdout:
  62. logfile = os.path.join(debsdir, "%s.buildlog" % (tag, ))
  63. print("building %s: directing output to %s" % (dist, logfile))
  64. stdout = open(logfile, "w")
  65. else:
  66. stdout = None
  67. # first build a docker image for the build environment
  68. subprocess.check_call([
  69. "docker", "build",
  70. "--tag", "dh-venv-builder:" + tag,
  71. "--build-arg", "distro=" + dist,
  72. "-f", "docker/Dockerfile-dhvirtualenv",
  73. "docker",
  74. ], stdout=stdout, stderr=subprocess.STDOUT)
  75. container_name = "synapse_build_" + tag
  76. with self._lock:
  77. self.active_containers.add(container_name)
  78. # then run the build itself
  79. subprocess.check_call([
  80. "docker", "run",
  81. "--rm",
  82. "--name", container_name,
  83. "--volume=" + projdir + ":/synapse/source:ro",
  84. "--volume=" + debsdir + ":/debs",
  85. "-e", "TARGET_USERID=%i" % (os.getuid(), ),
  86. "-e", "TARGET_GROUPID=%i" % (os.getgid(), ),
  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):
  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(builder.run_build, 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. 'dist', nargs='*', default=DISTS,
  125. help='a list of distributions to build for. Default: %(default)s',
  126. )
  127. args = parser.parse_args()
  128. run_builds(dists=args.dist, jobs=args.jobs)