parallel.py 11 KB

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