parallel.py 9.5 KB

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