parallel.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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 Thread
  7. from docker.errors import APIError
  8. from six.moves import _thread as thread
  9. from six.moves.queue import Empty
  10. from six.moves.queue import Queue
  11. from compose.cli.signals import ShutdownException
  12. from compose.utils import get_output_stream
  13. log = logging.getLogger(__name__)
  14. def parallel_execute(objects, func, get_name, msg, get_deps=None):
  15. """Runs func on objects in parallel while ensuring that func is
  16. ran on object only after it is ran on all its dependencies.
  17. get_deps called on object must return a collection with its dependencies.
  18. get_name called on object must return its name.
  19. """
  20. objects = list(objects)
  21. stream = get_output_stream(sys.stderr)
  22. writer = ParallelStreamWriter(stream, msg)
  23. for obj in objects:
  24. writer.initialize(get_name(obj))
  25. events = parallel_execute_stream(objects, func, get_deps)
  26. errors = {}
  27. results = []
  28. error_to_reraise = None
  29. for obj, result, exception in events:
  30. if exception is None:
  31. writer.write(get_name(obj), 'done')
  32. results.append(result)
  33. elif isinstance(exception, APIError):
  34. errors[get_name(obj)] = exception.explanation
  35. writer.write(get_name(obj), 'error')
  36. elif isinstance(exception, UpstreamError):
  37. writer.write(get_name(obj), 'error')
  38. else:
  39. errors[get_name(obj)] = exception
  40. error_to_reraise = exception
  41. for obj_name, error in errors.items():
  42. stream.write("\nERROR: for {} {}\n".format(obj_name, error))
  43. if error_to_reraise:
  44. raise error_to_reraise
  45. return results
  46. def _no_deps(x):
  47. return []
  48. class State(object):
  49. def __init__(self, objects):
  50. self.objects = objects
  51. self.started = set() # objects being processed
  52. self.finished = set() # objects which have been processed
  53. self.failed = set() # objects which either failed or whose dependencies failed
  54. def is_done(self):
  55. return len(self.finished) + len(self.failed) >= len(self.objects)
  56. def pending(self):
  57. return set(self.objects) - self.started - self.finished - self.failed
  58. def parallel_execute_stream(objects, func, get_deps):
  59. if get_deps is None:
  60. get_deps = _no_deps
  61. results = Queue()
  62. state = State(objects)
  63. while not state.is_done():
  64. feed_queue(objects, func, get_deps, results, state)
  65. try:
  66. event = results.get(timeout=0.1)
  67. except Empty:
  68. continue
  69. # See https://github.com/docker/compose/issues/189
  70. except thread.error:
  71. raise ShutdownException()
  72. obj, _, exception = event
  73. if exception is None:
  74. log.debug('Finished processing: {}'.format(obj))
  75. state.finished.add(obj)
  76. else:
  77. log.debug('Failed: {}'.format(obj))
  78. state.failed.add(obj)
  79. yield event
  80. def queue_producer(obj, func, results):
  81. try:
  82. result = func(obj)
  83. results.put((obj, result, None))
  84. except Exception as e:
  85. results.put((obj, None, e))
  86. def feed_queue(objects, func, get_deps, results, state):
  87. pending = state.pending()
  88. log.debug('Pending: {}'.format(pending))
  89. for obj in pending:
  90. deps = get_deps(obj)
  91. if any(dep in state.failed for dep in deps):
  92. log.debug('{} has upstream errors - not processing'.format(obj))
  93. results.put((obj, None, UpstreamError()))
  94. state.failed.add(obj)
  95. elif all(
  96. dep not in objects or dep in state.finished
  97. for dep in deps
  98. ):
  99. log.debug('Starting producer thread for {}'.format(obj))
  100. t = Thread(target=queue_producer, args=(obj, func, results))
  101. t.daemon = True
  102. t.start()
  103. state.started.add(obj)
  104. class UpstreamError(Exception):
  105. pass
  106. class ParallelStreamWriter(object):
  107. """Write out messages for operations happening in parallel.
  108. Each operation has it's own line, and ANSI code characters are used
  109. to jump to the correct line, and write over the line.
  110. """
  111. def __init__(self, stream, msg):
  112. self.stream = stream
  113. self.msg = msg
  114. self.lines = []
  115. def initialize(self, obj_index):
  116. if self.msg is None:
  117. return
  118. self.lines.append(obj_index)
  119. self.stream.write("{} {} ... \r\n".format(self.msg, obj_index))
  120. self.stream.flush()
  121. def write(self, obj_index, status):
  122. if self.msg is None:
  123. return
  124. position = self.lines.index(obj_index)
  125. diff = len(self.lines) - position
  126. # move up
  127. self.stream.write("%c[%dA" % (27, diff))
  128. # erase
  129. self.stream.write("%c[2K\r" % 27)
  130. self.stream.write("{} {} ... {}\r".format(self.msg, obj_index, status))
  131. # move back down
  132. self.stream.write("%c[%dB" % (27, diff))
  133. self.stream.flush()
  134. def parallel_operation(containers, operation, options, message):
  135. parallel_execute(
  136. containers,
  137. operator.methodcaller(operation, **options),
  138. operator.attrgetter('name'),
  139. message)
  140. def parallel_remove(containers, options):
  141. stopped_containers = [c for c in containers if not c.is_running]
  142. parallel_operation(stopped_containers, 'remove', options, 'Removing')
  143. def parallel_start(containers, options):
  144. parallel_operation(containers, 'start', options, 'Starting')
  145. def parallel_pause(containers, options):
  146. parallel_operation(containers, 'pause', options, 'Pausing')
  147. def parallel_unpause(containers, options):
  148. parallel_operation(containers, 'unpause', options, 'Unpausing')
  149. def parallel_kill(containers, options):
  150. parallel_operation(containers, 'kill', options, 'Killing')
  151. def parallel_restart(containers, options):
  152. parallel_operation(containers, 'restart', options, 'Restarting')