2018-10-26 21:55:49 +02:00
|
|
|
import asyncio
|
|
|
|
import websockets
|
|
|
|
|
|
|
|
from platypush.backend import Backend
|
|
|
|
from platypush.context import get_plugin, get_or_create_event_loop
|
|
|
|
from platypush.message import Message
|
|
|
|
from platypush.message.request import Request
|
2019-02-23 21:19:00 +01:00
|
|
|
from platypush.message.response import Response
|
2018-11-01 23:34:14 +01:00
|
|
|
from platypush.utils import get_ssl_server_context
|
2018-10-26 21:55:49 +02:00
|
|
|
|
|
|
|
|
|
|
|
class WebsocketBackend(Backend):
|
|
|
|
"""
|
|
|
|
Backend to communicate messages over a websocket medium.
|
|
|
|
|
|
|
|
Requires:
|
|
|
|
|
|
|
|
* **websockets** (``pip install websockets``)
|
|
|
|
"""
|
|
|
|
|
2018-10-27 01:09:09 +02:00
|
|
|
# Websocket client message recv timeout in seconds
|
2018-11-02 11:14:06 +01:00
|
|
|
_websocket_client_timeout = 0
|
2018-10-27 01:09:09 +02:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
# Default websocket service port
|
|
|
|
_default_websocket_port = 8765
|
|
|
|
|
|
|
|
def __init__(self, port=_default_websocket_port, bind_address='0.0.0.0',
|
|
|
|
ssl_cafile=None, ssl_capath=None, ssl_cert=None, ssl_key=None,
|
2018-11-01 23:34:14 +01:00
|
|
|
client_timeout=_websocket_client_timeout, **kwargs):
|
2018-10-26 21:55:49 +02:00
|
|
|
"""
|
|
|
|
:param port: Listen port for the websocket server (default: 8765)
|
|
|
|
:type port: int
|
|
|
|
|
|
|
|
:param bind_address: Bind address for the websocket server (default: 0.0.0.0, listen for any IP connection)
|
|
|
|
:type websocket_port: str
|
|
|
|
|
2018-11-01 18:28:54 +01:00
|
|
|
:param ssl_cert: Path to the certificate file if you want to enable SSL (default: None)
|
2018-10-26 21:55:49 +02:00
|
|
|
:type ssl_cert: str
|
2018-10-27 01:09:09 +02:00
|
|
|
|
2018-11-01 18:28:54 +01:00
|
|
|
:param ssl_key: Path to the key file if you want to enable SSL (default: None)
|
|
|
|
:type ssl_key: str
|
|
|
|
|
2018-11-01 23:34:14 +01:00
|
|
|
:param ssl_cafile: Path to the certificate authority file if required by the SSL configuration (default: None)
|
|
|
|
:type ssl_cafile: str
|
|
|
|
|
|
|
|
:param ssl_capath: Path to the certificate authority directory if required by the SSL configuration (default: None)
|
|
|
|
:type ssl_capath: str
|
|
|
|
|
2018-11-02 11:14:06 +01:00
|
|
|
:param client_timeout: Timeout without any messages being received before closing a client connection. A zero timeout keeps the websocket open until an error occurs (default: 0, no timeout)
|
2018-10-27 01:09:09 +02:00
|
|
|
:type ping_timeout: int
|
2018-10-26 21:55:49 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
|
|
|
|
self.port = port
|
|
|
|
self.bind_address = bind_address
|
2018-10-27 01:09:09 +02:00
|
|
|
self.client_timeout = client_timeout
|
2018-11-02 11:14:06 +01:00
|
|
|
self.active_websockets = set()
|
2021-02-23 23:07:35 +01:00
|
|
|
self._loop = None
|
2018-10-26 21:55:49 +02:00
|
|
|
|
2018-11-01 23:34:14 +01:00
|
|
|
self.ssl_context = get_ssl_server_context(ssl_cert=ssl_cert,
|
|
|
|
ssl_key=ssl_key,
|
|
|
|
ssl_cafile=ssl_cafile,
|
|
|
|
ssl_capath=ssl_capath) \
|
|
|
|
if ssl_cert else None
|
2018-10-26 21:55:49 +02:00
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
def send_message(self, msg, **kwargs):
|
2018-10-26 21:55:49 +02:00
|
|
|
websocket = get_plugin('websocket')
|
|
|
|
websocket_args = {}
|
|
|
|
|
|
|
|
if self.ssl_context:
|
|
|
|
url = 'wss://localhost:{}'.format(self.port)
|
2018-11-01 18:28:54 +01:00
|
|
|
websocket_args['ssl'] = self.ssl_context
|
2018-10-26 21:55:49 +02:00
|
|
|
else:
|
|
|
|
url = 'ws://localhost:{}'.format(self.port)
|
|
|
|
|
|
|
|
websocket.send(url=url, msg=msg, **websocket_args)
|
|
|
|
|
2018-11-02 11:14:06 +01:00
|
|
|
def notify_web_clients(self, event):
|
|
|
|
""" Notify all the connected web clients (over websocket) of a new event """
|
|
|
|
async def send_event(websocket):
|
|
|
|
try:
|
|
|
|
await websocket.send(str(event))
|
|
|
|
except Exception as e:
|
|
|
|
self.logger.warning('Error on websocket send_event: {}'.format(e))
|
|
|
|
|
|
|
|
loop = get_or_create_event_loop()
|
2019-08-16 12:24:42 +02:00
|
|
|
active_websockets = self.active_websockets.copy()
|
2018-11-02 11:14:06 +01:00
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
for ws in active_websockets:
|
2018-11-02 11:14:06 +01:00
|
|
|
try:
|
2020-08-14 00:34:13 +02:00
|
|
|
loop.run_until_complete(send_event(ws))
|
2018-11-02 11:14:06 +01:00
|
|
|
except websockets.exceptions.ConnectionClosed:
|
|
|
|
self.logger.info('Client connection lost')
|
2020-08-14 00:34:13 +02:00
|
|
|
self.active_websockets.remove(ws)
|
2018-11-02 11:14:06 +01:00
|
|
|
|
2018-10-26 21:55:49 +02:00
|
|
|
def run(self):
|
|
|
|
super().run()
|
2020-08-14 00:34:13 +02:00
|
|
|
self.register_service(port=self.port, name='ws')
|
2018-10-26 21:55:49 +02:00
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
# noinspection PyUnusedLocal
|
2018-10-26 21:55:49 +02:00
|
|
|
async def serve_client(websocket, path):
|
2018-11-02 11:14:06 +01:00
|
|
|
self.active_websockets.add(websocket)
|
2018-10-27 01:09:09 +02:00
|
|
|
self.logger.debug('New websocket connection from {}'.
|
2020-08-14 00:34:13 +02:00
|
|
|
format(websocket.remote_address[0]))
|
2018-10-26 21:55:49 +02:00
|
|
|
|
|
|
|
try:
|
2021-02-23 23:07:35 +01:00
|
|
|
while not self.should_stop():
|
2018-10-27 01:09:09 +02:00
|
|
|
if self.client_timeout:
|
|
|
|
msg = await asyncio.wait_for(websocket.recv(),
|
|
|
|
timeout=self.client_timeout)
|
|
|
|
else:
|
|
|
|
msg = await websocket.recv()
|
|
|
|
|
|
|
|
msg = Message.build(msg)
|
|
|
|
self.logger.info('Received message from {}: {}'.
|
2020-08-14 00:34:13 +02:00
|
|
|
format(websocket.remote_address[0], msg))
|
2018-10-26 21:55:49 +02:00
|
|
|
|
2018-10-27 01:09:09 +02:00
|
|
|
self.on_message(msg)
|
2018-10-26 21:55:49 +02:00
|
|
|
|
2018-10-27 01:09:09 +02:00
|
|
|
if isinstance(msg, Request):
|
2019-02-23 21:19:00 +01:00
|
|
|
response = self.get_message_response(msg) or Response()
|
2018-10-26 21:55:49 +02:00
|
|
|
self.logger.info('Processing response on the websocket backend: {}'.
|
2019-02-23 21:19:00 +01:00
|
|
|
format(response))
|
2018-10-26 21:55:49 +02:00
|
|
|
|
|
|
|
await websocket.send(str(response))
|
2018-10-27 01:09:09 +02:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
except websockets.exceptions.ConnectionClosed as e:
|
|
|
|
self.active_websockets.remove(websocket)
|
|
|
|
self.logger.debug('Websocket client {} closed connection'.
|
|
|
|
format(websocket.remote_address[0]))
|
|
|
|
except asyncio.TimeoutError as e:
|
|
|
|
self.active_websockets.remove(websocket)
|
|
|
|
self.logger.debug('Websocket connection to {} timed out'.
|
|
|
|
format(websocket.remote_address[0]))
|
2018-10-26 21:55:49 +02:00
|
|
|
except Exception as e:
|
2019-02-23 21:19:00 +01:00
|
|
|
self.logger.exception(e)
|
2018-10-26 21:55:49 +02:00
|
|
|
|
|
|
|
self.logger.info('Initialized websocket backend on port {}, bind address: {}'.
|
|
|
|
format(self.port, self.bind_address))
|
|
|
|
|
|
|
|
websocket_args = {}
|
|
|
|
if self.ssl_context:
|
|
|
|
websocket_args['ssl'] = self.ssl_context
|
|
|
|
|
2021-02-23 23:07:35 +01:00
|
|
|
self._loop = get_or_create_event_loop()
|
2018-10-27 01:09:09 +02:00
|
|
|
server = websockets.serve(serve_client, self.bind_address, self.port,
|
|
|
|
**websocket_args)
|
|
|
|
|
2021-02-23 23:07:35 +01:00
|
|
|
self._loop.run_until_complete(server)
|
|
|
|
self._loop.run_forever()
|
|
|
|
|
|
|
|
def on_stop(self):
|
|
|
|
self.logger.info('Received STOP event on the websocket backend')
|
|
|
|
if self._loop:
|
|
|
|
self._loop.stop()
|
|
|
|
|
|
|
|
self.logger.info('Websocket backend terminated')
|
2018-10-26 21:55:49 +02:00
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|