monitoring/obsdsnmp/__init__.py

85 lines
2.0 KiB
Python

# coding: utf-8
"""Command line interface."""
import asyncio
import logging
from typing import Optional, Tuple
import click
from pysnmp.hlapi.asyncio import SnmpEngine
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
try:
import uvloop # noqa: WPS433
except ImportError:
logging.info('For performance boost install uvloop')
else:
uvloop.install()
DEFAULT_INTERVAL = 10.0
async def worker(
interval: float,
host: str,
db_engine: Optional[AsyncEngine],
):
"""Connect to host, gather metrics and store to database.
Args:
interval: seconds to wait between iterations.
host: hostname or IP of the host.
db_engine: SQLAlchemy Engine object.
"""
snmp_engine = SnmpEngine()
while True:
print(host)
await asyncio.sleep(interval)
async def scheduler(interval: float, dsn: str, hosts: Tuple[str]):
"""Schdule async worker for each host.
Args:
interval: seconds to wait between iterations.
dsn: SQLAlchemy connection string.
hosts: hosts to monitor.
"""
db_engine = None
if dsn:
db_engine = create_async_engine(dsn, echo='debug', future=True)
async with db_engine.begin() as conn:
# await conn.run_sync(meta.drop_all)
# await conn.run_sync(meta.create_all)
pass
await asyncio.gather(
*(worker(interval, host, db_engine) for host in hosts),
)
@click.command()
@click.option(
'-i',
'--interval',
type=click.FloatRange(0, min_open=True),
default=DEFAULT_INTERVAL,
help='Collect metrics every interval seconds.',
show_default=True,
)
@click.option(
'-d',
'--dsn',
help='DSN connection string to store metrics.',
show_default=True,
)
@click.argument('hosts', nargs=-1, required=True)
def command(*args, **kwargs):
"""Collect OpenBSD SNMP metrics from HOST.
Multiple hosts can be specified with spaces.
""" # noqa: DAR101
asyncio.run(scheduler(*args, **kwargs))