Since this is a change to the table schema for all services using the ping adapter, you will have to delete the tables relating to them. - elstat.blueprints: add incidents blueprint (WIP) - elstat.blueprints: add decorators.py - elstat.blueprints: add errors.py - elstat.manager: add incidents & incident_stages tables - run: add handler for ApiError
84 lines
2.1 KiB
Python
84 lines
2.1 KiB
Python
import asyncio
|
|
import time
|
|
import re
|
|
|
|
PING_RGX = re.compile(r'(.+)( 0% packet loss)(.+)', re.I | re.M)
|
|
PING_LATENCY_RGX = re.compile('time\=(\d+(\.\d+)?) ms', re.M)
|
|
|
|
|
|
class Adapter:
|
|
spec = {
|
|
'db': None,
|
|
}
|
|
|
|
@classmethod
|
|
async def query(cls, _worker, _adp_args) -> tuple:
|
|
"""Main query function."""
|
|
raise NotImplementedError
|
|
|
|
|
|
class PingAdapter(Adapter):
|
|
"""Ping the given address and report if
|
|
any packet loss happened."""
|
|
spec = {
|
|
'db': ('timestamp', 'status', 'latency')
|
|
}
|
|
|
|
@classmethod
|
|
async def query(cls, worker, adp_args: dict):
|
|
process = await asyncio.create_subprocess_shell(
|
|
f'ping -c 1 {adp_args["address"]}',
|
|
stderr=asyncio.subprocess.PIPE,
|
|
stdout=asyncio.subprocess.PIPE,
|
|
)
|
|
|
|
out, err = map(lambda s: s.decode('utf-8'),
|
|
await process.communicate())
|
|
|
|
out += err
|
|
|
|
alive = bool(re.search(PING_RGX, out))
|
|
latency = PING_LATENCY_RGX.search(out)
|
|
|
|
if latency is not None:
|
|
num = latency.group(1)
|
|
try:
|
|
latency = int(num)
|
|
except ValueError:
|
|
try:
|
|
latency = max(float(num), 1)
|
|
except ValueError:
|
|
latency = 0
|
|
else:
|
|
latency = 0
|
|
|
|
worker.log.info(f'{worker.name}: alive? {alive} latency? {latency}ms')
|
|
return (alive, latency)
|
|
|
|
|
|
class HttpAdapter(Adapter):
|
|
"""Adapter to check if a certain
|
|
URL is giving 200."""
|
|
spec = {
|
|
'db': ('timestamp', 'status', 'latency')
|
|
}
|
|
|
|
@classmethod
|
|
async def query(cls, worker, adp_args: dict):
|
|
# yes, lots of attributes
|
|
session = worker.manager.app.session
|
|
|
|
t_start = time.monotonic()
|
|
resp = await session.get(f'{adp_args["url"]}')
|
|
t_end = time.monotonic()
|
|
|
|
latency = round((t_end - t_start) * 1000)
|
|
|
|
worker.log.info(f'{worker.name}: status={resp.status} '
|
|
f'latency={latency}ms')
|
|
|
|
if resp.status == 200:
|
|
return True, latency
|
|
|
|
# use 0ms drops as failures
|
|
return False, 0
|