parallel.py 9.5 KB

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