2018-01-29 13:47:21 +01:00
|
|
|
import os
|
2019-02-25 10:52:48 +01:00
|
|
|
import subprocess
|
2019-02-07 14:26:10 +01:00
|
|
|
import threading
|
2018-01-04 02:45:23 +01:00
|
|
|
|
|
|
|
from multiprocessing import Process
|
2018-07-08 21:36:58 +02:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
from platypush.backend import Backend
|
2019-02-24 00:11:35 +01:00
|
|
|
from platypush.backend.http.app import application
|
2019-02-23 21:19:00 +01:00
|
|
|
from platypush.context import get_or_create_event_loop
|
|
|
|
from platypush.utils import get_ssl_server_context, set_thread_name
|
2018-01-04 02:45:23 +01:00
|
|
|
|
|
|
|
|
|
|
|
class HttpBackend(Backend):
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
|
|
|
The HTTP backend is a general-purpose web server that you can leverage:
|
|
|
|
|
|
|
|
* To execute Platypush commands via HTTP calls. Example::
|
|
|
|
|
|
|
|
curl -XPOST -H 'Content-Type: application/json' -H "X-Token: your_token" \\
|
|
|
|
-d '{
|
|
|
|
"type":"request",
|
|
|
|
"target":"nodename",
|
|
|
|
"action":"tts.say",
|
|
|
|
"args": {"phrase":"This is a test"}
|
|
|
|
}' \\
|
|
|
|
http://localhost:8008/execute
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
* To interact with your system (and control plugins and backends) through the Platypush web panel,
|
|
|
|
by default available on your web root document. Any plugin that you have configured and available as a panel
|
|
|
|
plugin will appear on the web panel as well as a tab.
|
2018-06-26 00:16:39 +02:00
|
|
|
|
|
|
|
* To display a fullscreen dashboard with your configured widgets, by default available under ``/dashboard``
|
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
* To stream media over HTTP through the ``/media`` endpoint
|
|
|
|
|
|
|
|
Any plugin can register custom routes under ``platypush/backend/http/app/routes/plugins``.
|
|
|
|
Any additional route is managed as a Flask blueprint template and the `.py`
|
|
|
|
module can expose lists of routes to the main webapp through the
|
|
|
|
``__routes__`` object (a list of Flask blueprints).
|
|
|
|
|
2018-07-08 21:36:58 +02:00
|
|
|
Note that if you set up a main token, it will be required for any HTTP
|
|
|
|
interaction - either as ``X-Token`` HTTP header, on the query string
|
|
|
|
(attribute name: ``token``), as part of the JSON payload root (attribute
|
2018-07-08 22:00:28 +02:00
|
|
|
name: ``token``), or via HTTP basic auth (any username works).
|
2018-07-08 21:36:58 +02:00
|
|
|
|
2018-06-26 00:16:39 +02:00
|
|
|
Requires:
|
|
|
|
|
|
|
|
* **flask** (``pip install flask``)
|
|
|
|
* **redis** (``pip install redis``)
|
|
|
|
* **websockets** (``pip install websockets``)
|
2018-12-19 00:09:21 +01:00
|
|
|
* **python-dateutil** (``pip install python-dateutil``)
|
2019-02-07 14:26:10 +01:00
|
|
|
* **magic** (``pip install python-magic``), optional, for MIME type
|
|
|
|
support if you want to enable media streaming
|
2019-02-24 12:35:26 +01:00
|
|
|
* **uwsgi** (``pip install uwsgi`` plus uwsgi server installed on your
|
|
|
|
system if required) - optional but recommended. By default the
|
|
|
|
Platypush web server will run in a process spawned on the fly by
|
|
|
|
the HTTP backend. However, being a Flask app, it will serve clients
|
|
|
|
in a single thread and won't support many features of a full-blown
|
|
|
|
web server.
|
|
|
|
|
|
|
|
Base command to run the web server over uwsgi::
|
|
|
|
|
|
|
|
uwsgi --http :8008 --module platypush.backend.http.uwsgi --master --processes 4 --threads 4
|
2019-02-24 15:53:01 +01:00
|
|
|
|
|
|
|
Bear in mind that the main webapp is defined in ``platypush.backend.http.app:application``
|
|
|
|
and the WSGI startup script is stored under ``platypush/backend/http/uwsgi.py``.
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
2018-01-04 02:45:23 +01:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
_DEFAULT_HTTP_PORT = 8008
|
|
|
|
_DEFAULT_WEBSOCKET_PORT = 8009
|
2019-02-07 14:26:10 +01:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
def __init__(self, port=_DEFAULT_HTTP_PORT,
|
|
|
|
websocket_port=_DEFAULT_WEBSOCKET_PORT,
|
2019-05-15 09:31:04 +02:00
|
|
|
disable_websocket=False, dashboard=None, resource_dirs=None,
|
2018-11-01 23:43:02 +01:00
|
|
|
ssl_cert=None, ssl_key=None, ssl_cafile=None, ssl_capath=None,
|
2019-05-15 09:31:04 +02:00
|
|
|
maps=None, run_externally=False, uwsgi_args=None, **kwargs):
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
|
|
|
:param port: Listen port for the web server (default: 8008)
|
|
|
|
:type port: int
|
|
|
|
|
|
|
|
:param websocket_port: Listen port for the websocket server (default: 8009)
|
|
|
|
:type websocket_port: int
|
|
|
|
|
|
|
|
:param disable_websocket: Disable the websocket interface (default: False)
|
|
|
|
:type disable_websocket: bool
|
|
|
|
|
2018-11-01 23:43:02 +01:00
|
|
|
:param ssl_cert: Set it to the path of your certificate file if you want to enable HTTPS (default: None)
|
|
|
|
:type ssl_cert: str
|
|
|
|
|
|
|
|
:param ssl_key: Set it to the path of your key file if you want to enable HTTPS (default: None)
|
|
|
|
:type ssl_key: str
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
:param ssl_cafile: Set it to the path of your certificate authority file if you want to enable HTTPS
|
|
|
|
(default: None)
|
2018-11-01 23:43:02 +01:00
|
|
|
:type ssl_cafile: str
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
:param ssl_capath: Set it to the path of your certificate authority directory if you want to enable HTTPS
|
|
|
|
(default: None)
|
2018-11-01 23:43:02 +01:00
|
|
|
:type ssl_capath: str
|
|
|
|
|
2018-12-30 18:40:03 +01:00
|
|
|
:param resource_dirs: Static resources directories that will be
|
|
|
|
accessible through ``/resources/<path>``. It is expressed as a map
|
|
|
|
where the key is the relative path under ``/resources`` to expose and
|
|
|
|
the value is the absolute path to expose.
|
|
|
|
:type resource_dirs: dict[str, str]
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
:param dashboard: Set it if you want to use the dashboard service. It will contain the configuration for the
|
|
|
|
widgets to be used (look under ``platypush/backend/http/templates/widgets/`` for the available widgets).
|
2018-06-26 00:16:39 +02:00
|
|
|
|
|
|
|
Example configuration::
|
|
|
|
|
|
|
|
dashboard:
|
|
|
|
background_image: https://site/image.png
|
|
|
|
widgets: # Each row of the dashboard will have 6 columns
|
2019-01-28 23:14:12 +01:00
|
|
|
-
|
|
|
|
widget: calendar # Calendar widget
|
2018-06-26 00:16:39 +02:00
|
|
|
columns: 6
|
2019-01-28 23:14:12 +01:00
|
|
|
-
|
|
|
|
widget: music # Music widget
|
2018-06-26 00:16:39 +02:00
|
|
|
columns: 3
|
2019-01-28 23:14:12 +01:00
|
|
|
-
|
|
|
|
widget: date-time-weather # Date, time and weather widget
|
2018-06-26 00:16:39 +02:00
|
|
|
columns: 3
|
2019-01-28 23:14:12 +01:00
|
|
|
-
|
|
|
|
widget: image-carousel # Image carousel
|
2018-06-26 00:16:39 +02:00
|
|
|
columns: 6
|
2019-05-15 09:31:04 +02:00
|
|
|
# Absolute path (valid as long as it's a subdirectory of one of the available `resource_dirs`)
|
|
|
|
images_path: ~/Dropbox/Photos/carousel
|
2018-06-26 00:16:39 +02:00
|
|
|
refresh_seconds: 15
|
2019-01-28 23:14:12 +01:00
|
|
|
-
|
|
|
|
widget: rss-news # RSS feeds widget
|
2018-06-26 00:16:39 +02:00
|
|
|
# Requires backend.http.poll to be enabled with some RSS sources and write them to sqlite db
|
|
|
|
columns: 6
|
|
|
|
limit: 25
|
2019-05-15 09:31:04 +02:00
|
|
|
db: "sqlite:////home/user/.local/share/platypush/feeds/rss.db"
|
2018-06-26 00:16:39 +02:00
|
|
|
|
|
|
|
:type dashboard: dict
|
2019-02-24 12:35:26 +01:00
|
|
|
|
|
|
|
:param run_externally: If set, then the HTTP backend will not directly
|
|
|
|
spawn the web server. Set this option if you plan to run the webapp
|
|
|
|
in a separate web server (recommended), like uwsgi or uwsgi+nginx.
|
|
|
|
:type run_externally: bool
|
2019-02-25 10:52:48 +01:00
|
|
|
|
|
|
|
:param uwsgi_args: If ``run_externally`` is set and you would like the
|
|
|
|
HTTP backend to directly spawn and control the uWSGI application
|
|
|
|
server instance, then pass the list of uWSGI arguments through
|
|
|
|
this parameter. Some examples include::
|
|
|
|
|
|
|
|
# Start uWSGI instance listening on HTTP port 8008 with 4
|
|
|
|
# processes
|
|
|
|
['--plugin', 'python', '--http-socket', ':8008', '--master', '--processes', '4']
|
|
|
|
|
|
|
|
# Start uWSGI instance listening on uWSGI socket on port 3031.
|
|
|
|
# You can then use another full-blown web server, like nginx
|
|
|
|
# or Apache, to communicate with the uWSGI instance
|
|
|
|
['--plugin', 'python', '--socket', '127.0.0.1:3031', '--master', '--processes', '4']
|
|
|
|
:type uwsgi_args: list[str]
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
|
|
|
|
2018-01-04 02:45:23 +01:00
|
|
|
super().__init__(**kwargs)
|
2018-05-04 03:24:35 +02:00
|
|
|
|
2018-01-04 02:45:23 +01:00
|
|
|
self.port = port
|
2018-01-29 13:47:21 +01:00
|
|
|
self.websocket_port = websocket_port
|
2019-05-15 09:31:04 +02:00
|
|
|
self.dashboard = dashboard or {}
|
|
|
|
self.maps = maps or {}
|
2019-02-21 16:15:06 +01:00
|
|
|
self.server_proc = None
|
2018-01-29 16:34:00 +01:00
|
|
|
self.disable_websocket = disable_websocket
|
2018-01-29 13:47:21 +01:00
|
|
|
self.websocket_thread = None
|
2019-05-15 09:31:04 +02:00
|
|
|
|
|
|
|
if resource_dirs:
|
|
|
|
self.resource_dirs = {name: os.path.abspath(
|
|
|
|
os.path.expanduser(d)) for name, d in resource_dirs.items()}
|
|
|
|
else:
|
|
|
|
self.resource_dirs = {}
|
|
|
|
|
2018-01-29 13:47:21 +01:00
|
|
|
self.active_websockets = set()
|
2019-02-24 12:35:26 +01:00
|
|
|
self.run_externally = run_externally
|
2019-02-25 10:52:48 +01:00
|
|
|
self.uwsgi_args = uwsgi_args or []
|
2018-11-01 23:43:02 +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-07-08 12:13:43 +02:00
|
|
|
|
2019-02-25 10:52:48 +01:00
|
|
|
if self.uwsgi_args:
|
|
|
|
self.uwsgi_args = [str(_) for _ in self.uwsgi_args] + \
|
|
|
|
['--module', 'platypush.backend.http.uwsgi', '--enable-threads']
|
|
|
|
|
2019-06-21 02:13:14 +02:00
|
|
|
self.local_base_url = '{proto}://localhost:{port}'.\
|
|
|
|
format(proto=('https' if ssl_cert else 'http'), port=self.port)
|
|
|
|
|
2020-02-06 01:04:36 +01:00
|
|
|
self._websocket_lock_timeout = 10
|
|
|
|
self._websocket_lock = threading.RLock()
|
|
|
|
self._websocket_locks = {}
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
def send_message(self, msg, **kwargs):
|
2018-06-06 20:09:18 +02:00
|
|
|
self.logger.warning('Use cURL or any HTTP client to query the HTTP backend')
|
2018-01-04 02:45:23 +01:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
def on_stop(self):
|
|
|
|
""" On backend stop """
|
2018-06-06 20:09:18 +02:00
|
|
|
self.logger.info('Received STOP event on HttpBackend')
|
2018-01-29 13:47:21 +01:00
|
|
|
|
2019-02-21 16:15:06 +01:00
|
|
|
if self.server_proc:
|
2019-02-25 10:52:48 +01:00
|
|
|
if isinstance(self.server_proc, subprocess.Popen):
|
|
|
|
self.server_proc.kill()
|
|
|
|
self.server_proc.wait()
|
|
|
|
else:
|
|
|
|
self.server_proc.terminate()
|
|
|
|
self.server_proc.join()
|
2018-01-04 02:45:23 +01:00
|
|
|
|
2020-02-06 01:04:36 +01:00
|
|
|
def _acquire_websocket_lock(self, ws):
|
|
|
|
try:
|
|
|
|
acquire_ok = self._websocket_lock.acquire(timeout=self._websocket_lock_timeout)
|
|
|
|
if not acquire_ok:
|
|
|
|
raise TimeoutError('Websocket lock acquire timeout')
|
|
|
|
|
|
|
|
addr = ws.remote_address
|
|
|
|
if addr not in self._websocket_locks:
|
|
|
|
self._websocket_locks[addr] = threading.RLock()
|
|
|
|
finally:
|
|
|
|
self._websocket_lock.release()
|
|
|
|
|
|
|
|
acquire_ok = self._websocket_locks[addr].acquire(timeout=self._websocket_lock_timeout)
|
|
|
|
if not acquire_ok:
|
|
|
|
raise TimeoutError('Websocket on address {} not ready to receive data'.format(addr))
|
|
|
|
|
|
|
|
def _release_websocket_lock(self, ws):
|
2020-02-06 19:30:40 +01:00
|
|
|
try:
|
|
|
|
acquire_ok = self._websocket_lock.acquire(timeout=self._websocket_lock_timeout)
|
|
|
|
if not acquire_ok:
|
|
|
|
raise TimeoutError('Websocket lock acquire timeout')
|
|
|
|
|
|
|
|
addr = ws.remote_address
|
|
|
|
if addr in self._websocket_locks:
|
2020-02-06 01:04:36 +01:00
|
|
|
self._websocket_locks[addr].release()
|
2020-02-06 19:30:40 +01:00
|
|
|
except Exception as e:
|
|
|
|
self.logger.warning('Unhandled exception while releasing websocket lock: {}'.format(str(e)))
|
|
|
|
finally:
|
|
|
|
self._websocket_lock.release()
|
2020-02-06 01:04:36 +01:00
|
|
|
|
2018-01-29 13:47:21 +01:00
|
|
|
def notify_web_clients(self, event):
|
2018-06-26 00:16:39 +02:00
|
|
|
""" Notify all the connected web clients (over websocket) of a new event """
|
2018-01-29 16:34:00 +01:00
|
|
|
import websockets
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
async def send_event(ws):
|
2018-10-20 19:27:15 +02:00
|
|
|
try:
|
2020-02-06 01:04:36 +01:00
|
|
|
self._acquire_websocket_lock(ws)
|
2019-05-15 09:31:04 +02:00
|
|
|
await ws.send(str(event))
|
2018-10-20 19:27:15 +02:00
|
|
|
except Exception as e:
|
|
|
|
self.logger.warning('Error on websocket send_event: {}'.format(e))
|
2020-02-06 01:04:36 +01:00
|
|
|
finally:
|
|
|
|
self._release_websocket_lock(ws)
|
2018-01-29 13:47:21 +01:00
|
|
|
|
2018-10-26 21:55:49 +02:00
|
|
|
loop = get_or_create_event_loop()
|
2019-05-15 09:31:04 +02:00
|
|
|
wss = self.active_websockets.copy()
|
2020-02-06 19:30:40 +01:00
|
|
|
|
2020-02-06 01:04:36 +01:00
|
|
|
for _ws in wss:
|
2018-01-29 13:47:21 +01:00
|
|
|
try:
|
2020-02-06 01:04:36 +01:00
|
|
|
loop.run_until_complete(send_event(_ws))
|
2018-01-29 13:47:21 +01:00
|
|
|
except websockets.exceptions.ConnectionClosed:
|
2020-02-06 01:04:36 +01:00
|
|
|
self.logger.warning('Websocket client {} connection lost'.format(_ws.remote_address))
|
|
|
|
self.active_websockets.remove(_ws)
|
|
|
|
if _ws.remote_address in self._websocket_locks:
|
|
|
|
del self._websocket_locks[_ws.remote_address]
|
2018-01-29 13:47:21 +01:00
|
|
|
|
|
|
|
def websocket(self):
|
2018-06-26 00:16:39 +02:00
|
|
|
""" Websocket main server """
|
2018-01-29 16:34:00 +01:00
|
|
|
import websockets
|
2019-01-13 20:41:15 +01:00
|
|
|
set_thread_name('WebsocketServer')
|
2018-01-29 16:34:00 +01:00
|
|
|
|
2018-01-29 13:47:21 +01:00
|
|
|
async def register_websocket(websocket, path):
|
2020-02-06 01:04:36 +01:00
|
|
|
address = websocket.remote_address if websocket.remote_address \
|
2018-11-01 23:57:50 +01:00
|
|
|
else '<unknown client>'
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
self.logger.info('New websocket connection from {} on path {}'.format(address, path))
|
2018-01-29 13:47:21 +01:00
|
|
|
self.active_websockets.add(websocket)
|
|
|
|
|
2018-05-06 11:38:24 +02:00
|
|
|
try:
|
|
|
|
await websocket.recv()
|
|
|
|
except websockets.exceptions.ConnectionClosed:
|
2018-11-01 23:57:50 +01:00
|
|
|
self.logger.info('Websocket client {} closed connection'.format(address))
|
2018-05-06 11:38:24 +02:00
|
|
|
self.active_websockets.remove(websocket)
|
2020-02-06 01:04:36 +01:00
|
|
|
if address in self._websocket_locks:
|
|
|
|
del self._websocket_locks[address]
|
2018-01-29 13:47:21 +01:00
|
|
|
|
2018-11-01 23:57:50 +01:00
|
|
|
websocket_args = {}
|
|
|
|
if self.ssl_context:
|
|
|
|
websocket_args['ssl'] = self.ssl_context
|
|
|
|
|
2018-10-26 21:55:49 +02:00
|
|
|
loop = get_or_create_event_loop()
|
2018-01-29 13:47:21 +01:00
|
|
|
loop.run_until_complete(
|
2018-11-01 23:57:50 +01:00
|
|
|
websockets.serve(register_websocket, '0.0.0.0', self.websocket_port,
|
|
|
|
**websocket_args))
|
2018-01-29 13:47:21 +01:00
|
|
|
loop.run_forever()
|
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
def _start_web_server(self):
|
|
|
|
def proc():
|
2019-02-25 10:52:48 +01:00
|
|
|
self.logger.info('Starting local web server on port {}'.format(self.port))
|
2019-02-23 21:19:00 +01:00
|
|
|
kwargs = {
|
|
|
|
'host': '0.0.0.0',
|
|
|
|
'port': self.port,
|
|
|
|
'use_reloader': False,
|
|
|
|
'debug': False,
|
|
|
|
}
|
2018-11-01 23:43:02 +01:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
if self.ssl_context:
|
|
|
|
kwargs['ssl_context'] = self.ssl_context
|
|
|
|
|
2019-02-24 00:11:35 +01:00
|
|
|
application.run(**kwargs)
|
2019-02-23 21:19:00 +01:00
|
|
|
|
|
|
|
return proc
|
2018-11-01 23:43:02 +01:00
|
|
|
|
2019-02-23 21:19:00 +01:00
|
|
|
def run(self):
|
|
|
|
super().run()
|
2018-01-29 16:34:00 +01:00
|
|
|
|
|
|
|
if not self.disable_websocket:
|
2019-02-24 12:35:26 +01:00
|
|
|
self.logger.info('Initializing websocket interface')
|
2019-02-07 14:26:10 +01:00
|
|
|
self.websocket_thread = threading.Thread(target=self.websocket)
|
2018-01-29 16:34:00 +01:00
|
|
|
self.websocket_thread.start()
|
|
|
|
|
2019-02-24 12:35:26 +01:00
|
|
|
if not self.run_externally:
|
|
|
|
self.server_proc = Process(target=self._start_web_server(),
|
|
|
|
name='WebServer')
|
|
|
|
self.server_proc.start()
|
|
|
|
self.server_proc.join()
|
2019-02-25 10:52:48 +01:00
|
|
|
elif self.uwsgi_args:
|
|
|
|
uwsgi_cmd = ['uwsgi'] + self.uwsgi_args
|
2019-05-15 09:31:04 +02:00
|
|
|
self.logger.info('Starting uWSGI with arguments {}'.format(uwsgi_cmd))
|
2019-02-25 10:52:48 +01:00
|
|
|
self.server_proc = subprocess.Popen(uwsgi_cmd)
|
2019-05-15 09:31:04 +02:00
|
|
|
else:
|
2019-08-14 20:02:13 +02:00
|
|
|
self.logger.info('The web server is configured to be launched externally but ' +
|
|
|
|
'no uwsgi_args were provided. Make sure that you run another external service' +
|
|
|
|
'for the webserver (e.g. nginx)')
|
2018-01-04 02:45:23 +01:00
|
|
|
|
|
|
|
|
2019-01-07 15:34:31 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|