Compare commits

...
Author SHA1 Message Date
jared bba483bb05 Merge pull request 'Cluster alert needs network evidence; flapping NICs count once' (#59) from fix/no-network-without-evidence into main
Lint / JS (eslint) (push) Successful in 15s
Lint / Python (flake8) (push) Successful in 1m8s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m46s
Lint / Deploy (push) Successful in 14s
Test / Python Tests (pytest) (push) Successful in 1m8s
2026-11-23 23:37:22 -05:00
jaredandClaude Opus 5.5 7abe611adb Cluster alert needs network evidence; flapping NICs count once
Lint / JS (eslint) (push) Successful in 13s
Lint / Python (flake8) (push) Successful in 1m7s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m8s
Test / Python Tests (pytest) (push) Successful in 1m23s
Lint / Python (flake8) (pull_request) Successful in 1m9s
Lint / JS (eslint) (pull_request) Successful in 32s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m37s
Test / Python Tests (pytest) (pull_request) Successful in 1m53s
A host OOM stall on 2026-11-23 timed out one scrape on three hosts while
every switch link stayed up, and Gandalf opened a P1 network ticket on a
single poll (Tinker 615797777).

- A missing host counts toward the cluster check only after
  failure_threshold checks, not one missed scrape.
- The cluster P1 needs network evidence: a NIC link-down, or a missing
  host whose switch ports aren't all visibly up (unknown wiring counts as
  evidence). Without it, record a cluster_hosts_stalled warning with no
  ticket, naming hosts with recent OOM kills.
- The cluster ticket waits for consecutive checks like every other alert.
- A NIC that drops 3+ times in an hour is flapping: one standing alert,
  excluded from the cluster count.

Closes #57

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:34:38 -05:00
jared 54c5fb52c4 Merge pull request 'Kuma: sign in with a session token, wait for Kuma to be ready' (#54) from kuma-token into main
Lint / JS (eslint) (push) Successful in 15s
Lint / Python (flake8) (push) Successful in 59s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m20s
Test / Python Tests (pytest) (push) Successful in 1m19s
Lint / Deploy (push) Successful in 14s
2026-11-19 21:01:56 -05:00
jaredandClaude Opus 5.5 1444562a5d Kuma: sign in with a session token, wait for Kuma to be ready
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
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
5 changed files with 291 additions and 50 deletions

No files matched your search

+14 -3
View File
@@ -424,7 +424,7 @@ swap or recabling.
| Host unreachable via ping (≥`host_failure_threshold` consecutive checks) | P2 High |
| Configured host has no metrics in Prometheus (host or `node_exporter` down, ≥`host_failure_threshold` consecutive checks) | P2 High |
| Prometheus unavailable, so host and interface alerting is paused (≥2 consecutive checks) | P2 High |
| ≥3 hosts simultaneously reporting interface or metrics failures | P1 Critical |
| ≥`cluster_threshold` hosts failing at once, with network evidence, for ≥2 consecutive checks (see below) | P1 Critical |
| WAN down: broadband or optical status not Up, or PON not in O5 (≥`modem.failure_threshold`) | P1 Critical |
| Modem not responding (≥`modem.failure_threshold`) | P2 High |
| Fiber Rx/Tx power or optics temperature in the module's alarm range, or a supply voltage or Tx bias alarm flag (≥`modem.failure_threshold`) | P2 High |
@@ -437,6 +437,17 @@ swap or recabling.
A failed Pulse ping check counts as "unknown": it neither raises nor resolves `host_unreachable`.
**Cluster-wide alert: network evidence required.** Gandalf only alerts on the network, so the cluster P1 needs proof that the network is involved:
- **What counts as failing:**
- a NIC link-down regression
- a host with no metrics for ≥`failure_threshold` checks. One missed scrape doesn't count: a host stalled on memory or storage often times out a single scrape.
- **What counts as network evidence:**
- a NIC that went link-down
- a missing host whose switch ports aren't all visibly up in UniFi
- a missing host whose wiring Gandalf doesn't know
- **No evidence:** if the failing hosts' switch links all stayed up, Gandalf records a `cluster_hosts_stalled` warning with no ticket. The warning reads "not a network fault", names any host with recent OOM kills (`node_vmstat_oom_kill`), and leaves host health to hwmonDaemon.
- **Flapping links:** a NIC that drops `3` or more times within an hour is flapping. It keeps one open `interface_down` alert, which closes once it has been stable for an hour, and doesn't count toward the cluster check. Mark a dead NIC unused to silence it entirely.
### What a ticket contains
Tickets are Markdown. Besides the alert's own facts and a numbered "What to check" list, each one adds
@@ -679,7 +690,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
| `monitor.failure_threshold` | Consecutive failures before creating ticket (default: 2) |
| `monitor.host_failure_threshold` | Consecutive failures before ticketing a host that has disappeared, whether it has no metrics or doesn't answer ping (default: 5). A normal reboot takes about 3-5 minutes, so the default rides it out: the host still shows as down on the dashboard, but a ticket opens only after about 8 minutes at the default poll interval. For longer maintenance, suppress the host first. |
| `monitor.unifi_failure_threshold` | Consecutive failures before ticketing a UniFi device as offline (default: same as `failure_threshold`). Set higher than `failure_threshold`: UniFi switches/APs can take several minutes to rejoin after a firmware-update reboot, so a low threshold cuts tickets for momentary maintenance reboots instead of real failures. |
| `monitor.cluster_threshold` | Hosts with failures to trigger cluster-wide P1 (default: 3) |
| `monitor.cluster_threshold` | Hosts failing at once (with network evidence, see Alert Logic) to trigger the cluster-wide P1 (default: 3) |
| `monitor.ping_hosts` | Hosts checked only by ping (no node_exporter) |
| `monitor.stale_alert_days` | Days an alert can stay active before the dashboard flags it as stale (default: 3) |
| `monitor.stale_ticket_hours` | Hours a ticket can stay open after all its alerts cleared before it is listed under Needs Follow-up (default: 24) |
@@ -690,7 +701,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. |
---
+30 -12
View File
@@ -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'):
+101 -18
View File
@@ -1354,11 +1354,59 @@ class NetworkMonitor:
# ------------------------------------------------------------------
# Interface monitoring (Prometheus)
# ------------------------------------------------------------------
# An interface that went down this many times within the window is flapping: it keeps
# one standing alert and doesn't count toward the cluster-wide check.
FLAP_WINDOW_S = 3600
FLAP_MIN_DOWNS = 3
def _note_down(self, host: str, iface: str, now: float) -> bool:
"""Record an up-to-down transition; True if the interface is now flapping."""
downs = self.__dict__.setdefault('_iface_downs', {})
recent = [t for t in downs.get((host, iface), []) if now - t < self.FLAP_WINDOW_S] + [now]
downs[(host, iface)] = recent
return len(recent) >= self.FLAP_MIN_DOWNS
def _is_flapping(self, host: str, iface: str, now: float) -> bool:
recent = self.__dict__.get('_iface_downs', {}).get((host, iface), [])
return sum(1 for t in recent if now - t < self.FLAP_WINDOW_S) >= self.FLAP_MIN_DOWNS
def _switch_links_up(self, host: str) -> bool:
"""True only when every switch port this host is known to use is visibly up.
Unknown wiring, a switch Gandalf can't see, or a missing port all count as "not
proven up", so a real network failure is never explained away.
"""
if getattr(self, '_link_data', None) is None:
return False
switches = self._switches()
uplinks, _seen = self._uplinks_for(host, switches)
if not uplinks:
return False
for u in uplinks:
live = (switches.get(u['switch'], {}).get('ports') or {}).get(u['port'])
if not live or not live.get('up'):
return False
return True
def _oom_hosts(self) -> List[str]:
"""Hosts whose kernel OOM-killed something in the last 15 minutes (context only)."""
try:
rows = self.prom.query('increase(node_vmstat_oom_kill[15m]) > 0')
return sorted({self._hostname(r['metric'].get('instance', '')) for r in rows
if r.get('metric', {}).get('instance') in self._instance_map})
except Exception as e:
logger.warning(f'OOM context query failed: {e}')
return []
def _process_interfaces(self, states: Dict[str, Dict[str, bool]], suppressions: list) -> None:
baseline = db.get_baseline()
new_baseline = {k: dict(v) for k, v in baseline.items()}
# Only count hosts with genuine regressions (UP→DOWN) toward cluster threshold
now = time.time()
# Hosts with a sustained failure: a real link regression, or metrics gone for
# fail_thresh checks. A single missed scrape (a stalled host) doesn't count.
hosts_with_regression: List[str] = []
# The subset with network evidence: a link went down, or a switch port isn't up
network_evidence: List[str] = []
for instance, ifaces in states.items():
if instance not in self._instance_map:
@@ -1372,10 +1420,15 @@ class NetworkMonitor:
if iface in unused:
continue # marked unused: no alerts, and it can't count as a regression
prev = baseline.get(host, {}).get(iface) # 'up', 'initial_down', or None
last_seen = self.__dict__.setdefault('_iface_last', {})
was_up = last_seen.get((host, iface), True)
last_seen[(host, iface)] = is_up
if is_up:
new_baseline[host][iface] = 'up'
db.resolve_event('interface_down', host, iface)
# A flapping link keeps its one alert open until it settles
if not self._is_flapping(host, iface, now):
db.resolve_event('interface_down', host, iface)
else:
if prev is None:
# First observation is down: could be unused port, don't alert
@@ -1386,22 +1439,28 @@ class NetworkMonitor:
pass
else: # prev == 'up'
# Regression: was UP, now DOWN
host_has_regression = True
# Regression: was UP, now DOWN. Only a fresh drop (up on the last
# check) counts toward flapping, not every check of one long outage.
flapping = (self._note_down(host, iface, now) if was_up
else self._is_flapping(host, iface, now))
if not flapping:
host_has_regression = True
sup = (
db.check_suppressed(suppressions, 'interface', host, iface) or
db.check_suppressed(suppressions, 'host', host)
)
what = 'is flapping (link keeps dropping)' if flapping else 'went link-down'
event_id, is_new, consec, ticket_id = db.upsert_event(
'interface_down', 'critical', 'prometheus',
host, iface,
f'Interface {iface} on {host} went link-down ({_now_utc()})',
f'Interface {iface} on {host} {what} ({_now_utc()})',
)
if not sup and consec >= self.fail_thresh and not ticket_id:
self._ticket_interface(event_id, host, iface, consec)
if host_has_regression:
hosts_with_regression.append(host)
network_evidence.append(host)
# A dead host doesn't report its interfaces as down: its series just
# disappear, so a configured host that's absent needs its own check.
@@ -1409,31 +1468,55 @@ class NetworkMonitor:
if instance in states:
db.resolve_event('host_metrics_missing', host, instance)
continue
hosts_with_regression.append(host)
sup = db.check_suppressed(suppressions, 'host', host)
event_id, is_new, consec, ticket_id = db.upsert_event(
'host_metrics_missing', 'critical', 'prometheus',
host, instance,
f'No metrics from {host} ({instance}): host or node_exporter is down ({_now_utc()})',
)
if consec >= self.fail_thresh:
hosts_with_regression.append(host)
if not self._switch_links_up(host):
network_evidence.append(host)
if not sup and consec >= self.host_fail_thresh and not ticket_id:
self._ticket_metrics_missing(event_id, host, instance, consec)
db.set_baseline(new_baseline)
self._check_cluster(hosts_with_regression, network_evidence, suppressions)
# Cluster-wide check: only genuine regressions count
if len(hosts_with_regression) >= self.cluster_thresh:
sup = db.check_suppressed(suppressions, 'all', '')
event_id, is_new, consec, ticket_id = db.upsert_event(
'cluster_network_issue', 'critical', 'prometheus',
self.cluster_name, '',
f'{len(hosts_with_regression)} hosts with simultaneous interface or metrics failures: '
f'{", ".join(hosts_with_regression)}',
)
if not sup and (is_new or not ticket_id):
self._ticket_cluster(event_id, hosts_with_regression)
else:
def _check_cluster(self, failing: List[str], evidence: List[str], suppressions: list) -> None:
"""Ticket a cluster-wide network failure only with network evidence.
Several hosts failing at once with every switch link still up is a stall (memory,
storage, load), not the network: it's recorded as a warning with no ticket, and
host health is left to hwmonDaemon.
"""
if len(failing) < self.cluster_thresh:
db.resolve_event('cluster_network_issue', self.cluster_name, '')
db.resolve_event('cluster_hosts_stalled', self.cluster_name, '')
return
if not evidence:
db.resolve_event('cluster_network_issue', self.cluster_name, '')
oom = self._oom_hosts()
note = f' OOM kills in the last 15 min on {", ".join(oom)}.' if oom else ''
db.upsert_event(
'cluster_hosts_stalled', 'warning', 'prometheus', self.cluster_name, '',
f'{len(failing)} hosts stopped answering Prometheus ({", ".join(failing)}) but every '
f'switch link to them stayed up: not a network fault. Check host memory, storage '
f'and load.{note}',
)
return
db.resolve_event('cluster_hosts_stalled', self.cluster_name, '')
sup = db.check_suppressed(suppressions, 'all', '')
event_id, is_new, consec, ticket_id = db.upsert_event(
'cluster_network_issue', 'critical', 'prometheus',
self.cluster_name, '',
f'{len(failing)} hosts with simultaneous interface or metrics failures: '
f'{", ".join(failing)}',
)
# Two checks in a row, like every other alert: one bad poll is not a P1
if not sup and consec >= self.fail_thresh and not ticket_id:
self._ticket_cluster(event_id, failing)
def _ticket_cluster(self, event_id: int, hosts: List[str]) -> None:
switches = self._switches()
+39 -17
View File
@@ -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
+107
View File
@@ -138,6 +138,113 @@ class TestDeadHostDetection:
assert snap['hosts']['beta']['status'] == 'down'
HOST_C = '10.0.0.3:9100'
def _switches(up=True):
"""alpha, beta and gamma each linked to one AGG port, all up unless up=False."""
ports = {f'Port {i}': {'port_idx': i, 'up': up, 'lldp': {'system_name': name, 'port_id': 'eth0'}}
for i, name in enumerate(('alpha', 'beta', 'gamma'), start=1)}
return {'unifi_switches': {'AGG': {'ports': ports}}}
def _consec(by_type, default=2):
"""upsert_event side effect: consecutive count per event type."""
return lambda etype, *a, **k: (1, False, by_type.get(etype, default), None)
class TestClusterNeedsNetworkEvidence:
"""2026-11-23: an OOM stall on one host timed out scrapes on three; every switch link
stayed up, and Gandalf still opened a P1 network ticket on one poll (gandalf#57)."""
@pytest.fixture
def three(self, mon):
mon._instance_map[HOST_C] = 'gamma'
mon.cluster_thresh = 3
mon._known_uplinks = {}
return mon
def test_one_missed_scrape_never_counts(self, three, db):
db.upsert_event.side_effect = _consec({'host_metrics_missing': 1})
three._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, [])
types = [u[0] for u in upserted(db)]
assert 'cluster_network_issue' not in types and 'cluster_hosts_stalled' not in types
db.resolve_event.assert_any_call('cluster_network_issue', 'test-cluster', '')
def test_stall_with_switch_links_up_is_not_a_network_ticket(self, three, db):
three._link_data = _switches(up=True)
three.prom.query.return_value = [{'metric': {'instance': HOST_A}, 'value': [0, '11']}]
three._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, [])
types = [u[0] for u in upserted(db)]
assert 'cluster_network_issue' not in types
assert 'cluster_hosts_stalled' in types
assert not three.tickets.create.called
msg = next(c.args[5] for c in db.upsert_event.call_args_list if c.args[0] == 'cluster_hosts_stalled')
assert 'not a network fault' in msg and 'OOM kills in the last 15 min on alpha' in msg
def test_switch_port_down_is_network_evidence(self, three, db):
three._link_data = _switches(up=False)
three._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, [])
assert ('cluster_network_issue', 'test-cluster', '') in upserted(db)
assert 'Multiple hosts' in three.tickets.create.call_args.args[0]
def test_unknown_wiring_is_never_explained_away(self, three, db):
three._link_data = {'unifi_switches': {}}
three._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, [])
assert ('cluster_network_issue', 'test-cluster', '') in upserted(db)
def test_cluster_ticket_waits_for_a_second_check(self, three, db):
db.upsert_event.side_effect = _consec({'cluster_network_issue': 1})
three._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, [])
assert ('cluster_network_issue', 'test-cluster', '') in upserted(db)
assert not any('Multiple hosts' in c.args[0] for c in three.tickets.create.call_args_list)
def test_link_regressions_still_ticket(self, three, db):
db.get_baseline.return_value = {h: {'eth0': 'up'} for h in ('alpha', 'beta', 'gamma')}
three._process_interfaces({HOST_A: {'eth0': False}, HOST_B: {'eth0': False},
HOST_C: {'eth0': False}}, [])
assert any('Multiple hosts' in c.args[0] for c in three.tickets.create.call_args_list)
class TestFlappingInterface:
def _poll(self, mon, up, at):
with patch.object(monitor.time, 'time', return_value=at):
mon._process_interfaces({HOST_A: {'eth0': up}, HOST_B: {'eth0': True}}, [])
def test_three_drops_in_an_hour_is_flapping(self, mon, db):
db.get_baseline.return_value = {'alpha': {'eth0': 'up'}, 'beta': {'eth0': 'up'}}
for i, up in enumerate([False, True, False, True, False]):
self._poll(mon, up, 1000 + i * 120)
last = db.upsert_event.call_args_list[-1].args
assert last[0] == 'interface_down' and 'is flapping' in last[5]
# While flapping, coming back up doesn't close the alert
db.resolve_event.reset_mock()
self._poll(mon, True, 1700)
assert ('interface_down', 'alpha', 'eth0') not in [c.args for c in db.resolve_event.call_args_list]
def test_flapping_link_does_not_count_toward_cluster(self, mon, db):
db.get_baseline.return_value = {'alpha': {'eth0': 'up'}, 'beta': {'eth0': 'up'}}
mon.cluster_thresh = 1
for i, up in enumerate([False, True, False, True]):
self._poll(mon, up, 1000 + i * 120)
db.upsert_event.reset_mock()
self._poll(mon, False, 1600)
assert ('cluster_network_issue', 'test-cluster', '') not in upserted(db)
def test_one_long_outage_is_not_flapping(self, mon, db):
db.get_baseline.return_value = {'alpha': {'eth0': 'up'}, 'beta': {'eth0': 'up'}}
for i in range(5):
self._poll(mon, False, 1000 + i * 120)
assert 'went link-down' in db.upsert_event.call_args_list[-1].args[5]
def test_flapping_settles_after_an_hour(self, mon, db):
db.get_baseline.return_value = {'alpha': {'eth0': 'up'}, 'beta': {'eth0': 'up'}}
for i, up in enumerate([False, True, False, True, False]):
self._poll(mon, up, 1000 + i * 120)
self._poll(mon, True, 1000 + 4 * 120 + 3700)
db.resolve_event.assert_any_call('interface_down', 'alpha', 'eth0')
class TestPrometheusOutage:
def test_empty_result_means_unavailable(self):
client = monitor.PrometheusClient('http://prom.test')