parallel.py 10.0 KB

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