"""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 signs 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", "token": "...", "maintenance_id": 7} `token` is a Kuma session token (works with a two-factor account; it stops working if the Kuma password changes). `username` and `password` are accepted instead for an account without two-factor login. Nothing else in Kuma is read or changed. """ import logging import threading from typing import Callable, Optional import socketio logger = logging.getLogger('gandalf.kuma') class KumaError(Exception): """Kuma couldn't be reached, refused the sign-in, or refused the change.""" def configured(cfg: Optional[dict]) -> bool: cfg = cfg or {} signed_in = bool(cfg.get('token')) or bool(cfg.get('username') and cfg.get('password')) return bool(cfg.get('url') and cfg.get('maintenance_id')) and signed_in def _sign_in(sio, cfg: dict, timeout: float) -> None: if cfg.get('token'): res = sio.call('loginByToken', cfg['token'], timeout=timeout) or {} if not res.get('ok'): raise KumaError('token rejected (Kuma password changed?)') return 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: use uptime_kuma.token instead') raise KumaError(f'login refused: {res.get("msg") or "no reason given"}') 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() # Kuma registers its event handlers only after it sends 'info', so anything emitted # before that is silently dropped and the call times out. ready = threading.Event() sio.on('info', lambda *args: ready.set()) try: sio.connect(cfg['url'], transports=['websocket'], wait_timeout=timeout) if not ready.wait(timeout): raise KumaError('Kuma not ready (no info event after connecting)') _sign_in(sio, cfg, timeout) 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