jobserver-exec 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env python
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # This determines how many parallel tasks "make" is expecting, as it is
  5. # not exposed via an special variables, reserves them all, runs a subprocess
  6. # with PARALLELISM environment variable set, and releases the jobs back again.
  7. #
  8. # https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html#POSIX-Jobserver
  9. from __future__ import print_function
  10. import os, sys, errno
  11. import subprocess
  12. # Extract and prepare jobserver file descriptors from envirnoment.
  13. claim = 0
  14. jobs = b""
  15. try:
  16. # Fetch the make environment options.
  17. flags = os.environ['MAKEFLAGS']
  18. # Look for "--jobserver=R,W"
  19. # Note that GNU Make has used --jobserver-fds and --jobserver-auth
  20. # so this handles all of them.
  21. opts = [x for x in flags.split(" ") if x.startswith("--jobserver")]
  22. # Parse out R,W file descriptor numbers and set them nonblocking.
  23. fds = opts[0].split("=", 1)[1]
  24. reader, writer = [int(x) for x in fds.split(",", 1)]
  25. # Open a private copy of reader to avoid setting nonblocking
  26. # on an unexpecting process with the same reader fd.
  27. reader = os.open("/proc/self/fd/%d" % (reader),
  28. os.O_RDONLY | os.O_NONBLOCK)
  29. # Read out as many jobserver slots as possible.
  30. while True:
  31. try:
  32. slot = os.read(reader, 8)
  33. jobs += slot
  34. except (OSError, IOError) as e:
  35. if e.errno == errno.EWOULDBLOCK:
  36. # Stop at the end of the jobserver queue.
  37. break
  38. # If something went wrong, give back the jobs.
  39. if len(jobs):
  40. os.write(writer, jobs)
  41. raise e
  42. # Add a bump for our caller's reserveration, since we're just going
  43. # to sit here blocked on our child.
  44. claim = len(jobs) + 1
  45. except (KeyError, IndexError, ValueError, OSError, IOError) as e:
  46. # Any missing environment strings or bad fds should result in just
  47. # not being parallel.
  48. pass
  49. # We can only claim parallelism if there was a jobserver (i.e. a top-level
  50. # "-jN" argument) and there were no other failures. Otherwise leave out the
  51. # environment variable and let the child figure out what is best.
  52. if claim > 0:
  53. os.environ['PARALLELISM'] = '%d' % (claim)
  54. rc = subprocess.call(sys.argv[1:])
  55. # Return all the reserved slots.
  56. if len(jobs):
  57. os.write(writer, jobs)
  58. sys.exit(rc)