parallel.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import operator
  4. import sys
  5. from threading import Thread
  6. from docker.errors import APIError
  7. from six.moves.queue import Empty
  8. from six.moves.queue import Queue
  9. from compose.utils import get_output_stream
  10. def perform_operation(func, arg, callback, index):
  11. try:
  12. callback((index, func(arg)))
  13. except Exception as e:
  14. callback((index, e))
  15. def parallel_execute(objects, func, index_func, msg):
  16. """For a given list of objects, call the callable passing in the first
  17. object we give it.
  18. """
  19. objects = list(objects)
  20. stream = get_output_stream(sys.stdout)
  21. writer = ParallelStreamWriter(stream, msg)
  22. for obj in objects:
  23. writer.initialize(index_func(obj))
  24. q = Queue()
  25. # TODO: limit the number of threads #1828
  26. for obj in objects:
  27. t = Thread(
  28. target=perform_operation,
  29. args=(func, obj, q.put, index_func(obj)))
  30. t.daemon = True
  31. t.start()
  32. done = 0
  33. errors = {}
  34. while done < len(objects):
  35. try:
  36. msg_index, result = q.get(timeout=1)
  37. except Empty:
  38. continue
  39. if isinstance(result, APIError):
  40. errors[msg_index] = "error", result.explanation
  41. writer.write(msg_index, 'error')
  42. elif isinstance(result, Exception):
  43. errors[msg_index] = "unexpected_exception", result
  44. else:
  45. writer.write(msg_index, 'done')
  46. done += 1
  47. if not errors:
  48. return
  49. stream.write("\n")
  50. for msg_index, (result, error) in errors.items():
  51. stream.write("ERROR: for {} {} \n".format(msg_index, error))
  52. if result == 'unexpected_exception':
  53. raise error
  54. class ParallelStreamWriter(object):
  55. """Write out messages for operations happening in parallel.
  56. Each operation has it's own line, and ANSI code characters are used
  57. to jump to the correct line, and write over the line.
  58. """
  59. def __init__(self, stream, msg):
  60. self.stream = stream
  61. self.msg = msg
  62. self.lines = []
  63. def initialize(self, obj_index):
  64. self.lines.append(obj_index)
  65. self.stream.write("{} {} ... \r\n".format(self.msg, obj_index))
  66. self.stream.flush()
  67. def write(self, obj_index, status):
  68. position = self.lines.index(obj_index)
  69. diff = len(self.lines) - position
  70. # move up
  71. self.stream.write("%c[%dA" % (27, diff))
  72. # erase
  73. self.stream.write("%c[2K\r" % 27)
  74. self.stream.write("{} {} ... {}\r".format(self.msg, obj_index, status))
  75. # move back down
  76. self.stream.write("%c[%dB" % (27, diff))
  77. self.stream.flush()
  78. def parallel_operation(containers, operation, options, message):
  79. parallel_execute(
  80. containers,
  81. operator.methodcaller(operation, **options),
  82. operator.attrgetter('name'),
  83. message)
  84. def parallel_remove(containers, options):
  85. stopped_containers = [c for c in containers if not c.is_running]
  86. parallel_operation(stopped_containers, 'remove', options, 'Removing')
  87. def parallel_stop(containers, options):
  88. parallel_operation(containers, 'stop', options, 'Stopping')
  89. def parallel_start(containers, options):
  90. parallel_operation(containers, 'start', options, 'Starting')
  91. def parallel_pause(containers, options):
  92. parallel_operation(containers, 'pause', options, 'Pausing')
  93. def parallel_unpause(containers, options):
  94. parallel_operation(containers, 'unpause', options, 'Unpausing')
  95. def parallel_kill(containers, options):
  96. parallel_operation(containers, 'kill', options, 'Killing')
  97. def parallel_restart(containers, options):
  98. parallel_operation(containers, 'restart', options, 'Restarting')