log_printer.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. from __future__ import absolute_import
  2. from __future__ import unicode_literals
  3. import sys
  4. from collections import namedtuple
  5. from itertools import cycle
  6. from threading import Thread
  7. from six.moves import _thread as thread
  8. from six.moves.queue import Empty
  9. from six.moves.queue import Queue
  10. from . import colors
  11. from compose import utils
  12. from compose.cli.signals import ShutdownException
  13. from compose.utils import split_buffer
  14. class LogPresenter(object):
  15. def __init__(self, prefix_width, color_func):
  16. self.prefix_width = prefix_width
  17. self.color_func = color_func
  18. def present(self, container, line):
  19. prefix = container.name_without_project.ljust(self.prefix_width)
  20. return '{prefix} {line}'.format(
  21. prefix=self.color_func(prefix + ' |'),
  22. line=line)
  23. def build_log_presenters(service_names, monochrome):
  24. """Return an iterable of functions.
  25. Each function can be used to format the logs output of a container.
  26. """
  27. prefix_width = max_name_width(service_names)
  28. def no_color(text):
  29. return text
  30. for color_func in cycle([no_color] if monochrome else colors.rainbow()):
  31. yield LogPresenter(prefix_width, color_func)
  32. def max_name_width(service_names, max_index_width=3):
  33. """Calculate the maximum width of container names so we can make the log
  34. prefixes line up like so:
  35. db_1 | Listening
  36. web_1 | Listening
  37. """
  38. return max(len(name) for name in service_names) + max_index_width
  39. class LogPrinter(object):
  40. """Print logs from many containers to a single output stream."""
  41. def __init__(self,
  42. containers,
  43. presenters,
  44. event_stream,
  45. output=sys.stdout,
  46. cascade_stop=False,
  47. log_args=None):
  48. self.containers = containers
  49. self.presenters = presenters
  50. self.event_stream = event_stream
  51. self.output = utils.get_output_stream(output)
  52. self.cascade_stop = cascade_stop
  53. self.log_args = log_args or {}
  54. def run(self):
  55. if not self.containers:
  56. return
  57. queue = Queue()
  58. thread_args = queue, self.log_args
  59. thread_map = build_thread_map(self.containers, self.presenters, thread_args)
  60. start_producer_thread((
  61. thread_map,
  62. self.event_stream,
  63. self.presenters,
  64. thread_args))
  65. for line in consume_queue(queue, self.cascade_stop):
  66. remove_stopped_threads(thread_map)
  67. if not line:
  68. if not thread_map:
  69. return
  70. continue
  71. self.output.write(line)
  72. self.output.flush()
  73. def remove_stopped_threads(thread_map):
  74. for container_id, tailer_thread in list(thread_map.items()):
  75. if not tailer_thread.is_alive():
  76. thread_map.pop(container_id, None)
  77. def build_thread(container, presenter, queue, log_args):
  78. tailer = Thread(
  79. target=tail_container_logs,
  80. args=(container, presenter, queue, log_args))
  81. tailer.daemon = True
  82. tailer.start()
  83. return tailer
  84. def build_thread_map(initial_containers, presenters, thread_args):
  85. return {
  86. container.id: build_thread(container, presenters.next(), *thread_args)
  87. for container in initial_containers
  88. }
  89. class QueueItem(namedtuple('_QueueItem', 'item is_stop exc')):
  90. @classmethod
  91. def new(cls, item):
  92. return cls(item, None, None)
  93. @classmethod
  94. def exception(cls, exc):
  95. return cls(None, None, exc)
  96. @classmethod
  97. def stop(cls):
  98. return cls(None, True, None)
  99. def tail_container_logs(container, presenter, queue, log_args):
  100. generator = get_log_generator(container)
  101. try:
  102. for item in generator(container, log_args):
  103. queue.put(QueueItem.new(presenter.present(container, item)))
  104. except Exception as e:
  105. queue.put(QueueItem.exception(e))
  106. return
  107. if log_args.get('follow'):
  108. queue.put(QueueItem.new(presenter.color_func(wait_on_exit(container))))
  109. queue.put(QueueItem.stop())
  110. def get_log_generator(container):
  111. if container.has_api_logs:
  112. return build_log_generator
  113. return build_no_log_generator
  114. def build_no_log_generator(container, log_args):
  115. """Return a generator that prints a warning about logs and waits for
  116. container to exit.
  117. """
  118. yield "WARNING: no logs are available with the '{}' log driver\n".format(
  119. container.log_driver)
  120. def build_log_generator(container, log_args):
  121. # if the container doesn't have a log_stream we need to attach to container
  122. # before log printer starts running
  123. if container.log_stream is None:
  124. stream = container.logs(stdout=True, stderr=True, stream=True, **log_args)
  125. else:
  126. stream = container.log_stream
  127. return split_buffer(stream)
  128. def wait_on_exit(container):
  129. exit_code = container.wait()
  130. return "%s exited with code %s\n" % (container.name, exit_code)
  131. def start_producer_thread(thread_args):
  132. producer = Thread(target=watch_events, args=thread_args)
  133. producer.daemon = True
  134. producer.start()
  135. def watch_events(thread_map, event_stream, presenters, thread_args):
  136. for event in event_stream:
  137. if event['action'] != 'start':
  138. continue
  139. if event['id'] in thread_map:
  140. if thread_map[event['id']].is_alive():
  141. continue
  142. # Container was stopped and started, we need a new thread
  143. thread_map.pop(event['id'], None)
  144. thread_map[event['id']] = build_thread(
  145. event['container'],
  146. presenters.next(),
  147. *thread_args)
  148. def consume_queue(queue, cascade_stop):
  149. """Consume the queue by reading lines off of it and yielding them."""
  150. while True:
  151. try:
  152. item = queue.get(timeout=0.1)
  153. except Empty:
  154. yield None
  155. continue
  156. # See https://github.com/docker/compose/issues/189
  157. except thread.error:
  158. raise ShutdownException()
  159. if item.exc:
  160. raise item.exc
  161. if item.is_stop:
  162. if cascade_stop:
  163. raise StopIteration
  164. else:
  165. continue
  166. yield item.item