parallel.py 7.7 KB

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