2022-08-14 22:30:49 +02:00
|
|
|
import asyncio
|
2017-12-11 03:53:26 +01:00
|
|
|
import logging
|
2021-07-22 01:02:15 +02:00
|
|
|
import threading
|
2023-04-01 22:02:59 +02:00
|
|
|
import warnings
|
2017-12-13 03:37:28 +01:00
|
|
|
|
2022-08-14 22:30:49 +02:00
|
|
|
from abc import ABC, abstractmethod
|
2018-11-01 19:42:40 +01:00
|
|
|
from functools import wraps
|
2023-02-04 00:26:48 +01:00
|
|
|
from typing import Any, Callable, Optional
|
2023-02-11 15:05:59 +01:00
|
|
|
from typing_extensions import override
|
2018-11-01 19:42:40 +01:00
|
|
|
|
2021-07-22 01:02:15 +02:00
|
|
|
from platypush.bus import Bus
|
2021-09-16 17:53:40 +02:00
|
|
|
from platypush.common import ExtensionWithManifest
|
2019-02-28 01:21:25 +01:00
|
|
|
from platypush.event import EventGenerator
|
2017-12-13 04:21:26 +01:00
|
|
|
from platypush.message.response import Response
|
2023-02-08 00:46:50 +01:00
|
|
|
from platypush.utils import get_decorators, get_plugin_name_by_class
|
2017-11-03 04:08:47 +01:00
|
|
|
|
2023-02-04 00:26:48 +01:00
|
|
|
PLUGIN_STOP_TIMEOUT = 5 # Plugin stop timeout in seconds
|
2023-01-22 14:28:16 +01:00
|
|
|
|
2019-12-17 00:56:28 +01:00
|
|
|
|
2023-02-04 00:26:48 +01:00
|
|
|
def action(f: Callable[..., Any]) -> Callable[..., Response]:
|
|
|
|
"""
|
|
|
|
Decorator used to wrap the methods in the plugin classes that should be
|
|
|
|
exposed as actions.
|
|
|
|
|
|
|
|
It wraps the method's response into a generic
|
|
|
|
:meth:`platypush.message.response.Response` object.
|
|
|
|
"""
|
|
|
|
|
2018-11-01 19:42:40 +01:00
|
|
|
@wraps(f)
|
2023-02-04 00:26:48 +01:00
|
|
|
def _execute_action(*args, **kwargs) -> Response:
|
2019-03-06 02:01:17 +01:00
|
|
|
response = Response()
|
|
|
|
result = f(*args, **kwargs)
|
|
|
|
|
|
|
|
if result and isinstance(result, Response):
|
2022-07-23 17:33:23 +02:00
|
|
|
result.errors = (
|
|
|
|
result.errors if isinstance(result.errors, list) else [result.errors]
|
|
|
|
)
|
2019-03-06 02:01:17 +01:00
|
|
|
response = result
|
|
|
|
elif isinstance(result, tuple) and len(result) == 2:
|
2022-07-23 17:33:23 +02:00
|
|
|
response.errors = result[1] if isinstance(result[1], list) else [result[1]]
|
2019-03-06 02:01:17 +01:00
|
|
|
|
|
|
|
if len(response.errors) == 1 and response.errors[0] is None:
|
|
|
|
response.errors = []
|
|
|
|
response.output = result[0]
|
|
|
|
else:
|
|
|
|
response = Response(output=result, errors=[])
|
|
|
|
|
|
|
|
return response
|
2018-07-06 02:08:38 +02:00
|
|
|
|
2018-07-16 22:56:07 +02:00
|
|
|
# Propagate the docstring
|
|
|
|
_execute_action.__doc__ = f.__doc__
|
2018-07-05 09:15:53 +02:00
|
|
|
return _execute_action
|
|
|
|
|
|
|
|
|
2022-07-23 17:33:23 +02:00
|
|
|
class Plugin(EventGenerator, ExtensionWithManifest): # lgtm [py/missing-call-to-init]
|
|
|
|
"""Base plugin class"""
|
2017-11-03 15:06:29 +01:00
|
|
|
|
2017-12-18 01:10:51 +01:00
|
|
|
def __init__(self, **kwargs):
|
2019-02-28 01:21:25 +01:00
|
|
|
super().__init__()
|
2022-07-23 17:33:23 +02:00
|
|
|
self.logger = logging.getLogger(
|
|
|
|
'platypush:plugin:' + get_plugin_name_by_class(self.__class__)
|
|
|
|
)
|
2018-06-06 20:09:18 +02:00
|
|
|
if 'logging' in kwargs:
|
|
|
|
self.logger.setLevel(getattr(logging, kwargs['logging'].upper()))
|
2017-11-03 04:08:47 +01:00
|
|
|
|
2018-07-17 01:23:12 +02:00
|
|
|
self.registered_actions = set(
|
2020-01-10 00:07:40 +01:00
|
|
|
get_decorators(self.__class__, climb_class_hierarchy=True).get('action', [])
|
2018-07-17 01:23:12 +02:00
|
|
|
)
|
2018-07-06 02:08:38 +02:00
|
|
|
|
2023-04-29 11:35:57 +02:00
|
|
|
@property
|
|
|
|
def _db(self):
|
|
|
|
"""
|
|
|
|
:return: The reference to the :class:`platypush.plugins.db.DbPlugin`.
|
|
|
|
"""
|
|
|
|
from platypush.context import get_plugin
|
|
|
|
from platypush.plugins.db import DbPlugin
|
|
|
|
|
|
|
|
db: DbPlugin = get_plugin(DbPlugin) # type: ignore
|
|
|
|
assert db, 'db plugin not initialized'
|
|
|
|
return db
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _redis(self):
|
|
|
|
"""
|
|
|
|
:return: The reference to the :class:`platypush.plugins.redis.RedisPlugin`.
|
|
|
|
"""
|
|
|
|
from platypush.context import get_plugin
|
|
|
|
from platypush.plugins.redis import RedisPlugin
|
|
|
|
|
|
|
|
redis: RedisPlugin = get_plugin(RedisPlugin) # type: ignore
|
|
|
|
assert redis, 'db plugin not initialized'
|
|
|
|
return redis
|
|
|
|
|
2023-04-29 15:50:31 +02:00
|
|
|
@property
|
|
|
|
def _entities(self):
|
|
|
|
"""
|
|
|
|
:return: The reference to the :class:`platypush.plugins.entities.EntitiesPlugin`.
|
|
|
|
"""
|
|
|
|
from platypush.context import get_plugin
|
|
|
|
from platypush.plugins.entities import EntitiesPlugin
|
|
|
|
|
2023-04-30 10:42:05 +02:00
|
|
|
entities: EntitiesPlugin = get_plugin('entities') # type: ignore
|
2023-04-29 15:50:31 +02:00
|
|
|
assert entities, 'entities plugin not initialized'
|
|
|
|
return entities
|
|
|
|
|
2017-11-04 12:28:15 +01:00
|
|
|
def run(self, method, *args, **kwargs):
|
2022-07-23 17:33:23 +02:00
|
|
|
assert (
|
|
|
|
method in self.registered_actions
|
2023-02-04 00:26:48 +01:00
|
|
|
), f'{method} is not a registered action on {self.__class__.__name__}'
|
2017-12-13 04:14:46 +01:00
|
|
|
return getattr(self, method)(*args, **kwargs)
|
2017-12-13 03:37:28 +01:00
|
|
|
|
2017-10-31 09:20:35 +01:00
|
|
|
|
2021-09-16 17:53:40 +02:00
|
|
|
class RunnablePlugin(Plugin):
|
2021-07-22 01:02:15 +02:00
|
|
|
"""
|
|
|
|
Class for runnable plugins - i.e. plugins that have a start/stop method and can be started.
|
|
|
|
"""
|
2022-07-23 17:33:23 +02:00
|
|
|
|
2023-01-22 14:28:16 +01:00
|
|
|
def __init__(
|
|
|
|
self,
|
2023-03-03 02:00:48 +01:00
|
|
|
poll_interval: Optional[float] = 15,
|
2023-02-04 00:26:48 +01:00
|
|
|
stop_timeout: Optional[float] = PLUGIN_STOP_TIMEOUT,
|
2023-01-22 14:28:16 +01:00
|
|
|
**kwargs,
|
|
|
|
):
|
2021-07-22 01:02:15 +02:00
|
|
|
"""
|
2023-01-22 14:28:16 +01:00
|
|
|
:param poll_interval: How often the :meth:`.loop` function should be
|
2023-04-01 22:02:59 +02:00
|
|
|
execute (default: 15 seconds). *NOTE*: For back-compatibility
|
|
|
|
reasons, the `poll_seconds` argument is also supported, but it's
|
|
|
|
deprecated.
|
2023-01-22 14:28:16 +01:00
|
|
|
:param stop_timeout: How long we should wait for any running
|
|
|
|
threads/processes to stop before exiting (default: 5 seconds).
|
2021-07-22 01:02:15 +02:00
|
|
|
"""
|
|
|
|
super().__init__(**kwargs)
|
|
|
|
self.poll_interval = poll_interval
|
|
|
|
self.bus: Optional[Bus] = None
|
|
|
|
self._should_stop = threading.Event()
|
2023-01-22 14:28:16 +01:00
|
|
|
self._stop_timeout = stop_timeout
|
2021-07-22 01:02:15 +02:00
|
|
|
self._thread: Optional[threading.Thread] = None
|
|
|
|
|
2023-04-01 22:02:59 +02:00
|
|
|
if kwargs.get('poll_seconds') is not None:
|
|
|
|
warnings.warn(
|
|
|
|
'poll_seconds is deprecated, use poll_interval instead',
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=2,
|
|
|
|
)
|
|
|
|
|
|
|
|
if self.poll_interval is None:
|
|
|
|
self.poll_interval = kwargs['poll_seconds']
|
|
|
|
|
2021-07-22 01:02:15 +02:00
|
|
|
def main(self):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Implementation of the main loop of the plugin.
|
|
|
|
"""
|
2021-07-22 01:02:15 +02:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
2023-02-11 15:05:59 +01:00
|
|
|
def should_stop(self) -> bool:
|
2021-07-22 01:02:15 +02:00
|
|
|
return self._should_stop.is_set()
|
|
|
|
|
2022-07-23 17:33:23 +02:00
|
|
|
def wait_stop(self, timeout=None):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Wait until a stop event is received.
|
|
|
|
"""
|
2022-07-23 17:33:23 +02:00
|
|
|
return self._should_stop.wait(timeout=timeout)
|
|
|
|
|
2021-07-22 01:02:15 +02:00
|
|
|
def start(self):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Start the plugin.
|
|
|
|
"""
|
2023-02-08 00:46:50 +01:00
|
|
|
self._thread = threading.Thread(
|
|
|
|
target=self._runner, name=self.__class__.__name__
|
|
|
|
)
|
2021-07-22 01:02:15 +02:00
|
|
|
self._thread.start()
|
|
|
|
|
|
|
|
def stop(self):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Stop the plugin.
|
|
|
|
"""
|
2021-07-22 01:02:15 +02:00
|
|
|
self._should_stop.set()
|
2023-03-11 23:45:46 +01:00
|
|
|
if (
|
|
|
|
self._thread
|
|
|
|
and self._thread != threading.current_thread()
|
|
|
|
and self._thread.is_alive()
|
|
|
|
):
|
2023-02-08 00:46:50 +01:00
|
|
|
self.logger.info('Waiting for the plugin to stop')
|
2021-07-22 01:02:15 +02:00
|
|
|
try:
|
2022-03-27 16:14:30 +02:00
|
|
|
if self._thread:
|
2023-01-22 14:28:16 +01:00
|
|
|
self._thread.join(timeout=self._stop_timeout)
|
2023-01-27 22:12:34 +01:00
|
|
|
if self._thread and self._thread.is_alive():
|
2023-01-22 14:28:16 +01:00
|
|
|
self.logger.warning(
|
2023-02-08 00:46:50 +01:00
|
|
|
'Timeout (seconds=%s) on exit for the plugin',
|
2023-02-04 00:26:48 +01:00
|
|
|
self._stop_timeout,
|
2023-01-22 14:28:16 +01:00
|
|
|
)
|
2021-09-17 00:47:33 +02:00
|
|
|
except Exception as e:
|
2023-02-04 00:26:48 +01:00
|
|
|
self.logger.warning('Could not join thread on stop: %s', e)
|
2021-07-22 01:02:15 +02:00
|
|
|
|
2023-02-04 00:26:48 +01:00
|
|
|
self.logger.info('%s stopped', self.__class__.__name__)
|
2021-07-22 01:02:15 +02:00
|
|
|
|
|
|
|
def _runner(self):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Implementation of the runner thread.
|
|
|
|
"""
|
2023-02-04 00:26:48 +01:00
|
|
|
self.logger.info('Starting %s', self.__class__.__name__)
|
2021-07-22 01:02:15 +02:00
|
|
|
|
|
|
|
while not self.should_stop():
|
|
|
|
try:
|
|
|
|
self.main()
|
|
|
|
except Exception as e:
|
|
|
|
self.logger.exception(e)
|
|
|
|
|
|
|
|
if self.poll_interval:
|
2023-02-08 00:46:50 +01:00
|
|
|
self.wait_stop(self.poll_interval)
|
2021-07-22 01:02:15 +02:00
|
|
|
|
|
|
|
self._thread = None
|
|
|
|
|
|
|
|
|
2022-08-14 22:30:49 +02:00
|
|
|
class AsyncRunnablePlugin(RunnablePlugin, ABC):
|
|
|
|
"""
|
|
|
|
Class for runnable plugins with an asynchronous event loop attached.
|
|
|
|
"""
|
|
|
|
|
2023-01-22 14:28:16 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
2022-08-14 22:30:49 +02:00
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
2023-02-13 23:12:25 +01:00
|
|
|
self._loop: Optional[asyncio.AbstractEventLoop] = asyncio.new_event_loop()
|
2022-08-14 22:30:49 +02:00
|
|
|
self._task: Optional[asyncio.Task] = None
|
|
|
|
|
|
|
|
@property
|
|
|
|
def _should_start_runner(self):
|
2023-02-08 00:46:50 +01:00
|
|
|
"""
|
|
|
|
This property is used to determine if the runner and the event loop
|
|
|
|
should be started for this plugin.
|
|
|
|
"""
|
2022-08-14 22:30:49 +02:00
|
|
|
return True
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
async def listen(self):
|
2023-02-08 00:46:50 +01:00
|
|
|
"""
|
|
|
|
Main body of the async plugin. When it's called, the event loop should
|
|
|
|
already be running and available over `self._loop`.
|
|
|
|
"""
|
2022-08-14 22:30:49 +02:00
|
|
|
|
|
|
|
async def _listen(self):
|
2023-02-08 00:46:50 +01:00
|
|
|
"""
|
|
|
|
Wrapper for :meth:`.listen` that catches any exceptions and logs them.
|
|
|
|
"""
|
2022-08-14 22:30:49 +02:00
|
|
|
try:
|
|
|
|
await self.listen()
|
|
|
|
except KeyboardInterrupt:
|
|
|
|
pass
|
|
|
|
except RuntimeError as e:
|
|
|
|
if not (
|
|
|
|
str(e).startswith('Event loop stopped before ')
|
|
|
|
or str(e).startswith('no running event loop')
|
|
|
|
):
|
|
|
|
raise e
|
|
|
|
|
2023-02-08 00:46:50 +01:00
|
|
|
def _run_listener(self):
|
2023-02-11 15:05:59 +01:00
|
|
|
"""
|
|
|
|
Initialize an event loop and run the listener as a task.
|
|
|
|
"""
|
2022-08-14 22:30:49 +02:00
|
|
|
asyncio.set_event_loop(self._loop)
|
|
|
|
|
|
|
|
self._task = self._loop.create_task(self._listen())
|
2022-11-21 09:49:57 +01:00
|
|
|
if hasattr(self._task, 'set_name'):
|
|
|
|
self._task.set_name(self.__class__.__name__ + '.listen')
|
2023-02-08 00:46:50 +01:00
|
|
|
try:
|
|
|
|
self._loop.run_until_complete(self._task)
|
|
|
|
except Exception as e:
|
2023-02-19 23:03:27 +01:00
|
|
|
if not self.should_stop():
|
|
|
|
self.logger.warning('The loop has terminated with an error')
|
|
|
|
self.logger.exception(e)
|
2023-02-08 00:46:50 +01:00
|
|
|
|
|
|
|
self._task.cancel()
|
2022-08-14 22:30:49 +02:00
|
|
|
|
2023-02-11 15:05:59 +01:00
|
|
|
@override
|
2022-08-14 22:30:49 +02:00
|
|
|
def main(self):
|
2023-02-08 00:46:50 +01:00
|
|
|
if self.should_stop():
|
|
|
|
self.logger.info('The plugin is already scheduled to stop')
|
2022-08-14 22:30:49 +02:00
|
|
|
return
|
|
|
|
|
2023-02-08 00:46:50 +01:00
|
|
|
self._loop = asyncio.new_event_loop()
|
|
|
|
|
2022-08-14 22:30:49 +02:00
|
|
|
if self._should_start_runner:
|
2023-02-10 17:40:20 +01:00
|
|
|
while not self.should_stop():
|
|
|
|
try:
|
|
|
|
self._run_listener()
|
|
|
|
finally:
|
|
|
|
self.wait_stop(self.poll_interval)
|
|
|
|
else:
|
|
|
|
self.wait_stop()
|
2022-08-14 22:30:49 +02:00
|
|
|
|
2023-02-11 15:05:59 +01:00
|
|
|
@override
|
2022-08-14 22:30:49 +02:00
|
|
|
def stop(self):
|
|
|
|
if self._loop and self._loop.is_running():
|
|
|
|
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
|
|
self._loop = None
|
|
|
|
|
|
|
|
super().stop()
|
|
|
|
|
|
|
|
|
2017-10-31 09:20:35 +01:00
|
|
|
# vim:sw=4:ts=4:et:
|