56 lines
2.4 KiB
Python
56 lines
2.4 KiB
Python
"""Switch one Uptime Kuma maintenance window on and off (Kuma 2.x, over its Socket.IO API).
|
|||
|
|
|
||
|
|
Kuma has no REST API for maintenance, so this logs in over the same socket its web UI
|
||
|
|
uses. It only ever resumes or pauses the one window named in config, which is created
|
||
|
|
once in Kuma ("manual" strategy, covering the monitors that a modem restart takes down):
|
||
|
|
|
||
|
|
"uptime_kuma": {"url": "http://10.10.10.25:3001", "username": "...", "password": "...",
|
||
|
|
"maintenance_id": 7}
|
||
|
|
|
||
|
|
Nothing else in Kuma is read or changed.
|
||
|
|
"""
|
||
|
|
import logging
|
||
|
|
from typing import Callable, Optional
|
||
|
|
|
||
|
|
import socketio
|
||
|
|
|
||
|
|
logger = logging.getLogger('gandalf.kuma')
|
||
|
|
|
||
|
|
|
||
|
|
class KumaError(Exception):
|
||
|
|
"""Kuma couldn't be reached, refused the login, or refused the change."""
|
||
|
|
|
||
|
|
|
||
|
|
def configured(cfg: Optional[dict]) -> bool:
|
||
|
|
cfg = cfg or {}
|
||
|
|
return all(cfg.get(k) for k in ('url', 'username', 'password', 'maintenance_id'))
|
||
|
|
|
||
|
|
|
||
|
|
def set_maintenance(cfg: dict, active: bool, client_factory: Optional[Callable] = None) -> None:
|
||
|
|
"""Resume (active=True) or pause the configured maintenance window. Raises KumaError."""
|
||
|
|
timeout = cfg.get('timeout', 10)
|
||
|
|
factory = client_factory or (lambda: socketio.Client(
|
||
|
|
reconnection=False, ssl_verify=cfg.get('verify_ssl', True)))
|
||
|
|
sio = factory()
|
||
|
|
try:
|
||
|
|
sio.connect(cfg['url'], transports=['websocket'], wait_timeout=timeout)
|
||
|
|
res = sio.call('login', {'username': cfg['username'], 'password': cfg['password'], 'token': ''},
|
||
|
|
timeout=timeout) or {}
|
||
|
|
if not res.get('ok'):
|
||
|
|
if res.get('tokenRequired'):
|
||
|
|
raise KumaError('the Kuma account has two-factor login, which Gandalf cannot answer')
|
||
|
|
raise KumaError(f'login refused: {res.get("msg") or "no reason given"}')
|
||
|
|
event = 'resumeMaintenance' if active else 'pauseMaintenance'
|
||
|
|
res = sio.call(event, int(cfg['maintenance_id']), timeout=timeout) or {}
|
||
|
|
if not res.get('ok'):
|
||
|
|
raise KumaError(f'{event} refused: {res.get("msg") or "no reason given"}')
|
||
|
|
logger.info(f'Uptime Kuma maintenance {cfg["maintenance_id"]} {"on" if active else "off"}')
|
||
|
|
except KumaError:
|
||
|
|
raise
|
||
|
|
except Exception as e: # socketio raises its own errors and plain timeouts
|
||
|
|
raise KumaError(f'{type(e).__name__}: {e}') from e
|
||
|
|
finally:
|
||
|
|
try:
|
||
|
|
sio.disconnect()
|
||
|
|
except Exception: # nosec B110 - nothing left to clean up
|
||
|
|
pass
|