2020-04-18 20:52:27 +00:00
|
|
|
import subprocess
|
2020-04-14 22:49:22 +00:00
|
|
|
import re
|
|
|
|
import subprocess
|
2021-02-08 22:16:52 +00:00
|
|
|
from datetime import datetime, timedelta
|
2020-04-14 22:49:22 +00:00
|
|
|
|
|
|
|
import psutil
|
|
|
|
from peewee import *
|
|
|
|
from playhouse.shortcuts import model_to_dict
|
|
|
|
|
|
|
|
import config
|
|
|
|
from database import BaseModel
|
2020-04-14 22:52:07 +00:00
|
|
|
from plugins.plugin import Plugin
|
2020-04-14 22:49:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Ping(BaseModel):
|
2020-04-18 20:52:27 +00:00
|
|
|
time = DateTimeField(index=True, default=datetime.utcnow)
|
2020-04-14 22:49:22 +00:00
|
|
|
host = TextField(null=False)
|
|
|
|
ping = FloatField(null=True) # null = timeout or error
|
|
|
|
|
|
|
|
|
|
|
|
class PingPlugin(Plugin):
|
|
|
|
models = [Ping]
|
|
|
|
|
|
|
|
def __init__(self):
|
2020-04-18 20:52:27 +00:00
|
|
|
self.__timeout = 20
|
2020-04-17 16:16:58 +00:00
|
|
|
|
|
|
|
def get_interval(self):
|
|
|
|
return config.PING_INTERVAL
|
2020-04-14 22:49:22 +00:00
|
|
|
|
2020-04-18 20:52:27 +00:00
|
|
|
def do_ping(self, host):
|
2020-04-14 22:49:22 +00:00
|
|
|
command = ['ping', '-c', '1', '-W', str(self.__timeout), host]
|
2021-02-08 22:16:52 +00:00
|
|
|
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
|
|
|
|
ping = None
|
2020-04-14 22:49:22 +00:00
|
|
|
|
2021-02-08 22:16:52 +00:00
|
|
|
try:
|
|
|
|
proc.wait(60)
|
|
|
|
stdout = proc.stdout.read().decode()
|
|
|
|
|
|
|
|
match = re.search(r'time=([\d\.]+) ms', stdout)
|
|
|
|
if match is not None:
|
|
|
|
ping = float(match.group(1))
|
2020-04-14 22:49:22 +00:00
|
|
|
|
2021-02-08 22:16:52 +00:00
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
proc.kill()
|
2020-04-14 22:49:22 +00:00
|
|
|
|
2021-02-08 22:16:52 +00:00
|
|
|
entry = Ping()
|
|
|
|
entry.host = host
|
|
|
|
entry.ping = ping
|
2020-04-14 22:49:22 +00:00
|
|
|
entry.save()
|
|
|
|
|
|
|
|
def execute(self):
|
2020-04-18 20:52:27 +00:00
|
|
|
for host in config.PING_HOSTS:
|
|
|
|
self.do_ping(host)
|
2021-02-08 22:16:52 +00:00
|
|
|
|
|
|
|
def cleanup(self):
|
|
|
|
limit = datetime.utcnow() - timedelta(days=config.PING_RETAIN_DAYS)
|
|
|
|
return Ping.delete().where(Ping.time < limit).execute()
|