Files
gandalf/kuma.py
T
jaredandClaude Opus 5.5 1444562a5d
Lint / JS (eslint) (push) Successful in 10s
Lint / Python (flake8) (push) Successful in 58s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m1s
Lint / Python (flake8) (pull_request) Successful in 57s
Lint / JS (eslint) (pull_request) Successful in 8s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Test / Python Tests (pytest) (push) Successful in 1m34s
Test / Python Tests (pytest) (pull_request) Successful in 1m45s
Security / Python Security (bandit) (pull_request) Successful in 59s
Kuma: sign in with a session token, wait for Kuma to be ready
The Kuma account has two-factor login, so a password login always ends
in tokenRequired. Prod config now holds a Kuma session token instead
(uptime_kuma = {url, token, maintenance_id}).

- Sign in with loginByToken; a refusal says the token was rejected
  (Kuma password changed?). username/password stay as a fallback for an
  account without two-factor login.
- Wait for Kuma's first 'info' event before emitting: Kuma registers
  its handlers only after sending it, so an earlier emit is dropped and
  times out now and then.
- configured() needs url, maintenance_id and a token (or username and
  password).

Tested from prod against Kuma 2.5.5: signed in and paused window 7,
which was already paused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 20:59:37 -05:00

75 lines
3.3 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 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