parallel.py 8.8 KB

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