| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
"""Plugins for running Python code inside of the Cylc scheduler. |
| 17 |
|
| 18 |
.. _BuiltInPlugins: |
| 19 |
|
| 20 |
Built In Plugins |
| 21 |
---------------- |
| 22 |
|
| 23 |
Cylc Flow provides the following plugins: |
| 24 |
|
| 25 |
.. autosummary:: |
| 26 |
:toctree: built-in |
| 27 |
:template: main_loop_plugin.rst |
| 28 |
|
| 29 |
cylc.flow.main_loop.auto_restart |
| 30 |
cylc.flow.main_loop.health_check |
| 31 |
cylc.flow.main_loop.log_data_store |
| 32 |
cylc.flow.main_loop.log_main_loop |
| 33 |
cylc.flow.main_loop.log_memory |
| 34 |
cylc.flow.main_loop.reset_bad_hosts |
| 35 |
|
| 36 |
.. Note: Autosummary generates files in this directory, these are cleaned |
| 37 |
up by `make clean`. |
| 38 |
|
| 39 |
|
| 40 |
Configuring |
| 41 |
----------- |
| 42 |
|
| 43 |
Main loop plugins can be activated either by: |
| 44 |
|
| 45 |
* Using the ``--main-loop`` option with ``cylc play`` e.g: |
| 46 |
|
| 47 |
.. code-block:: console |
| 48 |
|
| 49 |
$ # run a workflow using the "health check" and "auto restart" plugins: |
| 50 |
$ cylc play my-workflow --main-loop 'health check' \ |
| 51 |
--main-loop 'auto restart' |
| 52 |
|
| 53 |
* Adding them to the default list of plugins in |
| 54 |
:cylc:conf:`global.cylc[scheduler][main loop]plugins` e.g: |
| 55 |
|
| 56 |
.. code-block:: cylc |
| 57 |
|
| 58 |
[scheduler] |
| 59 |
[[main loop]] |
| 60 |
plugins = health check, auto restart |
| 61 |
|
| 62 |
Main loop plugins can be individually configured in their |
| 63 |
:cylc:conf:`global.cylc[scheduler][main loop][<plugin name>]` section e.g: |
| 64 |
|
| 65 |
.. code-block:: cylc |
| 66 |
|
| 67 |
[scheduler] |
| 68 |
[[main loop]] |
| 69 |
[[[health check]]] |
| 70 |
interval = PT5M # perform check every 5 minutes |
| 71 |
|
| 72 |
|
| 73 |
Developing Main Loop Plugins |
| 74 |
---------------------------- |
| 75 |
|
| 76 |
Main loop plugins are Python modules containing asynchronous function(s) |
| 77 |
(sometimes referred to as coroutines) which Cylc Flow executes within the |
| 78 |
scheduler. |
| 79 |
|
| 80 |
Hello World |
| 81 |
^^^^^^^^^^^ |
| 82 |
|
| 83 |
Here is the "hello world" of main loop plugins: |
| 84 |
|
| 85 |
.. code-block:: python |
| 86 |
:caption: my_plugin.py |
| 87 |
|
| 88 |
from cylc.flow import LOG |
| 89 |
from cylc.flow.main_loop import startup |
| 90 |
|
| 91 |
@startup |
| 92 |
async def my_startup_coroutine(schd, state): |
| 93 |
# write Hello <workflow name> to the Cylc log. |
| 94 |
LOG.info(f'Hello {schd.workflow}') |
| 95 |
|
| 96 |
Plugins are registered by registering them with the ``cylc.main_loop`` |
| 97 |
entry point: |
| 98 |
|
| 99 |
.. code-block:: python |
| 100 |
:caption: setup.py |
| 101 |
|
| 102 |
# plugins must be properly installed, in-place PYTHONPATH meddling will |
| 103 |
# not work. |
| 104 |
|
| 105 |
from setuptools import setup |
| 106 |
|
| 107 |
setup( |
| 108 |
name='my-plugin', |
| 109 |
version='1.0', |
| 110 |
py_modules=['my_plugin'], |
| 111 |
entry_points={ |
| 112 |
# register this plugin with Cylc |
| 113 |
'cylc.main_loop': [ |
| 114 |
# name = python.namespace.of.module |
| 115 |
'my_plugin=my_plugin.my_plugin' |
| 116 |
] |
| 117 |
} |
| 118 |
) |
| 119 |
|
| 120 |
Examples |
| 121 |
^^^^^^^^ |
| 122 |
|
| 123 |
For examples see the built-in plugins in the :py:mod:`cylc.flow.main_loop` |
| 124 |
module which are registered in the Cylc Flow ``setup.cfg`` file. |
| 125 |
|
| 126 |
Coroutines |
| 127 |
^^^^^^^^^^ |
| 128 |
|
| 129 |
.. _coroutines: https://docs.python.org/3/library/asyncio-task.html#coroutines |
| 130 |
|
| 131 |
Plugins provide asynchronous functions (`coroutines`_) which Cylc will |
| 132 |
then run inside the scheduler. |
| 133 |
|
| 134 |
Coroutines should be fast running (read as gentle on the scheduler) |
| 135 |
and perform IO asynchronously. |
| 136 |
|
| 137 |
Coroutines shouldn't meddle with the state of the scheduler and should be |
| 138 |
parallel-safe with other plugins. |
| 139 |
|
| 140 |
Event Types |
| 141 |
^^^^^^^^^^^ |
| 142 |
|
| 143 |
Coroutines must be decorated using one of the main loop decorators. The |
| 144 |
choice of decorator effects when the coroutine is called and what |
| 145 |
arguments are provided to it. |
| 146 |
|
| 147 |
The available event types are: |
| 148 |
|
| 149 |
.. autofunction:: cylc.flow.main_loop.startup |
| 150 |
|
| 151 |
.. autofunction:: cylc.flow.main_loop.shutdown |
| 152 |
|
| 153 |
.. autofunction:: cylc.flow.main_loop.periodic |
| 154 |
|
| 155 |
""" |
| 156 |
from collections import deque |
| 157 |
from inspect import ( |
| 158 |
getmembers, |
| 159 |
isfunction |
| 160 |
) |
| 161 |
from textwrap import indent |
| 162 |
from time import time |
| 163 |
|
| 164 |
from cylc.flow import LOG, iter_entry_points |
| 165 |
from cylc.flow.exceptions import CylcError, InputError, PluginError |
| 166 |
|
| 167 |
|
| 168 |
class MainLoopPluginException(Exception): |
| 169 |
"""Raised in-place of CylcError exceptions. |
| 170 |
|
| 171 |
Note: |
| 172 |
* Not an instace of CylcError as that is used for controlled |
| 173 |
shutdown e.g. SchedulerStop. |
| 174 |
|
| 175 |
""" |
| 176 |
|
| 177 |
|
| 178 |
async def _wrapper(fcn, scheduler, state, timings=None): |
| 179 |
"""Wrapper for all plugin functions. |
| 180 |
|
| 181 |
* Logs the function's execution. |
| 182 |
* Times the function. |
| 183 |
* Catches any exceptions which aren't subclasses of CylcError. |
| 184 |
|
| 185 |
""" |
| 186 |
sig = f'{fcn.__module__}:{fcn.__name__}' |
| 187 |
LOG.debug(f'main_loop [run] {sig}') |
| 188 |
start_time = time() |
| 189 |
try: |
| 190 |
await fcn(scheduler, state) |
| 191 |
except CylcError as exc: |
| 192 |
# allow CylcErrors through (e.g. SchedulerStop) |
| 193 |
# NOTE: the `from None` bit gets rid of this gunk: |
| 194 |
# > During handling of the above exception another exception |
| 195 |
raise MainLoopPluginException(exc) from None |
| 196 |
except Exception as exc: |
| 197 |
LOG.error(f'Error in main loop plugin {sig}') |
| 198 |
LOG.exception(exc) |
| 199 |
duration = time() - start_time |
| 200 |
LOG.debug(f'main_loop [end] {sig} ({duration:.3f}s)') |
| 201 |
if timings is not None: |
| 202 |
timings.append((start_time, duration)) |
| 203 |
|
| 204 |
|
| 205 |
def _debounce(interval, timings): |
| 206 |
"""Rate limiter, returns True if the interval has elapsed. |
| 207 |
|
| 208 |
Arguments: |
| 209 |
interval (float): |
| 210 |
Time interval in seconds as a float-type object. |
| 211 |
timings (list): |
| 212 |
List-list object of the timings of previous runs in the form |
| 213 |
``(completion_wallclock_time, run_duration)``. |
| 214 |
Wallclock times are unix epoch times in seconds. |
| 215 |
|
| 216 |
Examples: |
| 217 |
>>> from time import time |
| 218 |
|
| 219 |
No previous run (should always return True): |
| 220 |
>>> _debounce(1., [(0, 0)]) |
| 221 |
True |
| 222 |
|
| 223 |
Interval not yet elapsed since previous run: |
| 224 |
>>> _debounce(1., [(time(), 0)]) |
| 225 |
False |
| 226 |
|
| 227 |
Interval has elapsed since previous run: |
| 228 |
>>> _debounce(1., [(time() - 2, 0)]) |
| 229 |
True |
| 230 |
|
| 231 |
""" |
| 232 |
if not interval: |
| 233 |
return True |
| 234 |
try: |
| 235 |
last_run_at = timings[-1][0] |
| 236 |
except IndexError: |
| 237 |
last_run_at = 0 |
| 238 |
if (time() - last_run_at) > interval: |
| 239 |
return True |
| 240 |
return False |
| 241 |
|
| 242 |
|
| 243 |
def startup(fcn): |
| 244 |
"""Decorates a coroutine which is run at workflow startup. |
| 245 |
|
| 246 |
The decorated coroutine should have the signature: |
| 247 |
|
| 248 |
``async coroutine(scheduler, plugin_state) -> None`` |
| 249 |
|
| 250 |
Exceptions: |
| 251 |
|
| 252 |
* Regular Exceptions are caught and logged. |
| 253 |
* Exceptions which subclass CylcError are re-raised as |
| 254 |
MainLoopPluginException |
| 255 |
|
| 256 |
""" |
| 257 |
fcn.main_loop = CoroTypes.StartUp |
| 258 |
return fcn |
| 259 |
|
| 260 |
|
| 261 |
def shutdown(fcn): |
| 262 |
"""Decorates a coroutine which is run at workflow shutdown. |
| 263 |
|
| 264 |
Note shutdown refers to "clean" shutdown as opposed to workflow abort. |
| 265 |
|
| 266 |
The decorated coroutine should have the signature: |
| 267 |
|
| 268 |
``async coroutine(scheduler, plugin_state) -> None`` |
| 269 |
|
| 270 |
Exceptions: |
| 271 |
|
| 272 |
* Regular Exceptions are caught and logged. |
| 273 |
* Exceptions which subclass CylcError are re-raised as |
| 274 |
MainLoopPluginException |
| 275 |
|
| 276 |
""" |
| 277 |
fcn.main_loop = CoroTypes.ShutDown |
| 278 |
return fcn |
| 279 |
|
| 280 |
|
| 281 |
def periodic(fcn): |
| 282 |
"""Decorates a coroutine which is run at a set interval. |
| 283 |
|
| 284 |
The decorated coroutine should have the signature: |
| 285 |
|
| 286 |
``async coroutine(scheduler, plugin_state) -> None`` |
| 287 |
|
| 288 |
Exceptions: |
| 289 |
|
| 290 |
* Regular Exceptions are caught and logged. |
| 291 |
* Exceptions which subclass CylcError are re-raised as |
| 292 |
MainLoopPluginException |
| 293 |
|
| 294 |
Configuration: |
| 295 |
|
| 296 |
* The interval of execution can be altered using |
| 297 |
:cylc:conf:`global.cylc[scheduler][main loop][<plugin name>]interval` |
| 298 |
|
| 299 |
""" |
| 300 |
fcn.main_loop = CoroTypes.Periodic |
| 301 |
return fcn |
| 302 |
|
| 303 |
|
| 304 |
class CoroTypes: |
| 305 |
"""Different types of coroutine which can be used with the main loop.""" |
| 306 |
|
| 307 |
StartUp = startup |
| 308 |
ShutDown = shutdown |
| 309 |
Periodic = periodic |
| 310 |
|
| 311 |
|
| 312 |
def load(config, additional_plugins=None): |
| 313 |
additional_plugins = additional_plugins or [] |
| 314 |
entry_points = { |
| 315 |
entry_point.name: entry_point |
| 316 |
for entry_point in |
| 317 |
iter_entry_points('cylc.main_loop') |
| 318 |
} |
| 319 |
plugins = { |
| 320 |
'state': {}, |
| 321 |
'timings': {} |
| 322 |
} |
| 323 |
for plugin_name in set(config['plugins'] + additional_plugins): |
| 324 |
# get plugin |
| 325 |
try: |
| 326 |
entry_point = entry_points[plugin_name.replace(' ', '_')] |
| 327 |
except KeyError: |
| 328 |
raise InputError( |
| 329 |
f'No main-loop plugin: "{plugin_name}"\n' |
| 330 |
+ ' Available plugins:\n' |
| 331 |
+ indent('\n'.join(sorted(entry_points)), ' ') |
| 332 |
) from None |
| 333 |
# load plugin |
| 334 |
try: |
| 335 |
module = entry_point.load() |
| 336 |
except Exception as exc: |
| 337 |
raise PluginError( |
| 338 |
'cylc.main_loop', entry_point.name, exc |
| 339 |
) from None |
| 340 |
# load coroutines |
| 341 |
log = [] |
| 342 |
for coro_name, coro in getmembers(module): |
| 343 |
if isfunction(coro) and hasattr(coro, 'main_loop'): |
| 344 |
log.append(coro_name) |
| 345 |
plugins.setdefault( |
| 346 |
coro.main_loop, {} |
| 347 |
)[(plugin_name, coro_name)] = coro |
| 348 |
plugins['timings'][(plugin_name, coro_name)] = deque(maxlen=1) |
| 349 |
LOG.debug( |
| 350 |
'Loaded main loop plugin "%s":\n%s', |
| 351 |
plugin_name, |
| 352 |
'\n'.join(f'* {x}' for x in log) |
| 353 |
) |
| 354 |
# set the initial state of the plugin |
| 355 |
plugins['state'][plugin_name] = {} |
| 356 |
# make a note of the config here for ease of reference |
| 357 |
plugins['config'] = config |
| 358 |
return plugins |
| 359 |
|
| 360 |
|
| 361 |
def get_runners(plugins, coro_type, scheduler): |
| 362 |
return [ |
| 363 |
_wrapper( |
| 364 |
coro, |
| 365 |
scheduler, |
| 366 |
plugins['state'][plugin_name], |
| 367 |
timings=plugins['timings'][(plugin_name, coro_name)] |
| 368 |
) |
| 369 |
for (plugin_name, coro_name), coro |
| 370 |
in plugins.get(coro_type, {}).items() |
| 371 |
if coro_type != CoroTypes.Periodic |
| 372 |
or _debounce( |
| 373 |
plugins['config'].get(plugin_name, {}).get('interval', None), |
| 374 |
plugins['timings'][(plugin_name, coro_name)] |
| 375 |
) |
| 376 |
] |