jobserver.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # pylint: disable=C0103,C0209
  5. #
  6. #
  7. """
  8. Interacts with the POSIX jobserver during the Kernel build time.
  9. A "normal" jobserver task, like the one initiated by a make subrocess would do:
  10. - open read/write file descriptors to communicate with the job server;
  11. - ask for one slot by calling::
  12. claim = os.read(reader, 1)
  13. - when the job finshes, call::
  14. os.write(writer, b"+") # os.write(writer, claim)
  15. Here, the goal is different: This script aims to get the remaining number
  16. of slots available, using all of them to run a command which handle tasks in
  17. parallel. To to that, it has a loop that ends only after there are no
  18. slots left. It then increments the number by one, in order to allow a
  19. call equivalent to ``make -j$((claim+1))``, e.g. having a parent make creating
  20. $claim child to do the actual work.
  21. The end goal here is to keep the total number of build tasks under the
  22. limit established by the initial ``make -j$n_proc`` call.
  23. See:
  24. https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html#POSIX-Jobserver
  25. """
  26. import errno
  27. import os
  28. import subprocess
  29. import sys
  30. def warn(text, *args):
  31. print(f'WARNING: {text}', *args, file = sys.stderr)
  32. class JobserverExec:
  33. """
  34. Claim all slots from make using POSIX Jobserver.
  35. The main methods here are:
  36. - open(): reserves all slots;
  37. - close(): method returns all used slots back to make;
  38. - run(): executes a command setting PARALLELISM=<available slots jobs + 1>.
  39. """
  40. def __init__(self):
  41. """Initialize internal vars."""
  42. self.claim = 0
  43. self.jobs = b""
  44. self.reader = None
  45. self.writer = None
  46. self.is_open = False
  47. def open(self):
  48. """Reserve all available slots to be claimed later on."""
  49. if self.is_open:
  50. return
  51. self.is_open = True # We only try once
  52. self.claim = None
  53. #
  54. # Check the make flags for "--jobserver=R,W"
  55. # Note that GNU Make has used --jobserver-fds and --jobserver-auth
  56. # so this handles all of them.
  57. #
  58. flags = os.environ.get('MAKEFLAGS', '')
  59. opts = [x for x in flags.split(" ") if x.startswith("--jobserver")]
  60. if not opts:
  61. return
  62. #
  63. # Separate out the provided file descriptors
  64. #
  65. split_opt = opts[-1].split('=', 1)
  66. if len(split_opt) != 2:
  67. warn('unparseable option:', opts[-1])
  68. return
  69. fds = split_opt[1]
  70. #
  71. # As of GNU Make 4.4, we'll be looking for a named pipe
  72. # identified as fifo:path
  73. #
  74. if fds.startswith('fifo:'):
  75. path = fds[len('fifo:'):]
  76. try:
  77. self.reader = os.open(path, os.O_RDONLY | os.O_NONBLOCK)
  78. self.writer = os.open(path, os.O_WRONLY)
  79. except (OSError, IOError):
  80. warn('unable to open jobserver pipe', path)
  81. return
  82. #
  83. # Otherwise look for integer file-descriptor numbers.
  84. #
  85. else:
  86. split_fds = fds.split(',')
  87. if len(split_fds) != 2:
  88. warn('malformed jobserver file descriptors:', fds)
  89. return
  90. try:
  91. self.reader = int(split_fds[0])
  92. self.writer = int(split_fds[1])
  93. except ValueError:
  94. warn('non-integer jobserver file-descriptors:', fds)
  95. return
  96. try:
  97. #
  98. # Open a private copy of reader to avoid setting nonblocking
  99. # on an unexpecting process with the same reader fd.
  100. #
  101. self.reader = os.open(f"/proc/self/fd/{self.reader}",
  102. os.O_RDONLY | os.O_NONBLOCK)
  103. except (IOError, OSError) as e:
  104. warn('Unable to reopen jobserver read-side pipe:', repr(e))
  105. return
  106. #
  107. # OK, we have the channel to the job server; read out as many jobserver
  108. # slots as possible.
  109. #
  110. while True:
  111. try:
  112. slot = os.read(self.reader, 8)
  113. if not slot:
  114. #
  115. # Something went wrong. Clear self.jobs to avoid writing
  116. # weirdness back to the jobserver and give up.
  117. self.jobs = b""
  118. warn("unexpected empty token from jobserver;"
  119. " possible invalid '--jobserver-auth=' setting")
  120. self.claim = None
  121. return
  122. except (OSError, IOError) as e:
  123. #
  124. # If there is nothing more to read then we are done.
  125. #
  126. if e.errno == errno.EWOULDBLOCK:
  127. break
  128. #
  129. # Anything else says that something went weird; give back
  130. # the jobs and give up.
  131. #
  132. if self.jobs:
  133. os.write(self.writer, self.jobs)
  134. self.claim = None
  135. warn('error reading from jobserver pipe', repr(e))
  136. return
  137. self.jobs += slot
  138. #
  139. # Add a bump for our caller's reserveration, since we're just going
  140. # to sit here blocked on our child.
  141. #
  142. self.claim = len(self.jobs) + 1
  143. def close(self):
  144. """Return all reserved slots to Jobserver."""
  145. if not self.is_open:
  146. return
  147. # Return all the reserved slots.
  148. if len(self.jobs):
  149. os.write(self.writer, self.jobs)
  150. self.is_open = False
  151. def __enter__(self):
  152. self.open()
  153. return self
  154. def __exit__(self, exc_type, exc_value, exc_traceback):
  155. self.close()
  156. def run(self, cmd, *args, **pwargs):
  157. """
  158. Run a command setting PARALLELISM env variable to the number of
  159. available job slots (claim) + 1, e.g. it will reserve claim slots
  160. to do the actual build work, plus one to monitor its children.
  161. """
  162. self.open() # Ensure that self.claim is set
  163. # We can only claim parallelism if there was a jobserver (i.e. a
  164. # top-level "-jN" argument) and there were no other failures. Otherwise
  165. # leave out the environment variable and let the child figure out what
  166. # is best.
  167. if self.claim:
  168. os.environ["PARALLELISM"] = str(self.claim)
  169. return subprocess.call(cmd, *args, **pwargs)