baseimage-tutorial-framework/tfw/components/fsm/fsm_handler.py
2019-08-26 11:12:13 +02:00

52 lines
1.6 KiB
Python

import logging
from tfw.internals.crypto import KeyManager, sign_message
from tfw.internals.networking import Scope, Intent
from .fsm_updater import FSMUpdater
LOG = logging.getLogger(__name__)
class FSMHandler:
keys = ['fsm']
def __init__(self, *, fsm_type, initial_trigger):
self.connector = None
self.fsm = fsm_type()
self._fsm_updater = FSMUpdater(self.fsm)
self.auth_key = KeyManager().auth_key
self.initial_trigger = initial_trigger
self.command_handlers = {
'frontend.ready' : self.handle_ready,
'fsm.step' : self.handle_step,
'fsm.update' : self.handle_update
}
def start(self):
self.connector.subscribe('frontend.ready')
def handle_event(self, message, _):
try:
message = self.command_handlers[message['key']](message)
if message:
fsm_update_message = self._fsm_updater.fsm_update
sign_message(self.auth_key, fsm_update_message)
self.connector.send_message(fsm_update_message, Scope.BROADCAST, Intent.EVENT)
except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
def handle_ready(self, message):
self.fsm.step(self.initial_trigger)
self.connector.unsubscribe('frontend.ready')
return message
def handle_step(self, message): # pylint: disable=inconsistent-return-statements
if self.fsm.step(message['trigger']):
return message
def handle_update(self, message):
# pylint: disable=no-self-use
return message