parallel.py 8.0 KB

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