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