baseimage-tutorial-framework/tfw/components/terminal/terminal_handler.py

86 lines
2.6 KiB
Python
Raw Normal View History

2019-06-10 13:32:45 +00:00
import logging
from .history_monitor import BashMonitor
from .terminado_mini_server import TerminadoMiniServer
LOG = logging.getLogger(__name__)
class TerminalHandler:
keys = ['shell']
2018-04-18 17:44:26 +00:00
"""
Event handler responsible for managing terminal sessions for frontend xterm
sessions to connect to. You need to instanciate this in order for frontend
terminals to work.
2018-06-01 14:20:20 +00:00
This EventHandler accepts messages that have a data['command'] key specifying
2018-04-18 17:44:26 +00:00
a command to be executed.
2018-06-01 14:20:20 +00:00
The API of each command is documented in their respective handler.
2018-04-18 17:44:26 +00:00
"""
2019-07-23 13:32:50 +00:00
def __init__(self, *, port, user, workind_directory, histfile):
2018-04-18 17:44:26 +00:00
"""
:param key: key this EventHandler listens to
:param monitor: tfw.components.HistoryMonitor instance to read command history from
"""
self.server_connector = None
2019-07-23 13:32:50 +00:00
self._histfile = histfile
self._historymonitor = None
2019-07-23 13:32:50 +00:00
bash_as_user_cmd = ['sudo', '-u', user, 'bash']
2018-06-01 15:19:58 +00:00
self.terminado_server = TerminadoMiniServer(
'/terminal',
2019-07-23 13:32:50 +00:00
port,
workind_directory,
bash_as_user_cmd
2018-06-01 15:19:58 +00:00
)
self.commands = {
'write': self.write,
'read': self.read
}
self.terminado_server.listen()
def start(self):
2019-07-23 13:32:50 +00:00
self._historymonitor = BashMonitor(self.server_connector, self._histfile)
self._historymonitor.start()
@property
def historymonitor(self):
return self._historymonitor
def handle_event(self, message, _):
try:
data = message['data']
message['data'] = self.commands[data['command']](data)
except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
2018-03-03 13:14:44 +00:00
def write(self, data):
2018-04-18 17:44:26 +00:00
"""
Writes a string to the terminal session (on the pty level).
Useful for pre-typing and executing commands for the user.
2018-06-01 14:20:20 +00:00
:param data: TFW message data containing 'value'
(command to be written to the pty)
2018-04-18 17:44:26 +00:00
"""
2018-05-31 12:08:29 +00:00
self.terminado_server.pty.write(data['value'])
return data
2018-03-03 21:46:14 +00:00
def read(self, data):
2018-04-18 17:44:26 +00:00
"""
Reads the history of commands executed.
2018-06-01 14:20:20 +00:00
:param data: TFW message data containing 'count'
(the number of history elements to return)
:return dict: message with list of commands in data['history']
2018-04-18 17:44:26 +00:00
"""
data['count'] = int(data.get('count', 1))
if self.historymonitor:
data['history'] = self.historymonitor.history[-data['count']:]
2018-03-03 21:46:14 +00:00
return data
def cleanup(self):
2019-05-31 11:10:33 +00:00
self.terminado_server.stop()
self.historymonitor.stop()