1
0

log_printer.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. # There are no running containers left to tail, so exit
  70. return
  71. # We got an empty line because of a timeout, but there are still
  72. # active containers to tail, so continue
  73. continue
  74. self.output.write(line)
  75. self.output.flush()
  76. def remove_stopped_threads(thread_map):
  77. for container_id, tailer_thread in list(thread_map.items()):
  78. if not tailer_thread.is_alive():
  79. thread_map.pop(container_id, None)
  80. def build_thread(container, presenter, queue, log_args):
  81. tailer = Thread(
  82. target=tail_container_logs,
  83. args=(container, presenter, queue, log_args))
  84. tailer.daemon = True
  85. tailer.start()
  86. return tailer
  87. def build_thread_map(initial_containers, presenters, thread_args):
  88. return {
  89. container.id: build_thread(container, next(presenters), *thread_args)
  90. for container in initial_containers
  91. }
  92. class QueueItem(namedtuple('_QueueItem', 'item is_stop exc')):
  93. @classmethod
  94. def new(cls, item):
  95. return cls(item, None, None)
  96. @classmethod
  97. def exception(cls, exc):
  98. return cls(None, None, exc)
  99. @classmethod
  100. def stop(cls):
  101. return cls(None, True, None)
  102. def tail_container_logs(container, presenter, queue, log_args):
  103. generator = get_log_generator(container)
  104. try:
  105. for item in generator(container, log_args):
  106. queue.put(QueueItem.new(presenter.present(container, item)))
  107. except Exception as e:
  108. queue.put(QueueItem.exception(e))
  109. return
  110. if log_args.get('follow'):
  111. queue.put(QueueItem.new(presenter.color_func(wait_on_exit(container))))
  112. queue.put(QueueItem.stop())
  113. def get_log_generator(container):
  114. if container.has_api_logs:
  115. return build_log_generator
  116. return build_no_log_generator
  117. def build_no_log_generator(container, log_args):
  118. """Return a generator that prints a warning about logs and waits for
  119. container to exit.
  120. """
  121. yield "WARNING: no logs are available with the '{}' log driver\n".format(
  122. container.log_driver)
  123. def build_log_generator(container, log_args):
  124. # if the container doesn't have a log_stream we need to attach to container
  125. # before log printer starts running
  126. if container.log_stream is None:
  127. stream = container.logs(stdout=True, stderr=True, stream=True, **log_args)
  128. else:
  129. stream = container.log_stream
  130. return split_buffer(stream)
  131. def wait_on_exit(container):
  132. exit_code = container.wait()
  133. return "%s exited with code %s\n" % (container.name, exit_code)
  134. def start_producer_thread(thread_args):
  135. producer = Thread(target=watch_events, args=thread_args)
  136. producer.daemon = True
  137. producer.start()
  138. def watch_events(thread_map, event_stream, presenters, thread_args):
  139. for event in event_stream:
  140. if event['action'] == 'stop':
  141. thread_map.pop(event['id'], None)
  142. if event['action'] != 'start':
  143. continue
  144. if event['id'] in thread_map:
  145. if thread_map[event['id']].is_alive():
  146. continue
  147. # Container was stopped and started, we need a new thread
  148. thread_map.pop(event['id'], None)
  149. thread_map[event['id']] = build_thread(
  150. event['container'],
  151. next(presenters),
  152. *thread_args)
  153. def consume_queue(queue, cascade_stop):
  154. """Consume the queue by reading lines off of it and yielding them."""
  155. while True:
  156. try:
  157. item = queue.get(timeout=0.1)
  158. except Empty:
  159. yield None
  160. continue
  161. # See https://github.com/docker/compose/issues/189
  162. except thread.error:
  163. raise ShutdownException()
  164. if item.exc:
  165. raise item.exc
  166. if item.is_stop:
  167. if cascade_stop:
  168. raise StopIteration
  169. else:
  170. continue
  171. yield item.item