parallel.py 7.1 KB

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