1
0
mirror of https://github.com/avatao-content/test-tutorial-framework synced 2024-11-15 06:37:18 +00:00
test-tutorial-framework/solvable/src/event_handler_main.py

181 lines
5.8 KiB
Python
Raw Normal View History

2019-06-10 13:35:09 +00:00
import logging
2019-06-28 15:36:03 +00:00
from sys import stderr
from ast import literal_eval
from functools import partial
from signal import signal, SIGTERM, SIGINT
from tornado.ioloop import IOLoop
2018-07-26 12:00:24 +00:00
from tfw.fsm import YamlFSM
2019-06-28 13:12:27 +00:00
from tfw.builtins import EventHandler, FSMAwareEventHandler, TFWServerUplinkConnector
from tfw.builtins import IdeEventHandler, TerminalEventHandler, FrontendEventHandler
from tfw.builtins import LogMonitoringEventHandler, ProcessManagingEventHandler
2019-06-27 12:38:36 +00:00
from tfw.builtins import DirectorySnapshottingEventHandler, FSMManagingEventHandler, MessageSender
from tfw.components import TerminalCommands
from tfw.config import TFWENV
2019-06-28 15:36:03 +00:00
from tfw.logging import Log, Logger, LogFormatter, VerboseLogFormatter
2019-07-01 12:54:47 +00:00
from tao.config import TAOENV
LOG = logging.getLogger(__name__)
2019-06-28 13:12:27 +00:00
class TerminalCallbackEventHandler(EventHandler):
"""
Logs commands executed in terminal to messages and invokes an
additional callback function to handle special commands.
!! Please remove from production code. !!
"""
def __init__(self, key, callback):
self.callback = callback
super().__init__(key)
def handle_event(self, message):
command = message['value']
self.cenator(command)
self.callback(command)
@staticmethod
def cenator(command):
LOG.debug('User executed command: "%s"', command)
MessageSender().send('JOHN CENA', f'You\'ve executed "{command}"')
class TestCommands(TerminalCommands):
"""
Some example commands useful for debugging.
!! Please remove from production code !! and inherit your own
class from TerminalCommands if you need to define custom
commands in your challenge.
"""
2018-04-18 18:45:17 +00:00
# pylint: disable=unused-argument, attribute-defined-outside-init, no-self-use
def command_sendmessage(self, *args):
"""
Insert TFW message template as first argument if executed without args.
Evaluate first argumen as a dict and send it to the frontend.
This is useful for playing around with frontend APIs.
"""
if not args:
message_template = """'{"key": "", "data": {"command": ""}}'"""
2019-06-04 11:59:32 +00:00
TFWServerUplinkConnector().send_message({
'key': 'shell',
'data': {
'command': 'write',
2018-05-31 12:20:08 +00:00
'value': f'sendmessage {message_template}'
}
})
else:
2019-06-04 11:59:32 +00:00
TFWServerUplinkConnector().send_message(literal_eval(args[0]))
2018-04-19 14:23:46 +00:00
def command_seppuku_tfw(self, *args):
"""
Restart tfw_server.py and event_handler_main.py.
This can speed up development when combined with mounting
volumes from host to container.
"""
seppuku = (
'nohup sh -c "supervisorctl restart tfwserver event_handler_main" &> /dev/null & '
'clear && echo "Committed seppuku! :)" && sleep infinity'
)
2019-06-04 11:59:32 +00:00
uplink = TFWServerUplinkConnector()
uplink.send_message({
'key': 'shell',
'data': {
'command': 'write',
2018-05-31 12:20:08 +00:00
'value': f'{seppuku}\n'
}
})
uplink.send_message({
'key': 'dashboard',
'data': {
2018-05-31 12:20:08 +00:00
'command': 'reloadFrontend'
}
})
class MessageFSMStepsEventHandler(FSMAwareEventHandler):
"""
This example EventHandler is capable of detecting FSM state.
!! Please remove from production code !!
"""
def handle_event(self, message):
pass
2018-07-24 15:17:14 +00:00
def handle_fsm_step(self, **kwargs):
"""
When the FSM steps this method is invoked.
2018-07-24 15:17:14 +00:00
Receives a 'data' field from an fsm_update message as kwargs.
"""
MessageSender().send(
'FSM info',
2018-07-24 15:17:14 +00:00
f'FSM has stepped from state "{kwargs["last_event"]["from_state"]}" '
f'to state "{kwargs["current_state"]}" in response to trigger "{kwargs["last_event"]["trigger"]}"'
)
def main():
# pylint: disable=unused-variable
2019-06-28 15:36:03 +00:00
Logger([
Log(stderr, LogFormatter(20)),
Log(TFWENV.LOGFILE, VerboseLogFormatter())
]).start()
2019-06-18 16:51:05 +00:00
# TFW component EventHandlers (builtins, required for their respective functionalities)
fsm = FSMManagingEventHandler( # TFW FSM
key='fsm',
2018-07-27 11:59:14 +00:00
fsm_type=partial(
YamlFSM,
'test_fsm.yml',
{} # jinja2 variables, use empty dict to enable jinja2 parsing without any variables
)
)
ide = IdeEventHandler( # Web IDE backend
key='ide',
allowed_directories=[TFWENV.IDE_WD, TFWENV.WEBSERVICE_DIR],
directory=TFWENV.IDE_WD,
exclude=['*.pyc']
)
terminal = TerminalEventHandler( # Web shell backend
2019-06-27 12:38:36 +00:00
key='shell'
)
commands = TerminalCallbackEventHandler( # Reacts to terminal commands
'history.bash',
TestCommands(bashrc=f'/home/{TAOENV.USER}/.bashrc').callback
)
processmanager = ProcessManagingEventHandler( # Handles 'deploy' button clicks
key='processmanager',
log_tail=2000
)
logmonitor = LogMonitoringEventHandler( # Sends live logs of webservice process to frontend
2018-05-30 13:23:54 +00:00
key='logmonitor',
process_name='webservice',
log_tail=2000
)
2018-08-07 15:03:41 +00:00
snapshot = DirectorySnapshottingEventHandler( # Manages filesystem snapshots of directories
key='snapshot',
directories=[
TFWENV.IDE_WD,
TFWENV.WEBSERVICE_DIR
]
)
frontend = FrontendEventHandler() # Proxies frontend API calls to frontend
# Your custom event handlers
message_fsm_steps_eh = MessageFSMStepsEventHandler(
key='test'
)
2019-06-28 13:12:27 +00:00
event_handlers = EventHandler.get_local_instances()
def stop(sig, frame): # pylint: disable=unused-argument
for eh in event_handlers:
2019-05-20 09:09:27 +00:00
eh.stop()
exit(0)
2019-05-20 09:09:27 +00:00
signal(SIGTERM, stop)
signal(SIGINT, stop)
IOLoop.instance().start()
if __name__ == '__main__':
main()