2.21. Plugins#

aiomisc можно расширить с помощью плагинов в виде отдельных python пакетов. Плагины взаимодействуют с aiomisc с помощью signals.

Чтобы сделать ваш плагин доступным для обнаружения с помощью aiomisc, вы должны добавить запись aiomisc.plugins к записи аргумента entry_points вызова setup в setup.py вашего python пакета.

# setup.py

setup(
    # ...
    entry_points={
        "aiomisc": ["myplugin = aiomisc_myplugin.plugin"]
    },
    # ...
)

В случае pyproject.toml можно это описать вот-так:

[tool.poetry.plugins.aiomisc]
myplugin = "aiomisc_myplugin.plugin"

Модули, представленные в entry_points`, должны иметь функцию setup. Эти функции будут вызываться aiomisc и должны поддерживать сигналы.

Если сервисы запускаются динамически, присоединенные функции будут выполняться каждый раз при запуске и остановке служб, однако только те службы, которые в данный момент запускаются или останавливаются, будут в параметре services.

# Content of: ``aiomisc_myplugin/plugin.py``
from typing import Tuple
from threading import Event

import aiomisc


event = Event()
# Will be shown in ``python -m aiomisc.plugins``
__doc__ = "Example plugin"


async def hello(
    *,
    entrypoint: aiomisc.Entrypoint,
    services: Tuple[aiomisc.Service, ...]
) -> None:
    print('Hello from aiomisc plugin')
    event.set()


def setup() -> None:
    """
    This code will be called by loading plugins declared in
    ``pyproject.toml`` or ``setup.py``.
    """
    aiomisc.Entrypoint.PRE_START.connect(hello)

# Content of: ``my_plugin_example.py``
# ======================================================================
# The code below is not related to the plugin, but serves to demonstrate
# how it works.
# ======================================================================
def main():
    """ some function in user code """

    # This function will be called by aiomisc.plugin module
    # in this example it's just for demonstration.
    setup()

    assert not event.is_set()

    with aiomisc.entrypoint() as loop:
        pass

    assert event.is_set()

main()

# remove the plugin on when unneeded
aiomisc.entrypoint.PRE_START.disconnect(hello)

Список доступных сигналов такой:

  • Entrypoint.PRE_START - Запускается перед стартом сервисов.

  • Entrypoint.PRE_STOP - Запускается перед остановкой сервисов.

  • Entrypoint.POST_START - Запускается после старта сервисов.

  • Entrypoint.POST_STOP - Запускается после остановки сервисов

2.21.1. Список доступный плагинов#

Чтобы просмотреть список всех доступных плагинов, вы можете вызвать из командной строки python -m aiomisc.plugins:

$ python -m aiomisc.plugins
[11:14:42] INFO     Available 1 plugins.
           INFO     'systemd_watchdog' - Adds SystemD watchdog support to the entrypoint.
systemd_watchdog

Вы также можете изменить поведение и вывод списка модулей. Для этого существуют следующие флаги:

$ python3 -m aiomisc.plugins -h
usage: python3 -m aiomisc.plugins [-h] [-q] [-n]
                                  [-l {critical,error,warning,info,debug,notset}]
                                  [-F {stream,color,json,syslog,plain,journald,rich,rich_tb}]

optional arguments:
  -h, --help            show this help message and exit
  -q, -s, --quiet, --silent
                        Disable logs and just output plugin-list, alias for
                        --log-level=critical
  -n, --no-output       Disable output plugin-list to the stdout
  -l {critical,error,warning,info,debug,notset}, --log-level {critical,error,warning,info,debug,notset}
                        Logging level
  -F {stream,color,json,syslog,plain,journald,rich,rich_tb}, --log-format {stream,color,json,syslog,plain,journald,rich,rich_tb}
                        Logging format

Вот несколько примеров запуска.

$ python3 -m aiomisc.plugins -n
[12:25:57] INFO     Available 1 plugins.
           INFO     'systemd_watchdog' - Adds SystemD watchdog support to the entrypoint.

Этот пример, печатает удобочитаемый список плагинов и их описания.

$ python3 -m aiomisc.plugins -s
systemd_watchdog

Это полезно для grep или других утилит.

По умолчанию печатается человекочитаемый лог в stderr, и список плагинов в stdout, поэтому можно использовать это без параметров в конвейере, и прочитать список в stderr.