2017-11-09 05:04:48 +01:00
|
|
|
import logging
|
2020-08-14 00:34:13 +02:00
|
|
|
import re
|
|
|
|
import socket
|
2020-01-11 18:13:25 +01:00
|
|
|
import time
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2021-04-05 00:58:44 +02:00
|
|
|
from threading import Thread, Event as ThreadEvent, get_ident
|
2021-03-03 19:19:56 +01:00
|
|
|
from typing import Optional, Dict
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2023-08-15 02:06:13 +02:00
|
|
|
from platypush import __version__
|
2017-12-18 03:09:38 +01:00
|
|
|
from platypush.bus import Bus
|
2021-09-16 17:53:40 +02:00
|
|
|
from platypush.common import ExtensionWithManifest
|
2017-12-18 01:10:51 +01:00
|
|
|
from platypush.config import Config
|
2019-05-15 09:31:04 +02:00
|
|
|
from platypush.context import get_backend
|
2023-08-15 02:06:13 +02:00
|
|
|
from platypush.event import EventGenerator
|
|
|
|
from platypush.message import Message
|
|
|
|
from platypush.message.event import Event
|
2023-07-22 23:02:44 +02:00
|
|
|
from platypush.message.event.zeroconf import (
|
|
|
|
ZeroconfServiceAddedEvent,
|
|
|
|
ZeroconfServiceRemovedEvent,
|
|
|
|
)
|
2023-08-15 02:06:13 +02:00
|
|
|
from platypush.message.request import Request
|
|
|
|
from platypush.message.response import Response
|
2023-07-22 23:02:44 +02:00
|
|
|
from platypush.utils import (
|
|
|
|
clear_timeout,
|
|
|
|
get_backend_name_by_class,
|
2023-08-15 02:06:13 +02:00
|
|
|
get_redis,
|
|
|
|
get_redis_queue_name_by_message,
|
|
|
|
get_remaining_timeout,
|
|
|
|
set_timeout,
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2019-05-15 09:31:04 +02:00
|
|
|
|
2018-06-06 20:09:18 +02:00
|
|
|
|
2021-09-16 17:53:40 +02:00
|
|
|
class Backend(Thread, EventGenerator, ExtensionWithManifest):
|
2018-06-26 00:16:39 +02:00
|
|
|
"""
|
|
|
|
Parent class for backends.
|
|
|
|
|
|
|
|
A backend is basically a thread that checks for new events on some channel
|
|
|
|
(e.g. a network socket, a queue, some new entries on an API endpoint or an
|
|
|
|
RSS feed, a voice command through an assistant, a new measure from a sensor
|
|
|
|
etc.) and propagates event messages to the main application bus whenever a
|
|
|
|
new event happens. You can then build whichever type of custom logic you
|
|
|
|
want on such events.
|
|
|
|
"""
|
2017-12-17 16:15:44 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
_default_response_timeout = 5
|
|
|
|
|
2020-01-11 18:13:25 +01:00
|
|
|
# Loop function, can be implemented by derived classes
|
|
|
|
loop = None
|
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
def __init__(
|
|
|
|
self, bus: Optional[Bus] = None, poll_seconds: Optional[float] = None, **kwargs
|
|
|
|
):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
2018-06-26 00:16:39 +02:00
|
|
|
:param bus: Reference to the bus object to be used in the backend
|
2020-01-11 18:13:25 +01:00
|
|
|
:param poll_seconds: If the backend implements a ``loop`` method, this parameter expresses how often the
|
|
|
|
loop should run in seconds.
|
2018-06-26 00:16:39 +02:00
|
|
|
:param kwargs: Key-value configuration for the backend
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
2019-01-13 20:41:15 +01:00
|
|
|
self._thread_name = self.__class__.__name__
|
2019-02-28 01:21:25 +01:00
|
|
|
EventGenerator.__init__(self)
|
2021-09-16 17:53:40 +02:00
|
|
|
ExtensionWithManifest.__init__(self)
|
2020-08-01 17:20:46 +02:00
|
|
|
Thread.__init__(self, name=self._thread_name, daemon=True)
|
2019-01-10 23:08:29 +01:00
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
# 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()
|
2020-01-11 18:13:25 +01:00
|
|
|
self.poll_seconds = float(poll_seconds) if poll_seconds else None
|
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
|
2021-04-05 00:58:44 +02:00
|
|
|
self._stop_event = ThreadEvent()
|
2023-08-15 02:06:13 +02:00
|
|
|
self._stop_thread: Optional[Thread] = None
|
2017-12-22 00:49:03 +01:00
|
|
|
self._kwargs = kwargs
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger = logging.getLogger(
|
|
|
|
'platypush:backend:' + get_backend_name_by_class(self.__class__)
|
|
|
|
)
|
2020-08-14 00:34:13 +02:00
|
|
|
self.zeroconf = None
|
|
|
|
self.zeroconf_info = None
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
# Internal-only, we set the request context on a backend if that
|
|
|
|
# backend is intended to react for a response to a specific request
|
2023-07-22 23:02:44 +02:00
|
|
|
self._request_context = kwargs['_req_ctx'] if '_req_ctx' in kwargs else None
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2018-06-06 20:09:18 +02:00
|
|
|
if 'logging' in kwargs:
|
2023-07-23 19:04:01 +02:00
|
|
|
self.logger.setLevel(getattr(logging, kwargs['logging'].upper()))
|
2018-06-06 20:09:18 +02: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.
|
|
|
|
|
2019-05-15 09:31:04 +02:00
|
|
|
:param msg: Received message. It can be either a key-value dictionary, a platypush.message.Message object,
|
|
|
|
or a string/byte UTF-8 encoded string
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
2018-06-26 00:16:39 +02:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
msg = Message.build(msg)
|
2023-07-23 19:04:01 +02:00
|
|
|
if msg is None:
|
|
|
|
return
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
if not getattr(msg, 'target', None) or msg.target != self.device_id:
|
2017-11-09 05:04:48 +01:00
|
|
|
return # Not for me
|
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger.debug(
|
2023-07-23 19:04:01 +02:00
|
|
|
'Message received on the %s backend: %s', self.__class__.__name__, msg
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
if self._is_expected_response(msg):
|
|
|
|
# Expected response, trigger the response handler
|
|
|
|
clear_timeout()
|
2023-07-23 19:04:01 +02:00
|
|
|
if self._request_context:
|
|
|
|
# pylint: disable=unsubscriptable-object
|
|
|
|
self._request_context['on_response'](msg)
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
self.stop()
|
|
|
|
return
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
msg.backend = self # Augment message to be able to process responses
|
2021-02-23 23:07:35 +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):
|
2023-07-23 19:04:01 +02:00
|
|
|
"""
|
|
|
|
Internal only - returns true if we are expecting for a response and msg
|
|
|
|
is that response.
|
|
|
|
"""
|
2017-12-22 00:49:03 +01:00
|
|
|
|
2022-02-07 15:45:19 +01:00
|
|
|
# pylint: disable=unsubscriptable-object
|
2023-07-22 23:02:44 +02:00
|
|
|
return (
|
|
|
|
self._request_context
|
|
|
|
and isinstance(msg, Response)
|
2017-12-22 00:49:03 +01:00
|
|
|
and msg.id == self._request_context['request'].id
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
def _get_backend_config(self):
|
2023-07-22 23:02:44 +02:00
|
|
|
config_name = (
|
|
|
|
'backend.' + self.__class__.__name__.split('Backend', maxsplit=1)[0].lower()
|
|
|
|
)
|
2023-07-23 19:04:01 +02:00
|
|
|
return Config.get(config_name) or {}
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
def _setup_response_handler(self, request, on_response, response_timeout):
|
|
|
|
def _timeout_hndl():
|
2023-07-22 23:02:44 +02:00
|
|
|
raise RuntimeError(
|
2023-07-23 19:04:01 +02:00
|
|
|
f'Timed out while waiting for a response from {request.target}'
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
req_ctx = {
|
|
|
|
'request': request,
|
|
|
|
'on_response': on_response,
|
|
|
|
'response_timeout': response_timeout,
|
|
|
|
}
|
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
resp_backend = self.__class__(
|
|
|
|
bus=self.bus, _req_ctx=req_ctx, **self._get_backend_config(), **self._kwargs
|
|
|
|
)
|
2017-12-22 00:49:03 +01:00
|
|
|
|
|
|
|
# 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):
|
|
|
|
"""
|
2018-06-26 00:16:39 +02:00
|
|
|
Send an event message on the backend.
|
|
|
|
|
2019-12-30 09:33:26 +01:00
|
|
|
:param event: Event to send. It can be a dict, a string/bytes UTF-8 JSON, or a platypush.message.event.Event
|
|
|
|
object.
|
2017-12-24 01:03:26 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
def send_request(
|
|
|
|
self,
|
|
|
|
request,
|
|
|
|
on_response=None,
|
|
|
|
response_timeout=_default_response_timeout,
|
2023-07-23 19:04:01 +02:00
|
|
|
**kwargs,
|
2023-07-22 23:02:44 +02:00
|
|
|
):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
2018-06-26 00:16:39 +02:00
|
|
|
Send a request message on the backend.
|
|
|
|
|
2019-12-30 09:33:26 +01:00
|
|
|
:param request: The request, either a dict, a string/bytes UTF-8 JSON, or a platypush.message.request.Request
|
|
|
|
object.
|
2018-06-26 00:16:39 +02:00
|
|
|
|
2019-12-30 09:33:26 +01:00
|
|
|
:param on_response: Optional callback that will be called when a response is received. If set, this method will
|
|
|
|
synchronously wait for a response before exiting.
|
2018-06-26 00:16:39 +02:00
|
|
|
:type on_response: function
|
|
|
|
|
2019-12-30 09:33:26 +01:00
|
|
|
:param 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: None)
|
2018-06-26 00:16:39 +02:00
|
|
|
:type response_timeout: float
|
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
|
|
|
"""
|
2018-06-26 00:16:39 +02:00
|
|
|
Send a response message on the backend.
|
|
|
|
|
2019-12-30 09:33:26 +01:00
|
|
|
:param response: The response, either a dict, a string/bytes UTF-8 JSON, or a
|
|
|
|
:class:`platypush.message.response.Response` object.
|
2018-06-26 00:16:39 +02:00
|
|
|
:param request: Associated request, used to set the response parameters that will link them
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
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
|
|
|
self.send_message(response, **kwargs)
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2022-02-07 15:45:19 +01:00
|
|
|
def send_message(self, msg, queue_name=None, **_):
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
Sends a platypush.message.Message to a node.
|
2018-06-14 20:42:57 +02:00
|
|
|
To be implemented in the derived classes. By default, if the Redis
|
|
|
|
backend is configured then it will try to deliver the message to
|
|
|
|
other consumers through the configured Redis main queue.
|
2017-12-16 04:56:43 +01:00
|
|
|
|
2018-06-26 00:16:39 +02:00
|
|
|
:param msg: The message to send
|
2019-12-30 09:33:26 +01:00
|
|
|
:param queue_name: Send the message on a specific queue (default: the queue_name configured on the Redis
|
|
|
|
backend)
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
2018-06-29 10:21:16 +02:00
|
|
|
|
2018-06-14 20:42:57 +02:00
|
|
|
try:
|
|
|
|
redis = get_backend('redis')
|
2018-06-14 20:44:06 +02:00
|
|
|
if not redis:
|
|
|
|
raise KeyError()
|
2018-06-14 20:42:57 +02:00
|
|
|
except KeyError:
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger.warning(
|
|
|
|
(
|
2023-07-23 19:04:01 +02:00
|
|
|
"Backend %s does not implement send_message "
|
2023-07-22 23:02:44 +02:00
|
|
|
"and the fallback Redis backend isn't configured"
|
2023-07-23 19:04:01 +02:00
|
|
|
),
|
|
|
|
self.__class__.__name__,
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2018-06-14 20:42:57 +02:00
|
|
|
return
|
|
|
|
|
2018-06-29 10:21:16 +02:00
|
|
|
redis.send_message(msg, queue_name=queue_name)
|
2017-11-29 02:42:36 +01:00
|
|
|
|
2017-11-09 05:04:48 +01:00
|
|
|
def run(self):
|
2023-07-22 23:02:44 +02:00
|
|
|
"""Starts the backend thread. To be implemented in the derived classes if the loop method isn't defined."""
|
2021-04-05 00:58:44 +02:00
|
|
|
self.thread_id = get_ident()
|
2020-01-11 18:13:25 +01:00
|
|
|
if not callable(self.loop):
|
|
|
|
return
|
|
|
|
|
2020-02-05 22:26:52 +01:00
|
|
|
while not self.should_stop():
|
|
|
|
try:
|
|
|
|
with self:
|
|
|
|
has_error = False
|
|
|
|
|
|
|
|
while not self.should_stop() and not has_error:
|
|
|
|
try:
|
2022-02-07 15:45:19 +01:00
|
|
|
# pylint: disable=not-callable
|
2020-02-05 22:26:52 +01:00
|
|
|
self.loop()
|
|
|
|
except Exception as e:
|
|
|
|
has_error = True
|
|
|
|
self.logger.error(str(e))
|
|
|
|
self.logger.exception(e)
|
|
|
|
finally:
|
|
|
|
if self.poll_seconds:
|
|
|
|
time.sleep(self.poll_seconds)
|
|
|
|
elif has_error:
|
|
|
|
time.sleep(5)
|
|
|
|
except Exception as e:
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger.error(
|
2023-07-23 19:04:01 +02:00
|
|
|
'%s initialization error: %s', self.__class__.__name__, e
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2020-02-05 22:26:52 +01:00
|
|
|
self.logger.exception(e)
|
|
|
|
time.sleep(self.poll_seconds or 5)
|
2020-01-11 18:13:25 +01:00
|
|
|
|
|
|
|
def __enter__(self):
|
2023-07-22 23:02:44 +02:00
|
|
|
"""Invoked when the backend is initialized, if the main logic is within a ``loop()`` function"""
|
2023-07-23 19:04:01 +02:00
|
|
|
self.logger.info('Initialized backend %s', self.__class__.__name__)
|
2020-01-11 18:13:25 +01:00
|
|
|
|
2023-07-23 19:04:01 +02:00
|
|
|
def __exit__(self, *_, **__):
|
2023-07-22 23:02:44 +02:00
|
|
|
"""Invoked when the backend is terminated, if the main logic is within a ``loop()`` function"""
|
2020-01-11 18:13:25 +01:00
|
|
|
self.on_stop()
|
2023-07-23 19:04:01 +02:00
|
|
|
self.logger.info('Terminated backend %s', self.__class__.__name__)
|
2017-11-09 05:04:48 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def on_stop(self):
|
2023-07-22 23:02:44 +02:00
|
|
|
"""Callback invoked when the process stops"""
|
2017-12-18 22:40:56 +01:00
|
|
|
|
2017-12-20 20:25:08 +01:00
|
|
|
def stop(self):
|
2023-07-22 23:02:44 +02:00
|
|
|
"""Stops the backend thread by sending a STOP event on its bus"""
|
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
def _async_stop():
|
2019-12-30 09:33:26 +01:00
|
|
|
self._stop_event.set()
|
2021-02-23 23:07:35 +01:00
|
|
|
self.unregister_service()
|
2017-12-22 00:49:03 +01:00
|
|
|
self.on_stop()
|
2023-08-15 02:06:13 +02:00
|
|
|
self._stop_thread = None
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2023-08-15 02:06:13 +02:00
|
|
|
if not (self._stop_thread and self._stop_thread.is_alive()):
|
|
|
|
self._stop_thread = Thread(target=_async_stop)
|
|
|
|
self._stop_thread.start()
|
2017-12-20 20:25:08 +01:00
|
|
|
|
|
|
|
def should_stop(self):
|
2023-08-15 02:06:13 +02:00
|
|
|
"""
|
|
|
|
:return: True if the backend thread should be stopped, False otherwise.
|
|
|
|
"""
|
2021-02-23 23:07:35 +01:00
|
|
|
return self._stop_event.is_set()
|
2019-12-30 09:33:26 +01:00
|
|
|
|
2020-08-22 12:09:24 +02:00
|
|
|
def wait_stop(self, timeout=None) -> bool:
|
2023-08-15 02:06:13 +02:00
|
|
|
"""
|
|
|
|
Waits for the backend thread to stop.
|
|
|
|
|
|
|
|
:param timeout: The maximum time to wait for the backend thread to stop (default: None)
|
|
|
|
:return: True if the backend thread has stopped, False otherwise.
|
|
|
|
"""
|
|
|
|
start = time.time()
|
|
|
|
|
|
|
|
if self._stop_thread:
|
|
|
|
try:
|
|
|
|
self._stop_thread.join(
|
|
|
|
get_remaining_timeout(timeout=timeout, start=start)
|
|
|
|
)
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return self._stop_event.wait(
|
|
|
|
get_remaining_timeout(timeout=timeout, start=start)
|
|
|
|
)
|
2017-12-20 20:25:08 +01:00
|
|
|
|
2018-10-11 16:02:26 +02:00
|
|
|
def get_message_response(self, msg):
|
2023-07-23 19:04:01 +02:00
|
|
|
queue = get_redis_queue_name_by_message(msg)
|
|
|
|
if not queue:
|
|
|
|
self.logger.warning('No response queue configured for the message')
|
|
|
|
return None
|
|
|
|
|
2018-10-11 16:02:26 +02:00
|
|
|
try:
|
2023-08-14 23:37:38 +02:00
|
|
|
redis = get_redis()
|
2023-07-23 19:04:01 +02:00
|
|
|
response = redis.blpop(queue, timeout=60)
|
2019-02-23 21:19:00 +01:00
|
|
|
if response and len(response) > 1:
|
2018-10-11 16:02:26 +02:00
|
|
|
response = Message.build(response[1])
|
|
|
|
else:
|
|
|
|
response = None
|
|
|
|
|
|
|
|
return response
|
|
|
|
except Exception as e:
|
2023-07-23 19:04:01 +02:00
|
|
|
self.logger.error('Error while processing response to %s: %s', msg, e)
|
|
|
|
|
|
|
|
return None
|
2018-10-11 16:02:26 +02:00
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
@staticmethod
|
|
|
|
def _get_ip() -> str:
|
|
|
|
"""
|
|
|
|
Get the IP address of the machine.
|
|
|
|
"""
|
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
s.connect(('8.8.8.8', 80))
|
|
|
|
addr = s.getsockname()[0]
|
|
|
|
s.close()
|
|
|
|
return addr
|
|
|
|
|
2023-07-22 23:02:44 +02:00
|
|
|
def register_service(
|
|
|
|
self,
|
|
|
|
port: Optional[int] = None,
|
|
|
|
name: Optional[str] = None,
|
|
|
|
srv_type: Optional[str] = None,
|
|
|
|
srv_name: Optional[str] = None,
|
|
|
|
udp: bool = False,
|
|
|
|
properties: Optional[Dict] = None,
|
|
|
|
):
|
2020-08-14 00:34:13 +02:00
|
|
|
"""
|
|
|
|
Initialize the Zeroconf service configuration for this backend.
|
2021-03-03 19:19:56 +01:00
|
|
|
|
|
|
|
:param port: Service listen port (default: the backend ``port`` attribute if available, or ``None``).
|
|
|
|
:param name: Service short name (default: backend name).
|
|
|
|
:param srv_type: Service type (default: ``_platypush-{name}._{proto}.local.``).
|
|
|
|
:param srv_name: Full service name (default: ``{hostname or device_id}.{type}``).
|
|
|
|
:param udp: Set to True if this is a UDP service.
|
|
|
|
:param properties: Extra properties to be passed on the service. Default:
|
|
|
|
|
|
|
|
.. code-block:: json
|
|
|
|
|
|
|
|
{
|
|
|
|
"name": "Platypush",
|
|
|
|
"vendor": "Platypush",
|
|
|
|
"version": "{platypush_version}"
|
|
|
|
}
|
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
from zeroconf import ServiceInfo, Zeroconf
|
2020-08-14 20:53:20 +02:00
|
|
|
from platypush.plugins.zeroconf import ZeroconfListener
|
2020-08-14 00:34:13 +02:00
|
|
|
except ImportError:
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger.warning(
|
|
|
|
'zeroconf package not available, service discovery will be disabled.'
|
|
|
|
)
|
2020-08-14 00:34:13 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
self.zeroconf = Zeroconf()
|
|
|
|
srv_desc = {
|
|
|
|
'name': 'Platypush',
|
|
|
|
'vendor': 'Platypush',
|
|
|
|
'version': __version__,
|
2021-03-03 19:19:56 +01:00
|
|
|
**(properties or {}),
|
2020-08-14 00:34:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
name = name or re.sub(r'Backend$', '', self.__class__.__name__).lower()
|
2023-07-23 19:04:01 +02:00
|
|
|
srv_type = srv_type or f'_platypush-{name}._{"udp" if udp else "tcp"}.local.'
|
|
|
|
srv_name = srv_name or f'{self.device_id}.{srv_type}'
|
|
|
|
srv_port = port if port else getattr(self, 'port', None)
|
2023-07-22 23:02:44 +02:00
|
|
|
self.zeroconf_info = ServiceInfo(
|
|
|
|
srv_type,
|
|
|
|
srv_name,
|
|
|
|
addresses=[socket.inet_aton(self._get_ip())],
|
|
|
|
port=srv_port,
|
|
|
|
weight=0,
|
|
|
|
priority=0,
|
|
|
|
properties=srv_desc,
|
|
|
|
)
|
2020-08-14 00:34:13 +02:00
|
|
|
|
2021-02-27 21:11:37 +01:00
|
|
|
if not self.zeroconf_info:
|
|
|
|
self.logger.warning('Could not register Zeroconf service')
|
|
|
|
return
|
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
self.zeroconf.register_service(self.zeroconf_info)
|
2023-07-22 23:02:44 +02:00
|
|
|
self.bus.post(
|
|
|
|
ZeroconfServiceAddedEvent(
|
|
|
|
service_type=srv_type,
|
|
|
|
service_name=srv_name,
|
|
|
|
service_info=ZeroconfListener.parse_service_info(self.zeroconf_info),
|
|
|
|
)
|
|
|
|
)
|
2020-08-14 00:34:13 +02:00
|
|
|
|
|
|
|
def unregister_service(self):
|
|
|
|
"""
|
|
|
|
Unregister the Zeroconf service configuration if available.
|
|
|
|
"""
|
2023-08-17 01:49:41 +02:00
|
|
|
from redis import exceptions
|
|
|
|
|
2020-08-14 00:34:13 +02:00
|
|
|
if self.zeroconf and self.zeroconf_info:
|
2021-02-27 15:01:25 +01:00
|
|
|
try:
|
|
|
|
self.zeroconf.unregister_service(self.zeroconf_info)
|
|
|
|
except Exception as e:
|
2023-07-22 23:02:44 +02:00
|
|
|
self.logger.warning(
|
2023-07-23 19:04:01 +02:00
|
|
|
'Could not register Zeroconf service %s: %s: %s',
|
|
|
|
self.zeroconf_info.name,
|
|
|
|
type(e).__name__,
|
|
|
|
e,
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2021-02-27 15:01:25 +01:00
|
|
|
|
2020-08-20 00:37:39 +02:00
|
|
|
if self.zeroconf:
|
2023-07-24 10:37:07 +02:00
|
|
|
try:
|
|
|
|
self.zeroconf.close()
|
|
|
|
except TimeoutError:
|
|
|
|
pass
|
2020-08-20 00:37:39 +02:00
|
|
|
|
2023-08-17 01:49:41 +02:00
|
|
|
try:
|
|
|
|
if self.zeroconf_info:
|
|
|
|
self.bus.post(
|
|
|
|
ZeroconfServiceRemovedEvent(
|
|
|
|
service_type=self.zeroconf_info.type,
|
|
|
|
service_name=self.zeroconf_info.name,
|
|
|
|
)
|
2023-07-22 23:02:44 +02:00
|
|
|
)
|
2023-08-17 01:49:41 +02:00
|
|
|
else:
|
|
|
|
self.bus.post(
|
|
|
|
ZeroconfServiceRemovedEvent(
|
|
|
|
service_type=None, service_name=None
|
|
|
|
)
|
|
|
|
)
|
|
|
|
except exceptions.ConnectionError:
|
|
|
|
pass
|
2020-08-14 00:34:13 +02:00
|
|
|
|
|
|
|
self.zeroconf_info = None
|
|
|
|
self.zeroconf = None
|
|
|
|
|
2017-12-18 22:40:56 +01:00
|
|
|
|
2017-11-09 05:04:48 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|