2017-12-20 20:25:08 +01:00
|
|
|
import argparse
|
2017-10-29 05:17:42 +01:00
|
|
|
import logging
|
2017-10-30 02:54:16 +01:00
|
|
|
import sys
|
2017-12-13 04:14:46 +01:00
|
|
|
import traceback
|
2017-10-29 05:17:42 +01:00
|
|
|
|
2017-10-31 10:24:15 +01:00
|
|
|
from threading import Thread
|
2017-12-13 04:21:26 +01:00
|
|
|
|
2017-12-18 01:10:51 +01:00
|
|
|
from .bus import Bus
|
|
|
|
from .config import Config
|
2017-12-20 20:25:08 +01:00
|
|
|
from .utils import get_or_load_plugin, init_backends, get_module_and_name_from_action
|
2017-12-17 16:15:44 +01:00
|
|
|
from .message.request import Request
|
2017-12-13 04:21:26 +01:00
|
|
|
from .message.response import Response
|
2017-10-29 05:17:42 +01:00
|
|
|
|
2017-11-03 01:56:27 +01:00
|
|
|
__author__ = 'Fabio Manganiello <info@fabiomanganiello.com>'
|
2017-12-18 22:45:55 +01:00
|
|
|
__version__ = '0.4'
|
2017-11-03 01:56:27 +01:00
|
|
|
|
|
|
|
#-----------#
|
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
class Daemon(object):
|
|
|
|
""" Main class for the Platypush daemon """
|
|
|
|
|
|
|
|
""" Configuration file (default: either ~/.config/platypush/config.yaml or
|
|
|
|
/etc/platypush/config.yaml) """
|
|
|
|
config_file = None
|
|
|
|
|
|
|
|
""" Application bus. It's an internal queue where:
|
|
|
|
- backends will post the messages they receive
|
|
|
|
- plugins will post the responses they process """
|
|
|
|
bus = None
|
|
|
|
|
|
|
|
""" backend_name => backend_obj map """
|
|
|
|
backends = None
|
|
|
|
|
|
|
|
""" number of executions retries before a request fails """
|
|
|
|
n_tries = 2
|
|
|
|
|
2017-12-20 22:12:32 +01:00
|
|
|
def __init__(self, config_file=None, message_handler=None):
|
2017-12-20 20:25:08 +01:00
|
|
|
""" Constructor
|
|
|
|
Params:
|
|
|
|
config_file -- Configuration file override (default: None)
|
2017-12-20 22:12:32 +01:00
|
|
|
message_handler -- Another function that will receive the messages.
|
|
|
|
If set, Platypush will just act as a message proxy. Useful to
|
|
|
|
embed into other projects, for tests, or for delegating events.
|
2017-12-20 20:25:08 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
self.config_file = config_file
|
2017-12-22 00:49:03 +01:00
|
|
|
self.message_handler = message_handler
|
2017-12-20 20:25:08 +01:00
|
|
|
Config.init(self.config_file)
|
|
|
|
logging.basicConfig(level=Config.get('logging'), stream=sys.stdout)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def build_from_cmdline(cls, args):
|
|
|
|
""" Build the app from command line arguments.
|
|
|
|
Params:
|
|
|
|
args -- Your sys.argv[1:] [List of strings]
|
|
|
|
"""
|
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('--config', '-c', dest='config', required=False,
|
|
|
|
default=None, help=cls.config_file.__doc__)
|
|
|
|
|
|
|
|
opts, args = parser.parse_known_args(args)
|
|
|
|
return cls(config_file=opts.config)
|
|
|
|
|
|
|
|
def on_message(self):
|
|
|
|
""" Default message handler """
|
|
|
|
|
|
|
|
def _f(msg):
|
|
|
|
""" on_message closure
|
|
|
|
Params:
|
|
|
|
msg -- platypush.message.Message instance """
|
2017-12-20 22:12:32 +01:00
|
|
|
|
|
|
|
if self.message_handler:
|
|
|
|
# Proxy the message
|
|
|
|
self.message_handler(msg)
|
|
|
|
return
|
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
if isinstance(msg, Request):
|
|
|
|
logging.info('Processing request: {}'.format(msg))
|
|
|
|
Thread(target=self.run_request(), args=(msg,)).start()
|
|
|
|
elif isinstance(msg, Response):
|
|
|
|
logging.info('Received response: {}'.format(msg))
|
|
|
|
|
|
|
|
return _f
|
|
|
|
|
|
|
|
|
|
|
|
def run_request(self):
|
|
|
|
""" Runs a request and returns the response """
|
|
|
|
def _thread_func(request, n_tries=self.n_tries):
|
|
|
|
""" Thread closure method
|
|
|
|
Params:
|
|
|
|
request - platypush.message.request.Request object """
|
|
|
|
|
|
|
|
(module_name, method_name) = get_module_and_name_from_action(request.action)
|
|
|
|
|
|
|
|
try:
|
|
|
|
plugin = get_or_load_plugin(module_name)
|
|
|
|
except RuntimeError as e: # Module/class not found
|
|
|
|
logging.exception(e)
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Run the action
|
|
|
|
response = plugin.run(method=method_name, **request.args)
|
|
|
|
if response and response.is_error():
|
2017-12-22 00:49:03 +01:00
|
|
|
raise RuntimeError('Response processed with errors: {}'.format(response))
|
|
|
|
|
|
|
|
logging.info('Processed response from plugin {}: {}'.
|
|
|
|
format(plugin, response))
|
|
|
|
except Exception as e:
|
|
|
|
# Retry mechanism
|
2017-12-20 20:25:08 +01:00
|
|
|
response = Response(output=None, errors=[str(e), traceback.format_exc()])
|
|
|
|
logging.exception(e)
|
|
|
|
if n_tries:
|
|
|
|
logging.info('Reloading plugin {} and retrying'.format(module_name))
|
|
|
|
get_or_load_plugin(module_name, reload=True)
|
|
|
|
_thread_func(request, n_tries=n_tries-1)
|
|
|
|
finally:
|
2017-12-22 00:49:03 +01:00
|
|
|
# Send the response on the backend
|
|
|
|
if request.backend and request.origin:
|
|
|
|
request.backend.send_response(response=response, request=request)
|
|
|
|
else:
|
|
|
|
logging.info('Dropping response whose request has no ' +
|
|
|
|
'origin attached: {}'.format(request))
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
return _thread_func
|
|
|
|
|
|
|
|
def start(self):
|
|
|
|
""" Start the daemon """
|
|
|
|
self.bus = Bus(on_message=self.on_message())
|
|
|
|
|
|
|
|
# Initialize the backends and link them to the bus
|
2017-12-22 00:49:03 +01:00
|
|
|
self.backends = init_backends(bus=self.bus)
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
# Start the backend threads
|
|
|
|
for backend in self.backends.values():
|
|
|
|
backend.start()
|
|
|
|
|
|
|
|
# Poll for messages on the bus
|
|
|
|
try:
|
|
|
|
self.bus.poll()
|
|
|
|
except KeyboardInterrupt as e:
|
|
|
|
logging.info('SIGINT received, terminating application')
|
|
|
|
|
|
|
|
for backend in self.backends.values():
|
|
|
|
backend.stop()
|
|
|
|
|
|
|
|
|
|
|
|
def main(args=sys.argv[1:]):
|
2017-12-13 04:14:46 +01:00
|
|
|
print('Starting platypush v.{}'.format(__version__))
|
2017-12-20 20:25:08 +01:00
|
|
|
app = Daemon.build_from_cmdline(args)
|
|
|
|
app.start()
|
2017-10-29 05:17:42 +01:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|
2017-10-29 20:45:19 +01:00
|
|
|
|
2017-11-04 12:28:15 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|