1
0

parallel.py 7.8 KB

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