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

65 lines
2.3 KiB
Python
Raw Normal View History

# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
2019-06-10 13:32:45 +00:00
import logging
from xmlrpc.client import Fault as SupervisorFault
2019-05-27 12:09:13 +00:00
from tfw.event_handlers import FrontendEventHandlerBase
from tfw.mixins.supervisor_mixin import SupervisorMixin, SupervisorLogMixin
from tfw.components.directory_monitor import with_monitor_paused
LOG = logging.getLogger(__name__)
2018-02-16 11:07:16 +00:00
class ProcessManager(SupervisorMixin, SupervisorLogMixin):
def __init__(self):
self.commands = {
'start': self.start_process,
'stop': self.stop_process,
'restart': self.restart_process
}
2018-02-20 13:45:16 +00:00
def __call__(self, command, process_name):
return self.commands[command](process_name)
2018-02-20 13:45:16 +00:00
2019-05-26 16:26:33 +00:00
class ProcessManagingEventHandler(FrontendEventHandlerBase):
2018-04-18 17:44:26 +00:00
"""
Event handler that can manage processes managed by supervisor.
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
Every message must contain a data['process_name'] field with the name of the
2018-04-18 17:44:26 +00:00
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, log_tail=0):
super().__init__(key)
self.monitor = dirmonitor
self.processmanager = ProcessManager()
self.log_tail = log_tail
2018-02-16 11:07:16 +00:00
@with_monitor_paused
def handle_event(self, message):
try:
data = message['data']
2018-05-28 13:02:53 +00:00
try:
self.processmanager(data['command'], data['process_name'])
except SupervisorFault as fault:
message['data']['error'] = fault.faultString
finally:
message['data']['stdout'] = self.processmanager.read_stdout(
data['process_name'],
self.log_tail
)
message['data']['stderr'] = self.processmanager.read_stderr(
data['process_name'],
self.log_tail
)
2018-05-29 09:05:45 +00:00
return message
except KeyError:
LOG.error('IGNORING MESSAGE: Invalid message received: %s', message)