2017-12-17 16:15:44 +01:00
|
|
|
import importlib
|
2017-11-09 05:04:48 +01:00
|
|
|
import logging
|
2017-12-13 04:14:46 +01:00
|
|
|
import sys
|
2017-12-20 20:25:08 +01:00
|
|
|
import threading
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
from threading import Thread
|
|
|
|
|
2017-12-18 03:09:38 +01:00
|
|
|
from platypush.bus import Bus
|
2017-12-18 01:10:51 +01:00
|
|
|
from platypush.config import Config
|
2017-12-22 00:49:03 +01:00
|
|
|
from platypush.utils import get_message_class_by_type, set_timeout, clear_timeout
|
2017-12-17 16:15:44 +01:00
|
|
|
from platypush.message import Message
|
2017-12-20 20:25:08 +01:00
|
|
|
from platypush.message.event import Event, StopEvent
|
2017-12-17 16:15:44 +01:00
|
|
|
from platypush.message.request import Request
|
|
|
|
from platypush.message.response import Response
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
class Backend(Thread):
|
2017-12-17 16:15:44 +01:00
|
|
|
""" Parent class for backends """
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
_default_response_timeout = 5
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
def __init__(self, bus=None, **kwargs):
|
|
|
|
"""
|
|
|
|
Params:
|
|
|
|
bus -- Reference to the Platypush bus where the requests and the
|
2017-12-18 03:09:38 +01:00
|
|
|
responses will be posted [Bus]
|
2017-12-17 16:15:44 +01:00
|
|
|
kwargs -- key-value configuration for this backend [Dict]
|
|
|
|
"""
|
|
|
|
|
|
|
|
# If no bus is specified, create an internal queue where
|
|
|
|
# the received messages will be pushed
|
2017-12-22 00:49:03 +01:00
|
|
|
self.bus = bus or Bus()
|
2017-12-18 01:10:51 +01:00
|
|
|
self.device_id = Config.get('device_id')
|
2017-12-20 20:25:08 +01:00
|
|
|
self.thread_id = None
|
|
|
|
self._stop = False
|
2017-12-22 00:49:03 +01:00
|
|
|
self._kwargs = kwargs
|
|
|
|
|
|
|
|
# Internal-only, we set the request context on a backend if that
|
|
|
|
# backend is intended to react for a response to a specific request
|
|
|
|
self._request_context = kwargs['_req_ctx'] if '_req_ctx' in kwargs \
|
|
|
|
else None
|
2017-11-09 05:04:48 +01:00
|
|
|
|
|
|
|
Thread.__init__(self)
|
2017-12-18 01:10:51 +01:00
|
|
|
logging.basicConfig(stream=sys.stdout, level=Config.get('logging')
|
2017-12-17 16:15:44 +01:00
|
|
|
if 'logging' not in kwargs
|
|
|
|
else getattr(logging, kwargs['logging']))
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2017-12-11 16:48:28 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def on_message(self, msg):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Callback when a message is received on the backend.
|
|
|
|
It parses and posts the message on the main bus.
|
|
|
|
It should be called by the derived classes whenever
|
|
|
|
a new message should be processed.
|
|
|
|
|
|
|
|
Params:
|
|
|
|
msg -- The message. It can be either a key-value
|
|
|
|
dictionary, a platypush.message.Message
|
|
|
|
object, or a string/byte UTF-8 encoded string
|
|
|
|
"""
|
2017-12-22 00:49:03 +01:00
|
|
|
msg = Message.build(msg)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
if not getattr(msg, 'target') or msg.target != self.device_id:
|
2017-11-09 05:04:48 +01:00
|
|
|
return # Not for me
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
logging.debug('Message received on the {} backend: {}'.format(
|
2017-12-20 20:25:08 +01:00
|
|
|
self.__class__.__name__, msg))
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
if self._is_expected_response(msg):
|
|
|
|
# Expected response, trigger the response handler
|
|
|
|
clear_timeout()
|
|
|
|
self._request_context['on_response'](msg)
|
|
|
|
self.stop()
|
|
|
|
return
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
if isinstance(msg, StopEvent) and msg.targets_me():
|
2017-12-22 00:49:03 +01:00
|
|
|
logging.info('Received STOP event on {}'.format(self.__class__.__name__))
|
2017-12-20 20:25:08 +01:00
|
|
|
self._stop = True
|
|
|
|
else:
|
2017-12-22 00:49:03 +01:00
|
|
|
msg.backend = self # Augment message to be able to process responses
|
2017-12-20 20:25:08 +01:00
|
|
|
self.bus.post(msg)
|
2017-12-16 04:56:43 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
def _is_expected_response(self, msg):
|
|
|
|
""" Internal only - returns true if we are expecting for a response
|
|
|
|
and msg is that response """
|
|
|
|
|
|
|
|
return self._request_context \
|
|
|
|
and isinstance(msg, Response) \
|
|
|
|
and msg.id == self._request_context['request'].id
|
|
|
|
|
|
|
|
|
|
|
|
def _get_backend_config(self):
|
|
|
|
config_name = 'backend.' + self.__class__.__name__.split('Backend')[0].lower()
|
|
|
|
return Config.get(config_name)
|
|
|
|
|
|
|
|
|
|
|
|
def _setup_response_handler(self, request, on_response, response_timeout):
|
|
|
|
def _timeout_hndl():
|
|
|
|
raise RuntimeError('Timed out while waiting for a response from {}'.
|
|
|
|
format(request.target))
|
|
|
|
|
|
|
|
req_ctx = {
|
|
|
|
'request': request,
|
|
|
|
'on_response': on_response,
|
|
|
|
'response_timeout': response_timeout,
|
|
|
|
}
|
|
|
|
|
|
|
|
resp_backend = self.__class__(bus=self.bus, _req_ctx=req_ctx,
|
|
|
|
**self._get_backend_config(), **self._kwargs)
|
|
|
|
|
|
|
|
# Set the response timeout
|
2017-12-22 02:11:56 +01:00
|
|
|
if response_timeout:
|
|
|
|
set_timeout(seconds=response_timeout, on_timeout=_timeout_hndl)
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
resp_backend.start()
|
|
|
|
|
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
def send_event(self, event, **kwargs):
|
|
|
|
"""
|
|
|
|
Send an event message on the backend
|
|
|
|
Params:
|
|
|
|
event -- The request, either a dict, a string/bytes UTF-8 JSON,
|
|
|
|
or a platypush.message.event.Event object.
|
|
|
|
"""
|
|
|
|
|
|
|
|
event = Event.build(event)
|
|
|
|
assert isinstance(event, Event)
|
|
|
|
|
|
|
|
event.origin = self.device_id
|
|
|
|
if not hasattr(event, 'target'):
|
|
|
|
event.target = self.device_id
|
|
|
|
|
|
|
|
self.send_message(event, **kwargs)
|
|
|
|
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
def send_request(self, request, on_response=None,
|
|
|
|
response_timeout=_default_response_timeout, **kwargs):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Send a request message on the backend
|
|
|
|
Params:
|
2017-12-22 00:49:03 +01:00
|
|
|
request -- The request, either a dict, a string/bytes UTF-8 JSON,
|
|
|
|
or a platypush.message.request.Request object.
|
|
|
|
|
|
|
|
on_response -- Response handler, takes a platypush.message.response.Response
|
|
|
|
as argument. If set, the method will wait for a
|
|
|
|
response before exiting (default: None)
|
|
|
|
response_timeout -- If on_response is set, the backend will raise
|
|
|
|
an exception if the response isn't received
|
|
|
|
within this number of seconds (default: 5)
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
request = Request.build(request)
|
|
|
|
assert isinstance(request, Request)
|
|
|
|
|
|
|
|
request.origin = self.device_id
|
|
|
|
|
2017-12-22 02:11:56 +01:00
|
|
|
if on_response and response_timeout != 0:
|
2017-12-22 00:49:03 +01:00
|
|
|
self._setup_response_handler(request, on_response, response_timeout)
|
|
|
|
|
|
|
|
self.send_message(request, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
def send_response(self, response, request, **kwargs):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Send a response message on the backend
|
|
|
|
Params:
|
|
|
|
response -- The response, either a dict, a string/bytes UTF-8 JSON,
|
|
|
|
or a platypush.message.response.Response object
|
2017-12-22 00:49:03 +01:00
|
|
|
request -- Associated request, used to set the response parameters
|
|
|
|
that will link them
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
response = Response.build(response)
|
|
|
|
assert isinstance(response, Response)
|
2017-12-22 00:49:03 +01:00
|
|
|
assert isinstance(request, Request)
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
response.id = request.id
|
|
|
|
response.target = request.origin
|
2017-12-17 16:15:44 +01:00
|
|
|
response.origin = self.device_id
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
self.send_message(response, **kwargs)
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
def send_message(self, msg, **kwargs):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Sends a platypush.message.Message to a node.
|
|
|
|
To be implemented in the derived classes.
|
2017-12-20 20:25:08 +01:00
|
|
|
Always call send_request or send_response instead of send_message directly
|
2017-12-16 04:56:43 +01:00
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
Param:
|
|
|
|
msg -- The message
|
|
|
|
"""
|
2017-12-16 04:56:43 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
raise NotImplementedError("send_message should be implemented in a derived class")
|
2017-11-29 02:42:36 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
|
2017-11-09 05:04:48 +01:00
|
|
|
def run(self):
|
2017-12-17 16:15:44 +01:00
|
|
|
""" Starts the backend thread. To be implemented in the derived classes """
|
2017-12-20 20:25:08 +01:00
|
|
|
self.thread_id = threading.get_ident()
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def on_stop(self):
|
|
|
|
""" Callback invoked when the process stops """
|
2017-12-18 22:40:56 +01:00
|
|
|
pass
|
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def stop(self):
|
|
|
|
""" Stops the backend thread by sending a STOP event on its bus """
|
2017-12-22 00:49:03 +01:00
|
|
|
def _async_stop():
|
|
|
|
evt = StopEvent(target=self.device_id, origin=self.device_id,
|
|
|
|
thread_id=self.thread_id)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
self.send_message(evt)
|
|
|
|
self.on_stop()
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
Thread(target=_async_stop).start()
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
def should_stop(self):
|
|
|
|
return self._stop
|
|
|
|
|
2017-12-18 22:40:56 +01:00
|
|
|
|
2017-11-09 05:04:48 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|
|
|
|
|