Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1444562a5d |
No files matched your search
@@ -690,7 +690,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
||||
| `modem.failure_threshold` | Consecutive failures before ticketing a modem alert (default: same as `failure_threshold`). Raise it if gateway reboots or automatic firmware updates cut tickets. |
|
||||
| `modem.rx_drift_db` | Rx drop below the 7-day median that raises `fiber_rx_drift` (default: 3.0) |
|
||||
| `modem.rx_drift_min_samples` | Readings required before drift alerts start (default: 288) |
|
||||
| `uptime_kuma.url`, `.username`, `.password`, `.maintenance_id` | Optional. Lets the Restart modem button switch an Uptime Kuma maintenance window on and off (Kuma 2.x, over its Socket.IO login). Create the window once in Kuma with the *manual* strategy and the monitors a modem restart takes down, pause it, and put its id here. The account must not use two-factor login. |
|
||||
| `uptime_kuma.url`, `.token`, `.maintenance_id` | Optional. Lets the Restart modem button switch an Uptime Kuma maintenance window on and off (Kuma 2.x, over its Socket.IO API). `token` is a Kuma session token, which works with a two-factor account and stops working if the Kuma password changes; `username` and `password` can be used instead for an account without two-factor login. Create the window once in Kuma with the *manual* strategy and the monitors a modem restart takes down, pause it, and put its id here. |
|
||||
| `modem.access_code` | Optional. The gateway's Device Access Code (printed on its label). With it, Gandalf logs in to read NAT session counts and to ping from the gateway when the internet is slow (see WAN modem notes). Keep it only in `config.json`, which is git-ignored and mode 600. |
|
||||
|
||||
---
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"""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
|
||||
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", "username": "...", "password": "...",
|
||||
"maintenance_id": 7}
|
||||
"uptime_kuma": {"url": "http://10.10.10.25:3001", "token": "...", "maintenance_id": 7}
|
||||
|
||||
Nothing else in Kuma is read or changed.
|
||||
`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
|
||||
@@ -18,12 +20,27 @@ logger = logging.getLogger('gandalf.kuma')
|
||||
|
||||
|
||||
class KumaError(Exception):
|
||||
"""Kuma couldn't be reached, refused the login, or refused the change."""
|
||||
"""Kuma couldn't be reached, refused the sign-in, 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'))
|
||||
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:
|
||||
@@ -32,14 +49,15 @@ def set_maintenance(cfg: dict, active: bool, client_factory: Optional[Callable]
|
||||
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)
|
||||
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"}')
|
||||
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'):
|
||||
|
||||
+39
-17
@@ -7,19 +7,26 @@ import pytest
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
import kuma # noqa: E402
|
||||
|
||||
CFG = {'url': 'http://kuma.test:3001', 'username': 'gandalf', 'password': 'pw', 'maintenance_id': 7}
|
||||
CFG = {'url': 'http://kuma.test:3001', 'token': 'tok', 'maintenance_id': 7}
|
||||
PASSWORD_CFG = {'url': 'http://kuma.test:3001', 'username': 'gandalf', 'password': 'pw', 'maintenance_id': 7}
|
||||
|
||||
|
||||
class FakeSocket:
|
||||
def __init__(self, answers=None, connect_error=None):
|
||||
def __init__(self, answers=None, connect_error=None, sends_info=True):
|
||||
self.answers = answers or {}
|
||||
self.connect_error = connect_error
|
||||
self.calls, self.disconnected = [], False
|
||||
self.sends_info = sends_info
|
||||
self.calls, self.disconnected, self.handlers = [], False, {}
|
||||
|
||||
def on(self, event, handler):
|
||||
self.handlers[event] = handler
|
||||
|
||||
def connect(self, url, **kw):
|
||||
if self.connect_error:
|
||||
raise self.connect_error
|
||||
self.url = url
|
||||
if self.sends_info: # Kuma's first event; its handlers exist only after it
|
||||
self.handlers['info']({'serverTimezone': 'America/New_York'})
|
||||
|
||||
def call(self, event, data=None, timeout=None):
|
||||
self.calls.append((event, data))
|
||||
@@ -29,34 +36,49 @@ class FakeSocket:
|
||||
self.disconnected = True
|
||||
|
||||
|
||||
def run(active=True, **kw):
|
||||
def run(active=True, cfg=CFG, **kw):
|
||||
sock = FakeSocket(**kw)
|
||||
kuma.set_maintenance(CFG, active, client_factory=lambda: sock)
|
||||
kuma.set_maintenance(dict(cfg, timeout=0.05), active, client_factory=lambda: sock)
|
||||
return sock
|
||||
|
||||
|
||||
class TestKuma:
|
||||
def test_configured_needs_every_field(self):
|
||||
assert kuma.configured(CFG)
|
||||
assert not kuma.configured(dict(CFG, password=''))
|
||||
def test_configured_needs_url_window_and_a_way_to_sign_in(self):
|
||||
assert kuma.configured(CFG) and kuma.configured(PASSWORD_CFG)
|
||||
assert not kuma.configured(dict(CFG, token=''))
|
||||
assert not kuma.configured(dict(CFG, maintenance_id=None))
|
||||
assert not kuma.configured(dict(PASSWORD_CFG, password=''))
|
||||
assert not kuma.configured(None)
|
||||
|
||||
def test_resume_logs_in_then_switches_the_window_on(self):
|
||||
def test_token_sign_in_then_switches_the_window_on(self):
|
||||
sock = run(True)
|
||||
assert sock.calls == [('login', {'username': 'gandalf', 'password': 'pw', 'token': ''}),
|
||||
('resumeMaintenance', 7)]
|
||||
assert sock.calls == [('loginByToken', 'tok'), ('resumeMaintenance', 7)]
|
||||
assert sock.disconnected and sock.url == CFG['url']
|
||||
|
||||
def test_rejected_token(self):
|
||||
with pytest.raises(kuma.KumaError, match='token rejected'):
|
||||
run(answers={'loginByToken': {'ok': False}})
|
||||
|
||||
def test_waits_for_kuma_to_be_ready(self):
|
||||
sock = FakeSocket(sends_info=False)
|
||||
with pytest.raises(kuma.KumaError, match='not ready'):
|
||||
kuma.set_maintenance(dict(CFG, timeout=0.05), True, client_factory=lambda: sock)
|
||||
assert sock.calls == [] and sock.disconnected # nothing sent before info
|
||||
|
||||
def test_password_sign_in(self):
|
||||
sock = run(True, cfg=PASSWORD_CFG)
|
||||
assert sock.calls[0] == ('login', {'username': 'gandalf', 'password': 'pw', 'token': ''})
|
||||
|
||||
def test_pause(self):
|
||||
assert run(False).calls[-1] == ('pauseMaintenance', 7)
|
||||
|
||||
def test_refused_login(self):
|
||||
def test_refused_password(self):
|
||||
with pytest.raises(kuma.KumaError, match='login refused: Incorrect username or password'):
|
||||
run(answers={'login': {'ok': False, 'msg': 'Incorrect username or password.'}})
|
||||
run(cfg=PASSWORD_CFG, answers={'login': {'ok': False, 'msg': 'Incorrect username or password.'}})
|
||||
|
||||
def test_two_factor_account(self):
|
||||
with pytest.raises(kuma.KumaError, match='two-factor'):
|
||||
run(answers={'login': {'ok': False, 'tokenRequired': True}})
|
||||
def test_two_factor_account_needs_the_token(self):
|
||||
with pytest.raises(kuma.KumaError, match='use uptime_kuma.token'):
|
||||
run(cfg=PASSWORD_CFG, answers={'login': {'ok': False, 'tokenRequired': True}})
|
||||
|
||||
def test_refused_change(self):
|
||||
with pytest.raises(kuma.KumaError, match='resumeMaintenance refused'):
|
||||
@@ -65,5 +87,5 @@ class TestKuma:
|
||||
def test_unreachable(self):
|
||||
sock = FakeSocket(connect_error=ConnectionError('refused'))
|
||||
with pytest.raises(kuma.KumaError, match='ConnectionError'):
|
||||
kuma.set_maintenance(CFG, True, client_factory=lambda: sock)
|
||||
kuma.set_maintenance(dict(CFG, timeout=0.05), True, client_factory=lambda: sock)
|
||||
assert sock.disconnected
|
||||
Reference in new issue
Block a user