1
|
|
|
import asyncio |
2
|
|
|
import logging |
3
|
|
|
|
4
|
|
|
from cached_property import cached_property |
5
|
|
|
|
6
|
|
|
from .dispatchers import LoaferDispatcher |
|
|
|
|
7
|
|
|
from .exceptions import ConfigurationError |
8
|
|
|
from .routes import Route |
|
|
|
|
9
|
|
|
from .runners import LoaferRunner |
10
|
|
|
|
11
|
|
|
logger = logging.getLogger(__name__) |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
class LoaferManager: |
15
|
|
|
|
16
|
|
|
def __init__(self, routes, runner=None, _concurrency_limit=None, _max_threads=None): |
17
|
|
|
self._concurrency_limit = _concurrency_limit |
18
|
|
|
if runner is None: |
19
|
|
|
self.runner = LoaferRunner(on_stop_callback=self.on_loop__stop, max_workers=_max_threads) |
20
|
|
|
else: |
21
|
|
|
self.runner = runner |
22
|
|
|
|
23
|
|
|
self.routes = routes |
24
|
|
|
|
25
|
|
|
@cached_property |
26
|
|
|
def dispatcher(self): |
27
|
|
|
if not (self.routes and all(isinstance(r, Route) for r in self.routes)): |
28
|
|
|
raise ConfigurationError('invalid routes to dispatch, routes={}'.format(self.routes)) |
29
|
|
|
|
30
|
|
|
if not any(r.enabled for r in self.routes): |
31
|
|
|
raise ConfigurationError('all routes are disabled, routes={}'.format(self.routes)) |
32
|
|
|
|
33
|
|
|
return LoaferDispatcher(self.routes, max_jobs=self._concurrency_limit) |
34
|
|
|
|
35
|
|
|
def run(self, forever=True): |
36
|
|
|
loop = self.runner.loop |
37
|
|
|
self._future = asyncio.ensure_future( |
|
|
|
|
38
|
|
|
self.dispatcher.dispatch_providers(loop, forever=forever), |
39
|
|
|
loop=loop, |
40
|
|
|
) |
41
|
|
|
self._future.add_done_callback(self.on_future__errors) |
42
|
|
|
self.runner.start(self._future, run_forever=forever) |
43
|
|
|
|
44
|
|
|
# |
45
|
|
|
# Callbacks |
46
|
|
|
# |
47
|
|
|
|
48
|
|
|
def on_future__errors(self, future): |
49
|
|
|
exc = future.exception() |
50
|
|
|
# Unhandled errors crashes the event loop execution |
51
|
|
|
if isinstance(exc, BaseException): |
52
|
|
|
logger.critical('fatal error caught: {!r}'.format(exc)) |
53
|
|
|
self.runner.stop() |
54
|
|
|
|
55
|
|
|
def on_loop__stop(self, *args, **kwargs): |
|
|
|
|
56
|
|
|
logger.info('cancel schedulled operations ...') |
57
|
|
|
for task in asyncio.Task.all_tasks(self.runner.loop): |
58
|
|
|
logger.debug('cancelling {}'.format(task)) |
59
|
|
|
task.cancel() |
60
|
|
|
|
61
|
|
|
if hasattr(self, '_future'): |
62
|
|
|
self._future.cancel() |
63
|
|
|
|
64
|
|
|
self.dispatcher.stop() |
65
|
|
|
|
This can be caused by one of the following:
1. Missing Dependencies
This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.
2. Missing __init__.py files
This error could also result from missing
__init__.py
files in your module folders. Make sure that you place one file in each sub-folder.