platypush/platypush/__init__.py

91 lines
2.5 KiB
Python
Raw Normal View History

2017-10-29 05:17:42 +01:00
import logging
import sys
import traceback
2017-10-29 05:17:42 +01:00
from threading import Thread
from getopt import getopt
2017-12-18 01:10:51 +01:00
from .bus import Bus
from .config import Config
from .utils import get_or_load_plugin, init_backends
from .message.request import Request
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
#-----------#
def _execute_request(request, retry=True):
tokens = request.action.split('.')
module_name = str.join('.', tokens[:-1])
method_name = tokens[-1:][0]
2017-11-03 16:48:48 +01:00
try:
2017-12-18 01:10:51 +01:00
plugin = get_or_load_plugin(module_name)
except RuntimeError as e: # Module/class not found
logging.exception(e)
return
try:
response = plugin.run(method=method_name, **request.args)
if response and response.is_error():
logging.warn('Response processed with errors: {}'.format(response))
except Exception as e:
response = Response(output=None, errors=[str(e), traceback.format_exc()])
logging.exception(e)
if retry:
logging.info('Reloading plugin {} and retrying'.format(module_name))
2017-12-18 01:10:51 +01:00
get_or_load_plugin(module_name, reload=True)
_execute_request(request, retry=False)
finally:
# Send the response on the backend that received the request
if request.backend and request.origin:
if request.id: response.id = request.id
response.target = request.origin
logging.info('Processing response: {}'.format(response))
request.backend.send_response(response)
2017-12-16 07:01:25 +01:00
def on_msg(msg):
if isinstance(msg, Request):
logging.info('Processing request: {}'.format(msg))
Thread(target=_execute_request, args=(msg,)).start()
elif isinstance(msg, Response):
logging.info('Received response: {}'.format(msg))
2017-11-03 15:06:29 +01:00
def main():
print('Starting platypush v.{}'.format(__version__))
2017-11-03 15:06:29 +01:00
config_file = None
optlist, args = getopt(sys.argv[1:], 'vh')
for opt, arg in optlist:
2017-11-03 01:56:27 +01:00
if opt == '-c':
config_file = arg
elif opt == '-h':
print('''
2017-12-18 01:10:51 +01:00
Usage: {} [-h] [-c <config_file>]
-h Show this help
2017-11-03 01:56:27 +01:00
-c Path to the configuration file (default: ./config.yaml)
'''.format(sys.argv[0]))
2017-10-30 02:59:35 +01:00
return
2017-12-18 01:10:51 +01:00
Config.init(config_file)
logging.basicConfig(level=Config.get('logging'), stream=sys.stdout)
2017-11-03 01:56:27 +01:00
2017-12-18 01:10:51 +01:00
bus = Bus(on_msg=on_msg)
backends = init_backends(bus)
2017-10-29 05:17:42 +01:00
for backend in backends.values():
backend.start()
2017-12-18 01:10:51 +01:00
bus.loop_forever()
2017-10-29 05:17:42 +01:00
if __name__ == '__main__':
main()
2017-10-29 20:45:19 +01:00
# vim:sw=4:ts=4:et: