2013-12-18 15:58:58 +01:00
|
|
|
import sys
|
|
|
|
|
|
|
|
from itertools import cycle
|
|
|
|
|
|
|
|
from .multiplexer import Multiplexer
|
|
|
|
from . import colors
|
|
|
|
|
|
|
|
|
|
|
|
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():
|
|
|
|
sys.stdout.write(line)
|
|
|
|
|
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-18 20:01:53 +01:00
|
|
|
format = lambda line: color_fn(container.name + " | ") + line
|
|
|
|
return (format(line) for line in self._readlines(self._attach(container)))
|
|
|
|
|
|
|
|
def _attach(self, container):
|
|
|
|
params = {
|
|
|
|
'stdin': False,
|
|
|
|
'stdout': True,
|
|
|
|
'stderr': True,
|
|
|
|
'logs': False,
|
|
|
|
'stream': True,
|
|
|
|
}
|
|
|
|
params.update(self.attach_params)
|
|
|
|
params = dict((name, 1 if value else 0) for (name, value) in params.items())
|
|
|
|
return container.attach_socket(params=params)
|
|
|
|
|
|
|
|
def _readlines(self, socket):
|
2013-12-18 15:58:58 +01:00
|
|
|
for line in iter(socket.makefile().readline, b''):
|
|
|
|
if not line.endswith('\n'):
|
|
|
|
line += '\n'
|
|
|
|
|
|
|
|
yield line
|
|
|
|
|
|
|
|
socket.close()
|