parallel.py 8.0 KB

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