parallel.py 11 KB

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