lecturehalls-dashboard/devicecheck.py
2024-09-09 11:41:02 +02:00

96 lines
3.0 KiB
Python

#!/usr/bin/env python3
import subprocess
from datetime import datetime
import mysql.connector as sql
from mysql.connector import IntegrityError
import requests
class Checker:
def __init__(self, config):
self.apisession = requests.Session()
self.apisession.auth = (config['deviceapi']['user'],
config['deviceapi']['pass'])
self.apisession.headers = {'Accept': 'application/json',
'Content-Type': 'application/json'}
self.apiurl = config['deviceapi']['url']
if self.apiurl.endswith('/'):
self.apiurl = self.apiurl[:-1]
self.dbparameters = {
'host': config['database']['host'],
'port': config['database']['port'],
'database': config['database']['database'],
'user': config['database']['user'],
'password': config['database']['pass'],
}
def _do_request(self, path):
response = self.apisession.get(self.apiurl + path)
response.raise_for_status()
return response.json()
def check_all(self):
hostcache = set()
for item in self._do_request('/config/devices'):
if 'host' in item:
hostcache.add(item['host'])
for host in hostcache:
result = self.ping(host)
self.store(host, result)
if result.returncode == 0:
print(f'{host} OK')
else:
print(f'{host}: {result.returncode} - {result.stderr}')
self._prune_db()
def ping(self, host):
# Ping settings:
# - send 3 packets
# - wait 0.5 seconds between packets
# - timeout each packet after 1 second
# - timeout entire operation after 5 seconds
command = ['ping', '-q',
'-c', '3',
'-i', '0.5',
'-W', '1',
'-w', '5',
host]
return subprocess.run(command, capture_output=True, text=True)
def _prune_db(self):
stmt = 'delete from `results`'
stmt += 'where `timestamp` < unix_timestamp(date_sub(now(), interval 30 day))'
with sql.connect(**self.dbparameters) as db:
with db.cursor() as cursor:
cursor.execute(stmt)
db.commit()
def store(self, host, result):
now = datetime.now().timestamp()
stmt = 'insert into `results`'
stmt += '(`host`, `timestamp`, `returncode`, `detail`)'
stmt += 'values(%s, %s, %s, %s)'
with sql.connect(**self.dbparameters) as db:
with db.cursor() as cursor:
cursor.execute(stmt, (host,
now,
result.returncode,
result.stderr))
db.commit()
if __name__ == '__main__':
from configparser import ConfigParser
conf = ConfigParser()
conf.read('config.ini')
checker = Checker(conf)
checker.check_all()