baseimage-tutorial-framework/lib/tfw/components/terminado_event_handler.py

42 lines
1.5 KiB
Python

from tfw.components.terminado_mini_server import TerminadoMiniServer
from tfw.components.history_monitor import HistoryMonitor
from tfw.event_handler_base import TriggerlessEventHandler
from tfw.config import tfwenv
from tfw.config.logs import logging
log = logging.getLogger(__name__)
class TerminadoEventHandler(TriggerlessEventHandler):
def __init__(self, key):
super().__init__(key)
self.working_directory = tfwenv.TERMINADO_DIR
self._historymonitor = HistoryMonitor(tfwenv.HISTFILE)
self.terminado_server = TerminadoMiniServer('/terminal', tfwenv.TERMINADO_PORT, tfwenv.TERMINADO_WD, ['bash'])
self.commands = {'write': self.write,
'read': self.read}
self._historymonitor.watch()
self.terminado_server.listen()
@property
def historymonitor(self):
return self._historymonitor
def handle_event(self, key, message):
log.debug('TerminadoEventHandler received event: {}'.format(message))
try:
message['data'] = self.commands[message['data']['command']](message['data'])
return message
except KeyError:
log.error('IGNORING MESSAGE: Invalid message received: {}'.format(message))
def write(self, data):
self.terminado_server.pty.write(data['shellcmd'])
def read(self, data):
data['count'] = int(data.get('count', 1))
data['history'] = self.historymonitor.history[-data['count']:]
return data
def cleanup(self):
self.historymonitor.stop()