2014-01-06 03:26:32 +01:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
from __future__ import absolute_import
|
2013-12-18 15:58:58 +01:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from itertools import cycle
|
|
|
|
|
2014-03-25 14:19:12 +01:00
|
|
|
from .multiplexer import Multiplexer, STOP
|
2013-12-18 15:58:58 +01:00
|
|
|
from . import colors
|
2014-01-22 18:44:04 +01:00
|
|
|
from .utils import split_buffer
|
2013-12-18 15:58:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
class LogPrinter(object):
|
2013-12-18 20:01:53 +01:00
|
|
|
def __init__(self, containers, attach_params=None):
|
|
|
|
self.containers = containers
|
|
|
|
self.attach_params = attach_params or {}
|
|
|
|
self.generators = self._make_log_generators()
|
2013-12-18 15:58:58 +01:00
|
|
|
|
2013-12-18 20:01:53 +01:00
|
|
|
def run(self):
|
|
|
|
mux = Multiplexer(self.generators)
|
2013-12-18 15:58:58 +01:00
|
|
|
for line in mux.loop():
|
2014-04-11 01:47:26 +02:00
|
|
|
sys.stdout.write(line.encode(sys.__stdout__.encoding or 'utf-8'))
|
2013-12-18 15:58:58 +01:00
|
|
|
|
2013-12-18 20:01:53 +01:00
|
|
|
def _make_log_generators(self):
|
2013-12-18 15:58:58 +01:00
|
|
|
color_fns = cycle(colors.rainbow())
|
|
|
|
generators = []
|
|
|
|
|
2013-12-18 20:01:53 +01:00
|
|
|
for container in self.containers:
|
2013-12-18 15:58:58 +01:00
|
|
|
color_fn = color_fns.next()
|
|
|
|
generators.append(self._make_log_generator(container, color_fn))
|
|
|
|
|
|
|
|
return generators
|
|
|
|
|
|
|
|
def _make_log_generator(self, container, color_fn):
|
2013-12-20 11:52:46 +01:00
|
|
|
prefix = color_fn(container.name + " | ")
|
2014-01-21 18:58:04 +01:00
|
|
|
# Attach to container before log printer starts running
|
|
|
|
line_generator = split_buffer(self._attach(container), '\n')
|
2014-03-25 14:19:12 +01:00
|
|
|
|
|
|
|
for line in line_generator:
|
|
|
|
yield prefix + line.decode('utf-8')
|
|
|
|
|
|
|
|
exit_code = container.wait()
|
|
|
|
yield color_fn("%s exited with code %s\n" % (container.name, exit_code))
|
|
|
|
yield STOP
|
2013-12-18 20:01:53 +01:00
|
|
|
|
|
|
|
def _attach(self, container):
|
|
|
|
params = {
|
|
|
|
'stdout': True,
|
|
|
|
'stderr': True,
|
|
|
|
'stream': True,
|
|
|
|
}
|
|
|
|
params.update(self.attach_params)
|
2014-01-06 03:26:32 +01:00
|
|
|
params = dict((name, 1 if value else 0) for (name, value) in list(params.items()))
|
2014-01-13 17:23:10 +01:00
|
|
|
return container.attach(**params)
|