200 lines
9.6 KiB
Python
200 lines
9.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Local DSM collector and authenticated HOMELAB API. Python 3 standard library."""
|
|
import argparse
|
|
import glob
|
|
import hmac
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
STATIC = Path(__file__).parent / 'static'
|
|
|
|
def read(path):
|
|
try:
|
|
return Path(path).read_text().strip()
|
|
except OSError:
|
|
return ''
|
|
|
|
def run(args):
|
|
try:
|
|
p = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
universal_newlines=True, timeout=25, env=dict(os.environ, LC_ALL='C'))
|
|
return p.returncode, p.stdout
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return -1, ''
|
|
|
|
def executable(name, paths):
|
|
return next((p for p in paths if os.access(p, os.X_OK)), shutil.which(name))
|
|
|
|
def smart(text, code):
|
|
match = re.search(r'(?:overall-health self-assessment test result|Health Status):\s*(.+)', text)
|
|
status = 'Unbekannt'
|
|
if match and code >= 0 and not code & 7:
|
|
status = 'OK' if match[1].strip() in ('PASSED', 'OK') else 'Warnung'
|
|
if code & 248:
|
|
status = 'Warnung'
|
|
temp = re.search(r'^\s*194\s+\S+\s+(?:\S+\s+){7}(\d+)', text, re.M)
|
|
if not temp:
|
|
temp = re.search(r'(?:Temperature|Current Drive Temperature):\s*(\d+)', text)
|
|
return {'status': status, 'temperature': int(temp[1]) if temp else None}
|
|
|
|
class Collector:
|
|
def __init__(self):
|
|
self.lock = threading.Lock()
|
|
self.previous = None
|
|
self.storage = {}
|
|
self.storage_time = 0
|
|
|
|
def disks_and_pools(self):
|
|
disks = []
|
|
binary = executable('smartctl', ['/usr/syno/bin/smartctl', '/usr/sbin/smartctl'])
|
|
for path in sorted(glob.glob('/sys/block/*')):
|
|
name = Path(path).name
|
|
if not re.fullmatch(r'(sd[a-z]+|sata\d+|nvme\d+n\d+)', name):
|
|
continue
|
|
code, output = run([binary, '-n', 'standby', '-a', '/dev/' + name]) if binary else (-1, '')
|
|
disks.append(dict(name=name, model=read(path + '/device/model') or name, **smart(output, code)))
|
|
raids = []
|
|
for path in sorted(glob.glob('/sys/block/md*/md')):
|
|
name = Path(path).parent.name
|
|
if name in ('md0', 'md1'):
|
|
continue
|
|
degraded = read(path + '/degraded')
|
|
raids.append({'name': name, 'level': read(path + '/level'),
|
|
'status': ('Warnung' if int(degraded) else 'OK') if degraded.isdigit() else 'Unbekannt',
|
|
'action': read(path + '/sync_action') or 'Unbekannt'})
|
|
pools = []
|
|
vgs = executable('vgs', ['/sbin/vgs', '/usr/sbin/vgs'])
|
|
if vgs:
|
|
code, output = run([vgs, '--noheadings', '--units', 'b', '--nosuffix', '--separator', '|', '-o', 'vg_name,vg_size,vg_free'])
|
|
if code == 0:
|
|
for line in output.splitlines():
|
|
fields = line.strip().split('|')
|
|
try:
|
|
pools.append({'name': fields[0].strip(), 'total': float(fields[1]), 'free': float(fields[2])})
|
|
except (ValueError, IndexError):
|
|
pass
|
|
volumes = []
|
|
for path in sorted(glob.glob('/volume[0-9]*')):
|
|
if not re.fullmatch(r'/volume\d+', path) or not os.path.ismount(path):
|
|
continue
|
|
usage = shutil.disk_usage(path)
|
|
volumes.append(dict(name=path, total=usage.total, free=usage.free))
|
|
return dict(disks=disks, raids=raids, pools=pools, volumes=volumes)
|
|
|
|
def sample(self):
|
|
with self.lock:
|
|
now = time.monotonic()
|
|
cpu_line = read('/proc/stat').splitlines()
|
|
cpu = [int(x) for x in cpu_line[0].split()[1:9]] if cpu_line else []
|
|
net = {}
|
|
for path in sorted(glob.glob('/sys/class/net/*')):
|
|
name = Path(path).name
|
|
# Physical links only: avoids counting bonds/bridges and members twice.
|
|
if not os.path.exists(path + '/device'):
|
|
continue
|
|
rx, tx = read(path + '/statistics/rx_bytes'), read(path + '/statistics/tx_bytes')
|
|
if rx.isdigit() and tx.isdigit():
|
|
net[name] = (int(rx), int(tx), read(path + '/operstate'))
|
|
load, interfaces = None, []
|
|
if self.previous:
|
|
before, old_cpu, old_net = self.previous
|
|
if cpu and old_cpu:
|
|
total = sum(cpu) - sum(old_cpu)
|
|
idle = sum(cpu[3:5]) - sum(old_cpu[3:5])
|
|
load = round(max(0, min(100, 100 * (1 - idle / total))), 1) if total > 0 else None
|
|
for name, (rx, tx, state) in net.items():
|
|
old = old_net.get(name)
|
|
interfaces.append(dict(name=name, status=state,
|
|
down=max(0, rx-old[0]) / (now-before) if old else None,
|
|
up=max(0, tx-old[1]) / (now-before) if old else None))
|
|
else:
|
|
interfaces = [dict(name=n, status=v[2], down=None, up=None) for n,v in net.items()]
|
|
self.previous = now, cpu, net
|
|
mem = dict((k, int(v)*1024) for k,v in re.findall(r'^(\w+):\s+(\d+)', read('/proc/meminfo'), re.M))
|
|
ram = dict(total=mem.get('MemTotal'), free=mem.get('MemAvailable'))
|
|
if now-self.storage_time > 60 or not self.storage:
|
|
self.storage = self.disks_and_pools()
|
|
self.storage_time = now
|
|
dns_pid = read('/var/packages/DNSServer/target/var/named.pid')
|
|
dns = 'Läuft' if dns_pid.isdigit() and Path('/proc/' + dns_pid).exists() else 'Unbekannt'
|
|
return dict(cpu=load, ram=ram, interfaces=interfaces, dns=dns,
|
|
timestamp=time.time(), storage_age=round(now-self.storage_time), **self.storage)
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--host', default='127.0.0.1')
|
|
parser.add_argument('--port', type=int, default=8787)
|
|
parser.add_argument('--demo', action='store_true')
|
|
args = parser.parse_args()
|
|
token = os.environ.get('HOMELAB_TOKEN', '')
|
|
if not args.demo and len(token) < 24:
|
|
parser.error('HOMELAB_TOKEN muss mindestens 24 Zeichen enthalten.')
|
|
collector = Collector()
|
|
restart_lock = threading.Lock()
|
|
last_restart = [0]
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def reply(self, status, data, kind='application/json'):
|
|
body = json.dumps(data).encode() if kind == 'application/json' else data
|
|
self.send_response(status)
|
|
self.send_header('Content-Type', kind + '; charset=utf-8')
|
|
self.send_header('Content-Length', str(len(body)))
|
|
self.send_header('Cache-Control', 'no-store')
|
|
self.send_header('X-Content-Type-Options', 'nosniff')
|
|
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'none'; base-uri 'none'")
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def authorized(self):
|
|
return hmac.compare_digest(self.headers.get('Authorization', ''), 'Bearer ' + token) and bool(token)
|
|
|
|
def do_GET(self):
|
|
if self.path == '/api/status':
|
|
if args.demo:
|
|
return self.reply(200, {'demo': True})
|
|
if not self.authorized():
|
|
return self.reply(401, {'error': 'Zugriffsschlüssel erforderlich.'})
|
|
try:
|
|
data = collector.sample()
|
|
data['can_restart'] = os.environ.get('HOMELAB_ALLOW_DNS_RESTART') == '1'
|
|
return self.reply(200, data)
|
|
except Exception:
|
|
return self.reply(503, {'error': 'Messwerte konnten nicht gelesen werden.'})
|
|
files = {'/': ('index.html','text/html'), '/dsm': ('index.html','text/html'),
|
|
'/app.js': ('app.js','text/javascript'), '/style.css': ('style.css','text/css')}
|
|
if self.path not in files:
|
|
return self.reply(404, {'error': 'Nicht gefunden'})
|
|
name, kind = files[self.path]
|
|
self.reply(200, (STATIC/name).read_bytes(), kind)
|
|
|
|
def do_POST(self):
|
|
if self.path != '/api/dns/restart':
|
|
return self.reply(404, {'error': 'Nicht gefunden'})
|
|
if args.demo or not self.authorized():
|
|
return self.reply(403, {'error': 'Neustart nicht freigegeben.'})
|
|
if os.environ.get('HOMELAB_ALLOW_DNS_RESTART') != '1':
|
|
return self.reply(403, {'error': 'DNS-Neustart muss auf dem NAS aktiviert werden.'})
|
|
if not restart_lock.acquire(blocking=False):
|
|
return self.reply(409, {'error': 'Neustart läuft bereits.'})
|
|
try:
|
|
if time.monotonic()-last_restart[0] < 60:
|
|
return self.reply(429, {'error': 'Bitte 60 Sekunden zwischen Neustarts warten.'})
|
|
last_restart[0] = time.monotonic()
|
|
code, _ = run(['/usr/syno/bin/synopkg', 'restart', 'DNSServer'])
|
|
self.reply(200 if code == 0 else 503, {'message': 'Neustartbefehl erfolgreich ausgeführt. Dienststatus in DSM prüfen.'} if code == 0 else {'error': 'Neustart fehlgeschlagen oder Zeitlimit erreicht. Dienststatus in DSM prüfen.'})
|
|
finally:
|
|
restart_lock.release()
|
|
|
|
httpd = ThreadingHTTPServer((args.host, args.port), Handler)
|
|
print('HOMELAB: http://%s:%s%s' % (args.host, args.port, ' (DEMO)' if args.demo else ''), flush=True)
|
|
httpd.serve_forever()
|
|
|
|
if __name__ == '__main__':
|
|
main()
|