1
0

parallel.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import logging
  4. import operator
  5. import sys
  6. from threading import Semaphore
  7. from threading import Thread
  8. from docker.errors import APIError
  9. from docker.errors import ImageNotFound
  10. from six.moves import _thread as thread
  11. from six.moves.queue import Empty
  12. from six.moves.queue import Queue
  13. from compose.cli.colors import green
  14. from compose.cli.colors import red
  15. from compose.cli.signals import ShutdownException
  16. from compose.const import PARALLEL_LIMIT
  17. from compose.errors import HealthCheckFailed
  18. from compose.errors import NoHealthCheckConfigured
  19. from compose.errors import OperationFailedError
  20. from compose.utils import get_output_stream
  21. log = logging.getLogger(__name__)
  22. STOP = object()
  23. class GlobalLimit(object):
  24. """Simple class to hold a global semaphore limiter for a project. This class
  25. should be treated as a singleton that is instantiated when the project is.
  26. """
  27. global_limiter = Semaphore(PARALLEL_LIMIT)
  28. @classmethod
  29. def set_global_limit(cls, value):
  30. if value is None:
  31. value = PARALLEL_LIMIT
  32. cls.global_limiter = Semaphore(value)
  33. def parallel_execute(objects, func, get_name, msg, get_deps=None, limit=None, parent_objects=None):
  34. """Runs func on objects in parallel while ensuring that func is
  35. ran on object only after it is ran on all its dependencies.
  36. get_deps called on object must return a collection with its dependencies.
  37. get_name called on object must return its name.
  38. """
  39. objects = list(objects)
  40. stream = get_output_stream(sys.stderr)
  41. writer = ParallelStreamWriter(stream, msg)
  42. display_objects = list(parent_objects) if parent_objects else objects
  43. for obj in display_objects:
  44. writer.add_object(get_name(obj))
  45. # write data in a second loop to consider all objects for width alignment
  46. # and avoid duplicates when parent_objects exists
  47. for obj in objects:
  48. writer.write_initial(get_name(obj))
  49. events = parallel_execute_iter(objects, func, get_deps, limit)
  50. errors = {}
  51. results = []
  52. error_to_reraise = None
  53. for obj, result, exception in events:
  54. if exception is None:
  55. writer.write(get_name(obj), 'done', green)
  56. results.append(result)
  57. elif isinstance(exception, ImageNotFound):
  58. # This is to bubble up ImageNotFound exceptions to the client so we
  59. # can prompt the user if they want to rebuild.
  60. errors[get_name(obj)] = exception.explanation
  61. writer.write(get_name(obj), 'error', red)
  62. error_to_reraise = exception
  63. elif isinstance(exception, APIError):
  64. errors[get_name(obj)] = exception.explanation
  65. writer.write(get_name(obj), 'error', red)
  66. elif isinstance(exception, (OperationFailedError, HealthCheckFailed, NoHealthCheckConfigured)):
  67. errors[get_name(obj)] = exception.msg
  68. writer.write(get_name(obj), 'error', red)
  69. elif isinstance(exception, UpstreamError):
  70. writer.write(get_name(obj), 'error', red)
  71. else:
  72. errors[get_name(obj)] = exception
  73. error_to_reraise = exception
  74. for obj_name, error in errors.items():
  75. stream.write("\nERROR: for {} {}\n".format(obj_name, error))
  76. if error_to_reraise:
  77. raise error_to_reraise
  78. return results, errors
  79. def _no_deps(x):
  80. return []
  81. class State(object):
  82. """
  83. Holds the state of a partially-complete parallel operation.
  84. state.started: objects being processed
  85. state.finished: objects which have been processed
  86. state.failed: objects which either failed or whose dependencies failed
  87. """
  88. def __init__(self, objects):
  89. self.objects = objects
  90. self.started = set()
  91. self.finished = set()
  92. self.failed = set()
  93. def is_done(self):
  94. return len(self.finished) + len(self.failed) >= len(self.objects)
  95. def pending(self):
  96. return set(self.objects) - self.started - self.finished - self.failed
  97. class NoLimit(object):
  98. def __enter__(self):
  99. pass
  100. def __exit__(self, *ex):
  101. pass
  102. def parallel_execute_iter(objects, func, get_deps, limit):
  103. """
  104. Runs func on objects in parallel while ensuring that func is
  105. ran on object only after it is ran on all its dependencies.
  106. Returns an iterator of tuples which look like:
  107. # if func returned normally when run on object
  108. (object, result, None)
  109. # if func raised an exception when run on object
  110. (object, None, exception)
  111. # if func raised an exception when run on one of object's dependencies
  112. (object, None, UpstreamError())
  113. """
  114. if get_deps is None:
  115. get_deps = _no_deps
  116. if limit is None:
  117. limiter = NoLimit()
  118. else:
  119. limiter = Semaphore(limit)
  120. results = Queue()
  121. state = State(objects)
  122. while True:
  123. feed_queue(objects, func, get_deps, results, state, limiter)
  124. try:
  125. event = results.get(timeout=0.1)
  126. except Empty:
  127. continue
  128. # See https://github.com/docker/compose/issues/189
  129. except thread.error:
  130. raise ShutdownException()
  131. if event is STOP:
  132. break
  133. obj, _, exception = event
  134. if exception is None:
  135. log.debug('Finished processing: {}'.format(obj))
  136. state.finished.add(obj)
  137. else:
  138. log.debug('Failed: {}'.format(obj))
  139. state.failed.add(obj)
  140. yield event
  141. def producer(obj, func, results, limiter):
  142. """
  143. The entry point for a producer thread which runs func on a single object.
  144. Places a tuple on the results queue once func has either returned or raised.
  145. """
  146. with limiter, GlobalLimit.global_limiter:
  147. try:
  148. result = func(obj)
  149. results.put((obj, result, None))
  150. except Exception as e:
  151. results.put((obj, None, e))
  152. def feed_queue(objects, func, get_deps, results, state, limiter):
  153. """
  154. Starts producer threads for any objects which are ready to be processed
  155. (i.e. they have no dependencies which haven't been successfully processed).
  156. Shortcuts any objects whose dependencies have failed and places an
  157. (object, None, UpstreamError()) tuple on the results queue.
  158. """
  159. pending = state.pending()
  160. log.debug('Pending: {}'.format(pending))
  161. for obj in pending:
  162. deps = get_deps(obj)
  163. try:
  164. if any(dep[0] in state.failed for dep in deps):
  165. log.debug('{} has upstream errors - not processing'.format(obj))
  166. results.put((obj, None, UpstreamError()))
  167. state.failed.add(obj)
  168. elif all(
  169. dep not in objects or (
  170. dep in state.finished and (not ready_check or ready_check(dep))
  171. ) for dep, ready_check in deps
  172. ):
  173. log.debug('Starting producer thread for {}'.format(obj))
  174. t = Thread(target=producer, args=(obj, func, results, limiter))
  175. t.daemon = True
  176. t.start()
  177. state.started.add(obj)
  178. except (HealthCheckFailed, NoHealthCheckConfigured) as e:
  179. log.debug(
  180. 'Healthcheck for service(s) upstream of {} failed - '
  181. 'not processing'.format(obj)
  182. )
  183. results.put((obj, None, e))
  184. if state.is_done():
  185. results.put(STOP)
  186. class UpstreamError(Exception):
  187. pass
  188. class ParallelStreamWriter(object):
  189. """Write out messages for operations happening in parallel.
  190. Each operation has its own line, and ANSI code characters are used
  191. to jump to the correct line, and write over the line.
  192. """
  193. noansi = False
  194. @classmethod
  195. def set_noansi(cls, value=True):
  196. cls.noansi = value
  197. def __init__(self, stream, msg):
  198. self.stream = stream
  199. self.msg = msg
  200. self.lines = []
  201. self.width = 0
  202. def add_object(self, obj_index):
  203. self.lines.append(obj_index)
  204. self.width = max(self.width, len(obj_index))
  205. def write_initial(self, obj_index):
  206. if self.msg is None:
  207. return
  208. self.stream.write("{} {:<{width}} ... \r\n".format(
  209. self.msg, self.lines[self.lines.index(obj_index)], width=self.width))
  210. self.stream.flush()
  211. def _write_ansi(self, obj_index, status):
  212. position = self.lines.index(obj_index)
  213. diff = len(self.lines) - position
  214. # move up
  215. self.stream.write("%c[%dA" % (27, diff))
  216. # erase
  217. self.stream.write("%c[2K\r" % 27)
  218. self.stream.write("{} {:<{width}} ... {}\r".format(self.msg, obj_index,
  219. status, width=self.width))
  220. # move back down
  221. self.stream.write("%c[%dB" % (27, diff))
  222. self.stream.flush()
  223. def _write_noansi(self, obj_index, status):
  224. self.stream.write("{} {:<{width}} ... {}\r\n".format(self.msg, obj_index,
  225. status, width=self.width))
  226. self.stream.flush()
  227. def write(self, obj_index, status, color_func):
  228. if self.msg is None:
  229. return
  230. if self.noansi:
  231. self._write_noansi(obj_index, status)
  232. else:
  233. self._write_ansi(obj_index, color_func(status))
  234. def parallel_operation(containers, operation, options, message):
  235. parallel_execute(
  236. containers,
  237. operator.methodcaller(operation, **options),
  238. operator.attrgetter('name'),
  239. message,
  240. )
  241. def parallel_remove(containers, options):
  242. stopped_containers = [c for c in containers if not c.is_running]
  243. parallel_operation(stopped_containers, 'remove', options, 'Removing')
  244. def parallel_pause(containers, options):
  245. parallel_operation(containers, 'pause', options, 'Pausing')
  246. def parallel_unpause(containers, options):
  247. parallel_operation(containers, 'unpause', options, 'Unpausing')
  248. def parallel_kill(containers, options):
  249. parallel_operation(containers, 'kill', options, 'Killing')