baseimage-tutorial-framework/lib/tfw/components/process_managing_event_handler.py
2018-04-18 19:44:26 +02:00

56 lines
2.0 KiB
Python

# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
from xmlrpc.client import Fault as SupervisorFault
from tfw import EventHandlerBase
from tfw.mixins import SupervisorMixin
from tfw.config.logs import logging
from .directory_monitor import with_monitor_paused
LOG = logging.getLogger(__name__)
class ProcessManager(SupervisorMixin):
def __init__(self):
self.commands = {'start': self.start_process,
'stop': self.stop_process,
'restart': self.restart_process,
'readlog': self.read_log}
def __call__(self, command, process_name):
return self.commands[command](process_name)
class ProcessManagingEventHandler(EventHandlerBase):
"""
Event handler that can manage processes managed by supervisor.
This EventHandler accepts messages that have a data["command"] key specifying
a command to be executed.
Every message must contain a data["process_name"] field with the name of the
process to manage. This is the name specified in supervisor config files like so:
[program:someprogram]
Commands available: start, stop, restart, readlog
(the names are as self-documenting as it gets)
"""
def __init__(self, key, dirmonitor=None):
super().__init__(key)
self.key = key
self.monitor = dirmonitor
self.processmanager = ProcessManager()
@with_monitor_paused
def handle_event(self, message):
try:
data = message['data']
self.processmanager(data['command'], data['process_name'])
return message
except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)
except SupervisorFault as fault:
message['data']['error'] = fault.faultString
message['data']['log'] = self.processmanager.read_log(message['data']['process_name'])
return message