Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
48420a5698 | ||
|
|
a5d4fc3156 | ||
|
|
a7792063ba | ||
|
|
3e3069d2aa | ||
|
|
a31437f2e5 | ||
|
|
bba483bb05 | ||
|
|
7abe611adb | ||
|
|
54c5fb52c4 | ||
|
|
1444562a5d | ||
|
|
dd9ba41479 |
No files matched your search
@@ -424,7 +424,7 @@ swap or recabling.
|
|||||||
| Host unreachable via ping (≥`host_failure_threshold` consecutive checks) | P2 High |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
||||||
@@ -432,11 +432,23 @@ swap or recabling.
|
|||||||
| Rx power `rx_drift_db` or more below its 7-day median (≥`modem.failure_threshold`) | P3 |
|
| Rx power `rx_drift_db` or more below its 7-day median (≥`modem.failure_threshold`) | P3 |
|
||||||
| Modem pages unreadable, e.g. after a firmware update (≥`modem.failure_threshold`) | P3 |
|
| Modem pages unreadable, e.g. after a firmware update (≥`modem.failure_threshold`) | P3 |
|
||||||
| UniFi logs that Smart Power auto power-cycled the modem | P3 |
|
| UniFi logs that Smart Power auto power-cycled the modem | P3 |
|
||||||
| UniFi logs that the WAN failed multiple times in 24 hours (at most one ticket a day) | P2 |
|
| UniFi logs that the WAN failed multiple times in 24 hours, and at least 2 of those drops aren't explained by a modem restart (decided 10 minutes later; at most one ticket a day) | P2 |
|
||||||
|
| Internet degraded: at least `modem.degraded_fraction` (default half) of the last 2 hours' 5 minute periods slow, lossy or down by UniFi's WAN health. Closes with a recovery note once the last 2 hours are at most a quarter bad. A modem restart resets it: only periods from 15 minutes after the latest restart count. | P2 |
|
||||||
| An installed cable doesn't match the cutsheet (wrong neighbor, no link, missing port, port conflict) for `cutsheet.mismatch_ticket_hours` | P4 |
|
| An installed cable doesn't match the cutsheet (wrong neighbor, no link, missing port, port conflict) for `cutsheet.mismatch_ticket_hours` | P4 |
|
||||||
|
|
||||||
A failed Pulse ping check counts as "unknown": it neither raises nor resolves `host_unreachable`.
|
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
|
### What a ticket contains
|
||||||
|
|
||||||
Tickets are Markdown. Besides the alert's own facts and a numbered "What to check" list, each one adds
|
Tickets are Markdown. Besides the alert's own facts and a numbered "What to check" list, each one adds
|
||||||
@@ -502,6 +514,13 @@ Uptime comes from the System Information page without a login. Firmware 6.40 sho
|
|||||||
(older firmware sent seconds; both are read). Uptime going backwards between polls records a restart, and
|
(older firmware sent seconds; both are read). Uptime going backwards between polls records a restart, and
|
||||||
the panel shows it (*restarted ... by ...*).
|
the panel shows it (*restarted ... by ...*).
|
||||||
|
|
||||||
|
**Restarts and the WAN tickets.** Gandalf folds every kind of restart into one history:
|
||||||
|
- Smart Power power-cycles from the UniFi log
|
||||||
|
- uptime resets, which catch a reboot from the AT&T app, the modem's own button or a power loss
|
||||||
|
- the Restart modem button
|
||||||
|
|
||||||
|
Entries within 15 minutes of each other count as one restart; a reboot that Smart Power then power-cycles mid-boot is common. The "WAN connection unstable" ticket waits 10 minutes for the uptime reset to show up, then ignores drops from 5 minutes before to 15 minutes after a restart, so a reboot's own drops no longer open it. Both WAN tickets list the last 7 days of restarts and how long each one lasted. After 2 or more restarts in a week, they suggest asking AT&T for a replacement modem.
|
||||||
|
|
||||||
Outages can be over between polls: two real ones lasted about two minutes against a 5 minute poll.
|
Outages can be over between polls: two real ones lasted about two minutes against a 5 minute poll.
|
||||||
So WAN outages and modem restarts also come from the UniFi system log, and a drop in the modem's uptime
|
So WAN outages and modem restarts also come from the UniFi system log, and a drop in the modem's uptime
|
||||||
records a restart even if nothing logged it. A single short outage only appears in the panel's history.
|
records a restart even if nothing logged it. A single short outage only appears in the panel's history.
|
||||||
@@ -536,11 +555,20 @@ for read-only checks, stored in `monitor_state.modem_checks`:
|
|||||||
1. switches the `uptime_kuma` maintenance window on (if that fails it stops and asks whether to go on
|
1. switches the `uptime_kuma` maintenance window on (if that fails it stops and asks whether to go on
|
||||||
without it),
|
without it),
|
||||||
2. starts Gandalf maintenance (a global suppression for up to 20 minutes, shown in the banner),
|
2. starts Gandalf maintenance (a global suppression for up to 20 minutes, shown in the banner),
|
||||||
3. posts the gateway's Restart Device form. If that fails, steps 1 and 2 are undone.
|
3. pauses UniFi Smart Power auto power-cycle on every outlet that has it on (the modem's RPDU outlet).
|
||||||
|
Otherwise Smart Power sees the internet down while the modem boots and cuts its power mid-boot,
|
||||||
|
turning one restart into two or three. If the pause fails, the restart still goes ahead.
|
||||||
|
4. posts the gateway's Restart Device form. If that fails, steps 1 to 3 are undone.
|
||||||
|
|
||||||
The monitor then waits for the gateway to answer with its WAN up and an uptime showing it restarted
|
The monitor then waits for the gateway to answer with its WAN up and an uptime showing it restarted
|
||||||
(at least 3 minutes later), switches the Kuma window off, ends the suppression, and records how long it
|
(at least 3 minutes later), switches the Kuma window off, ends the suppression, turns auto power-cycle
|
||||||
took (`monitor_state.modem_restart`). After 30 minutes it ends both regardless. One restart at a time.
|
back on, and records how long it took (`monitor_state.modem_restart`). After 30 minutes it ends all three
|
||||||
|
regardless. One restart at a time.
|
||||||
|
|
||||||
|
Auto power-cycle is the only UniFi setting Gandalf ever changes. It sends the outlet's settings back
|
||||||
|
with only `cycle_enabled` changed and reads them again to confirm. If turning it back on fails, the
|
||||||
|
monitor retries every cycle, and Needs attention shows it as broken until it succeeds. A modem reboot
|
||||||
|
from the AT&T app isn't covered, so Smart Power can still interrupt one; use the button instead.
|
||||||
|
|
||||||
The login posts md5(access code + nonce), as the gateway's own page does, so the code itself is never sent.
|
The login posts md5(access code + nonce), as the gateway's own page does, so the code itself is never sent.
|
||||||
The session is kept between checks and renewed when it expires. A refused code is reported in Needs
|
The session is kept between checks and renewed when it expires. A refused code is reported in Needs
|
||||||
@@ -679,7 +707,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.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.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.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.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_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) |
|
| `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) |
|
||||||
@@ -689,8 +717,9 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
|||||||
| `modem.timeout` | Seconds to wait per status page (default: 10) |
|
| `modem.timeout` | Seconds to wait per status page (default: 10) |
|
||||||
| `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.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_db` | Rx drop below the 7-day median that raises `fiber_rx_drift` (default: 3.0) |
|
||||||
|
| `modem.degraded_fraction` | Share of the last 2 hours' WAN health periods that must be slow, lossy or down to open `wan_degraded` (default: 0.5) |
|
||||||
| `modem.rx_drift_min_samples` | Readings required before drift alerts start (default: 288) |
|
| `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. |
|
| `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,7 +30,7 @@ import diagnose
|
|||||||
import kuma
|
import kuma
|
||||||
import modem as modem_api
|
import modem as modem_api
|
||||||
import topology
|
import topology
|
||||||
from monitor import PulseClient, UnifiClient
|
from monitor import PulseClient, UnifiClient, pause_smart_power, restore_smart_power
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
level=logging.INFO,
|
level=logging.INFO,
|
||||||
@@ -605,10 +605,24 @@ def api_modem_restart():
|
|||||||
|
|
||||||
sup_id = db.create_suppression('all', '', '', 'Modem restart from Gandalf', user,
|
sup_id = db.create_suppression('all', '', '', 'Modem restart from Gandalf', user,
|
||||||
MODEM_RESTART_SILENCE_MIN)
|
MODEM_RESTART_SILENCE_MIN)
|
||||||
|
# Smart Power would see the internet down while the modem boots and cut its power
|
||||||
|
# mid-boot, so auto power-cycle is off until the modem is back. A failure here doesn't
|
||||||
|
# stop the restart: it just means Smart Power may cycle it once more, as it used to.
|
||||||
|
unifi = UnifiClient(cfg['unifi']) if cfg.get('unifi') else None
|
||||||
|
paused, sp_error = pause_smart_power(unifi) if unifi else ([], None)
|
||||||
|
if sp_error:
|
||||||
|
logger.warning(f'Smart Power auto power-cycle could not be paused: {sp_error}')
|
||||||
try:
|
try:
|
||||||
result = modem_api.ModemAdmin(modem_cfg).restart()
|
result = modem_api.ModemAdmin(modem_cfg).restart()
|
||||||
except (modem_api.ModemUnreachable, modem_api.ModemDataInvalid, modem_api.ModemLoginFailed) as e:
|
except (modem_api.ModemUnreachable, modem_api.ModemDataInvalid, modem_api.ModemLoginFailed) as e:
|
||||||
logger.error(f'Modem restart failed: {e}')
|
logger.error(f'Modem restart failed: {e}')
|
||||||
|
if paused:
|
||||||
|
err = restore_smart_power(unifi, paused)
|
||||||
|
if err:
|
||||||
|
logger.error(f'Smart Power auto power-cycle could not be turned back on: {err}')
|
||||||
|
db.set_state('modem_restart', {'at': time.time(), 'by': user, 'result': 'failed',
|
||||||
|
'finished_at': time.time(), 'back': False,
|
||||||
|
'smart_power_paused': paused, 'smart_power_error': err})
|
||||||
db.deactivate_suppression(sup_id)
|
db.deactivate_suppression(sup_id)
|
||||||
if kuma_on:
|
if kuma_on:
|
||||||
try:
|
try:
|
||||||
@@ -618,10 +632,13 @@ def api_modem_restart():
|
|||||||
return jsonify({'error': f'The modem did not restart: {e}'}), 502
|
return jsonify({'error': f'The modem did not restart: {e}'}), 502
|
||||||
|
|
||||||
db.set_state('modem_restart', {'at': time.time(), 'by': user, 'result': result,
|
db.set_state('modem_restart', {'at': time.time(), 'by': user, 'result': result,
|
||||||
'suppression_id': sup_id, 'kuma': kuma_on, 'finished_at': None})
|
'suppression_id': sup_id, 'kuma': kuma_on, 'finished_at': None,
|
||||||
|
'smart_power_paused': paused, 'smart_power_error': sp_error})
|
||||||
logger.warning(f'Modem restart requested by {user} ({result}); Kuma maintenance '
|
logger.warning(f'Modem restart requested by {user} ({result}); Kuma maintenance '
|
||||||
f'{"on" if kuma_on else "not set"}, suppression #{sup_id}')
|
f'{"on" if kuma_on else "not set"}, suppression #{sup_id}, Smart Power paused on '
|
||||||
return jsonify({'ok': True, 'result': result, 'kuma': kuma_on, 'suppression_id': sup_id})
|
f'{len(paused)} outlet(s)')
|
||||||
|
return jsonify({'ok': True, 'result': result, 'kuma': kuma_on, 'suppression_id': sup_id,
|
||||||
|
'smart_power_paused': len(paused), 'smart_power_error': sp_error})
|
||||||
|
|
||||||
|
|
||||||
@app.route('/api/devices')
|
@app.route('/api/devices')
|
||||||
@@ -1425,7 +1442,8 @@ def _attention() -> dict:
|
|||||||
sheet = {'items': (view or {}).get('items') or [], 'cables': (view or {}).get('cables') or []}
|
sheet = {'items': (view or {}).get('items') or [], 'cables': (view or {}).get('cables') or []}
|
||||||
power = _topology_graph(events, sheet, feeds).get('power') or []
|
power = _topology_graph(events, sheet, feeds).get('power') or []
|
||||||
return attention.build(events, power, view, racks, _state_json('wan_quality'),
|
return attention.build(events, power, view, racks, _state_json('wan_quality'),
|
||||||
modem_checks=_state_json('modem_checks'))
|
modem_checks=_state_json('modem_checks'),
|
||||||
|
modem_restart=_state_json('modem_restart'))
|
||||||
|
|
||||||
|
|
||||||
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
|
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
|
||||||
|
|||||||
+18
-3
@@ -188,21 +188,36 @@ def _wan(quality: Optional[dict], now: float, checks: Optional[dict] = None) ->
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _smart_power(restart: Optional[dict]) -> List[dict]:
|
||||||
|
"""Auto power-cycle left off after a modem restart: the modem would not be
|
||||||
|
power-cycled if it hangs, so this is broken until Gandalf manages to turn it back on."""
|
||||||
|
r = restart or {}
|
||||||
|
if not r.get('finished_at') or not r.get('smart_power_paused') or r.get('smart_power_restored'):
|
||||||
|
return []
|
||||||
|
outlets = ', '.join(f'{o.get("device")} outlet {o.get("index")}' for o in r['smart_power_paused'])
|
||||||
|
return [_entry('broken', 'bad', 'Smart Power auto power-cycle is still off after the modem restart',
|
||||||
|
'#modem-section', f'{outlets}. Gandalf keeps trying to turn it back on'
|
||||||
|
+ (f' (last error: {r["smart_power_error"]})' if r.get('smart_power_error') else '')
|
||||||
|
+ '; it can also be turned on in UniFi under the outlet\'s settings.')]
|
||||||
|
|
||||||
|
|
||||||
def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict],
|
def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict],
|
||||||
rack_issues: Optional[Dict[str, dict]] = None, wan_quality: Optional[dict] = None,
|
rack_issues: Optional[Dict[str, dict]] = None, wan_quality: Optional[dict] = None,
|
||||||
now: Optional[float] = None, modem_checks: Optional[dict] = None) -> dict:
|
now: Optional[float] = None, modem_checks: Optional[dict] = None,
|
||||||
|
modem_restart: Optional[dict] = None) -> dict:
|
||||||
"""{'broken': [entry], 'tidy': [entry]}, worst first within each group.
|
"""{'broken': [entry], 'tidy': [entry]}, worst first within each group.
|
||||||
|
|
||||||
events: active alerts, annotated with 'is_suppressed'. power: topology.build_power output.
|
events: active alerts, annotated with 'is_suppressed'. power: topology.build_power output.
|
||||||
cutsheet_view: the cutsheet API view (cables with 'problem', suggestions, port_names,
|
cutsheet_view: the cutsheet API view (cables with 'problem', suggestions, port_names,
|
||||||
labels), or None when the cutsheet couldn't be loaded. rack_issues: {rack: rack_layout()}.
|
labels), or None when the cutsheet couldn't be loaded. rack_issues: {rack: rack_layout()}.
|
||||||
wan_quality: modem.wan_quality() output as stored by the monitor. modem_checks: the
|
wan_quality: modem.wan_quality() output as stored by the monitor. modem_checks: the
|
||||||
monitor's logged-in modem checks (NAT sessions, ping from the modem). now: for tests.
|
monitor's logged-in modem checks (NAT sessions, ping from the modem). modem_restart: the
|
||||||
|
Restart modem button's state, for auto power-cycle left off. now: for tests.
|
||||||
Entry: {group, severity: bad|warn|info, text, href, detail}.
|
Entry: {group, severity: bad|warn|info, text, href, detail}.
|
||||||
"""
|
"""
|
||||||
now = time.time() if now is None else now
|
now = time.time() if now is None else now
|
||||||
entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks)
|
entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks)
|
||||||
+ _alerts(events) + _power(power))
|
+ _smart_power(modem_restart) + _alerts(events) + _power(power))
|
||||||
if cutsheet_view is not None:
|
if cutsheet_view is not None:
|
||||||
entries += _cutsheet(cutsheet_view)
|
entries += _cutsheet(cutsheet_view)
|
||||||
entries += _rack(rack_issues or {})
|
entries += _rack(rack_issues or {})
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
"""Switch one Uptime Kuma maintenance window on and off (Kuma 2.x, over its Socket.IO API).
|
"""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
|
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):
|
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": "...",
|
"uptime_kuma": {"url": "http://10.10.10.25:3001", "token": "...", "maintenance_id": 7}
|
||||||
"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 logging
|
||||||
|
import threading
|
||||||
from typing import Callable, Optional
|
from typing import Callable, Optional
|
||||||
|
|
||||||
import socketio
|
import socketio
|
||||||
@@ -18,12 +20,27 @@ logger = logging.getLogger('gandalf.kuma')
|
|||||||
|
|
||||||
|
|
||||||
class KumaError(Exception):
|
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:
|
def configured(cfg: Optional[dict]) -> bool:
|
||||||
cfg = cfg or {}
|
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:
|
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(
|
factory = client_factory or (lambda: socketio.Client(
|
||||||
reconnection=False, ssl_verify=cfg.get('verify_ssl', True)))
|
reconnection=False, ssl_verify=cfg.get('verify_ssl', True)))
|
||||||
sio = factory()
|
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:
|
try:
|
||||||
sio.connect(cfg['url'], transports=['websocket'], wait_timeout=timeout)
|
sio.connect(cfg['url'], transports=['websocket'], wait_timeout=timeout)
|
||||||
res = sio.call('login', {'username': cfg['username'], 'password': cfg['password'], 'token': ''},
|
if not ready.wait(timeout):
|
||||||
timeout=timeout) or {}
|
raise KumaError('Kuma not ready (no info event after connecting)')
|
||||||
if not res.get('ok'):
|
_sign_in(sio, cfg, timeout)
|
||||||
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'
|
event = 'resumeMaintenance' if active else 'pauseMaintenance'
|
||||||
res = sio.call(event, int(cfg['maintenance_id']), timeout=timeout) or {}
|
res = sio.call(event, int(cfg['maintenance_id']), timeout=timeout) or {}
|
||||||
if not res.get('ok'):
|
if not res.get('ok'):
|
||||||
|
|||||||
@@ -383,6 +383,111 @@ def quality_counts(periods: List[dict], since: float) -> Dict[str, int]:
|
|||||||
return counts
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
# A sustained slowdown: half of the last two hours' 5 minute periods slow, lossy or down.
|
||||||
|
# It counts as over once the last two hours have at most a quarter of their periods bad,
|
||||||
|
# so one good stretch in the middle of a bad day doesn't close and reopen it.
|
||||||
|
DEGRADED_WINDOW_S = 7200
|
||||||
|
DEGRADED_FRACTION = 0.5
|
||||||
|
DEGRADED_MIN_PERIODS = 12
|
||||||
|
RECOVERED_WINDOW_S = 7200
|
||||||
|
RECOVERED_FRACTION = 0.25
|
||||||
|
|
||||||
|
|
||||||
|
def _bad_share(periods: List[dict], since: float) -> tuple:
|
||||||
|
counts = quality_counts(periods, since)
|
||||||
|
total = sum(counts.values())
|
||||||
|
return counts, total, (total - counts['ok']) / total if total else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def degradation(periods: List[dict], newest: float, fraction: float = DEGRADED_FRACTION) -> Optional[dict]:
|
||||||
|
"""{'latency', 'loss', 'down', 'bad', 'total'} over the last two hours if the WAN has
|
||||||
|
been degraded for most of them, else None. *newest* anchors the window (the newest
|
||||||
|
period's start), so a stale timeline can't look healthy or sick by the clock alone.
|
||||||
|
Needs at least an hour of periods to decide."""
|
||||||
|
counts, total, share = _bad_share(periods, newest - DEGRADED_WINDOW_S + QUALITY_PERIOD_S)
|
||||||
|
if total < DEGRADED_MIN_PERIODS or share < fraction:
|
||||||
|
return None
|
||||||
|
return dict(counts, bad=total - counts['ok'], total=total)
|
||||||
|
|
||||||
|
|
||||||
|
def recovered(periods: List[dict], newest: float) -> bool:
|
||||||
|
"""True once the last two hours have been mostly fine again."""
|
||||||
|
_counts, total, share = _bad_share(periods, newest - RECOVERED_WINDOW_S + QUALITY_PERIOD_S)
|
||||||
|
return total > 0 and share <= RECOVERED_FRACTION
|
||||||
|
|
||||||
|
|
||||||
|
# Restart entries this close together are one restart (a reboot, then Smart Power, say).
|
||||||
|
_EPISODE_GAP_S = 900
|
||||||
|
# WAN health from this long after a restart reflects the modem as it now runs.
|
||||||
|
RESTART_SETTLE_S = 900
|
||||||
|
|
||||||
|
|
||||||
|
def restart_episodes(history: dict, button: Optional[dict], since: float) -> List[dict]:
|
||||||
|
"""Modem restarts since *since*, oldest first: [{'at', 'by'}].
|
||||||
|
|
||||||
|
Folds together the UniFi log (Smart Power), uptime resets (any reboot, including one
|
||||||
|
from the AT&T app or the modem's own button) and Gandalf's Restart modem button.
|
||||||
|
Entries within 15 minutes of each other are one restart; 'by' names the most specific
|
||||||
|
cause seen: the Gandalf button, then Smart Power, then "outside Gandalf".
|
||||||
|
"""
|
||||||
|
entries = [(r['at'], 'smart power' if r.get('by') else 'outside') for r in history.get('restarts') or []
|
||||||
|
if isinstance(r.get('at'), (int, float))]
|
||||||
|
if button and isinstance(button.get('at'), (int, float)):
|
||||||
|
entries.append((button['at'], 'gandalf'))
|
||||||
|
rank = {'gandalf': 0, 'smart power': 1, 'outside': 2}
|
||||||
|
episodes: List[dict] = []
|
||||||
|
for at, by in sorted(entries):
|
||||||
|
if at < since:
|
||||||
|
continue
|
||||||
|
if episodes and at - episodes[-1]['last'] <= _EPISODE_GAP_S:
|
||||||
|
ep = episodes[-1]
|
||||||
|
ep['last'] = at
|
||||||
|
if rank[by] < rank[ep['by']]:
|
||||||
|
ep['by'] = by
|
||||||
|
else:
|
||||||
|
episodes.append({'at': at, 'last': at, 'by': by})
|
||||||
|
return [{'at': e['at'], 'by': e['by']} for e in episodes]
|
||||||
|
|
||||||
|
|
||||||
|
def unexplained_drops(outages: List[dict], episodes: List[dict], since: float) -> List[dict]:
|
||||||
|
"""WAN drops since *since* that a modem restart doesn't explain (a restart takes the
|
||||||
|
WAN down from a few minutes before its logged time to 15 minutes after)."""
|
||||||
|
def explained(o):
|
||||||
|
return any(e['at'] - 300 <= o['failed_at'] <= e['at'] + _EPISODE_GAP_S for e in episodes)
|
||||||
|
return [o for o in outages or []
|
||||||
|
if isinstance(o.get('failed_at'), (int, float)) and o['failed_at'] >= since and not explained(o)]
|
||||||
|
|
||||||
|
|
||||||
|
_RESTART_BY = {'gandalf': "Gandalf's Restart modem button", 'smart power': 'Smart Power power-cycled it',
|
||||||
|
'outside': 'restarted outside Gandalf (AT&T app, modem button or power)'}
|
||||||
|
|
||||||
|
|
||||||
|
def _span(seconds: float) -> str:
|
||||||
|
days, rest = divmod(int(seconds), 86400)
|
||||||
|
hours = rest // 3600
|
||||||
|
return f'{days} d {hours} h' if days else f'{hours} h {rest % 3600 // 60} min'
|
||||||
|
|
||||||
|
|
||||||
|
def restart_lines(episodes: List[dict], now: float) -> List[str]:
|
||||||
|
"""Markdown lines: each restart, and how long the connection went before the next one."""
|
||||||
|
lines = []
|
||||||
|
for i, e in enumerate(episodes):
|
||||||
|
when = time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(e['at']))
|
||||||
|
nxt = episodes[i + 1]['at'] if i + 1 < len(episodes) else None
|
||||||
|
after = (f', next restart {_span(nxt - e["at"])} later' if nxt
|
||||||
|
else f', {_span(now - e["at"])} ago')
|
||||||
|
lines.append(f'- {when}: {_RESTART_BY[e["by"]]}{after}')
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def replacement_hint(episodes: List[dict]) -> str:
|
||||||
|
"""Advice when restarts keep being needed: two or more in a week."""
|
||||||
|
if len(episodes) >= 2:
|
||||||
|
return (f'The modem has needed {len(episodes)} restarts in the last 7 days. If each one only '
|
||||||
|
f'fixes it for a few days, ask AT&T for a replacement BGW320.')
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# Logged-in checks, used only when an access code is configured. Two pages are
|
# Logged-in checks, used only when an access code is configured. Two pages are
|
||||||
# read: the NAT table's session counts, and the Troubleshoot page's ping test,
|
# read: the NAT table's session counts, and the Troubleshoot page's ping test,
|
||||||
|
|||||||
+299
-34
@@ -103,6 +103,36 @@ class PrometheusClient:
|
|||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# UniFi client
|
# UniFi client
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
|
class UnifiWriteError(Exception):
|
||||||
|
"""A UniFi setting couldn't be read or changed."""
|
||||||
|
|
||||||
|
|
||||||
|
def pause_smart_power(unifi) -> tuple:
|
||||||
|
"""Turn off auto power-cycle on every outlet that has it, before a deliberate modem
|
||||||
|
restart: otherwise Smart Power sees the internet down while the modem boots and cuts
|
||||||
|
its power mid-boot. Returns (paused outlets, error or None); outlets paused before an
|
||||||
|
error are still listed, so they get turned back on."""
|
||||||
|
paused: List[dict] = []
|
||||||
|
try:
|
||||||
|
for outlet in unifi.auto_power_cycle_outlets():
|
||||||
|
unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], False)
|
||||||
|
paused.append(outlet)
|
||||||
|
return paused, None
|
||||||
|
except UnifiWriteError as e:
|
||||||
|
return paused, str(e)
|
||||||
|
|
||||||
|
|
||||||
|
def restore_smart_power(unifi, paused: List[dict]) -> Optional[str]:
|
||||||
|
"""Turn auto power-cycle back on for *paused*. Returns an error, or None when all are on."""
|
||||||
|
errors = []
|
||||||
|
for outlet in paused or []:
|
||||||
|
try:
|
||||||
|
unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], True)
|
||||||
|
except UnifiWriteError as e:
|
||||||
|
errors.append(f'{outlet.get("device")} outlet {outlet.get("index")}: {e}')
|
||||||
|
return '; '.join(errors) or None
|
||||||
|
|
||||||
|
|
||||||
class UnifiClient:
|
class UnifiClient:
|
||||||
# Devices whose port tables are collected: switches and the gateway/router
|
# Devices whose port tables are collected: switches and the gateway/router
|
||||||
_PORT_DEVICE_TYPES = ('usw', 'udm', 'ugw', 'uxg')
|
_PORT_DEVICE_TYPES = ('usw', 'udm', 'ugw', 'uxg')
|
||||||
@@ -180,6 +210,59 @@ class UnifiClient:
|
|||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Smart Power auto power-cycle: the one UniFi setting Gandalf ever changes
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _stat_devices(self) -> List[dict]:
|
||||||
|
url = f'{self.base_url}/proxy/network/api/s/{self.site_id}/stat/device'
|
||||||
|
resp = self.session.get(url, headers=self.headers, timeout=15)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return resp.json().get('data', [])
|
||||||
|
|
||||||
|
def auto_power_cycle_outlets(self) -> List[dict]:
|
||||||
|
"""Outlets with Smart Power auto power-cycle on: [{'device_id', 'device', 'index', 'name'}].
|
||||||
|
In practice the modem's outlet. Raises UnifiWriteError if UniFi can't be read."""
|
||||||
|
try:
|
||||||
|
found = []
|
||||||
|
for d in self._stat_devices():
|
||||||
|
for o in d.get('outlet_overrides') or []:
|
||||||
|
if o.get('cycle_enabled') is True:
|
||||||
|
found.append({'device_id': d.get('_id'), 'device': d.get('name') or d.get('mac', ''),
|
||||||
|
'index': o.get('index'), 'name': o.get('name', '')})
|
||||||
|
return found
|
||||||
|
except Exception as e:
|
||||||
|
raise UnifiWriteError(f'reading outlets: {e}') from e
|
||||||
|
|
||||||
|
def set_auto_power_cycle(self, device_id: str, index: int, enabled: bool) -> None:
|
||||||
|
"""Turn auto power-cycle on or off for one outlet, changing nothing else.
|
||||||
|
|
||||||
|
UniFi takes the device's whole outlet_overrides list, so the current list is sent
|
||||||
|
back with only that outlet's cycle_enabled changed (relay states untouched), then
|
||||||
|
read again to confirm. Raises UnifiWriteError.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
device = next((d for d in self._stat_devices() if d.get('_id') == device_id), None)
|
||||||
|
if device is None:
|
||||||
|
raise UnifiWriteError(f'device {device_id} not found')
|
||||||
|
overrides = [dict(o) for o in device.get('outlet_overrides') or []]
|
||||||
|
target = next((o for o in overrides if o.get('index') == index), None)
|
||||||
|
if target is None:
|
||||||
|
raise UnifiWriteError(f'outlet {index} has no override entry on {device.get("name")}')
|
||||||
|
if target.get('cycle_enabled') is enabled:
|
||||||
|
return
|
||||||
|
target['cycle_enabled'] = enabled
|
||||||
|
url = f'{self.base_url}/proxy/network/api/s/{self.site_id}/rest/device/{device_id}'
|
||||||
|
resp = self.session.put(url, headers=self.headers, timeout=15, json={'outlet_overrides': overrides})
|
||||||
|
resp.raise_for_status()
|
||||||
|
check = next((d for d in self._stat_devices() if d.get('_id') == device_id), {})
|
||||||
|
now = next((o for o in check.get('outlet_overrides') or [] if o.get('index') == index), {})
|
||||||
|
if now.get('cycle_enabled') is not enabled:
|
||||||
|
raise UnifiWriteError('UniFi accepted the change but still reports the old setting')
|
||||||
|
except UnifiWriteError:
|
||||||
|
raise
|
||||||
|
except Exception as e:
|
||||||
|
raise UnifiWriteError(f'{type(e).__name__}: {e}') from e
|
||||||
|
|
||||||
def get_wired_clients(self) -> List[dict]:
|
def get_wired_clients(self) -> List[dict]:
|
||||||
"""Return wired clients as {mac, sw_mac, sw_port}; empty if unavailable."""
|
"""Return wired clients as {mac, sw_mac, sw_port}; empty if unavailable."""
|
||||||
try:
|
try:
|
||||||
@@ -1354,11 +1437,59 @@ class NetworkMonitor:
|
|||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Interface monitoring (Prometheus)
|
# 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:
|
def _process_interfaces(self, states: Dict[str, Dict[str, bool]], suppressions: list) -> None:
|
||||||
baseline = db.get_baseline()
|
baseline = db.get_baseline()
|
||||||
new_baseline = {k: dict(v) for k, v in baseline.items()}
|
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] = []
|
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():
|
for instance, ifaces in states.items():
|
||||||
if instance not in self._instance_map:
|
if instance not in self._instance_map:
|
||||||
@@ -1372,10 +1503,15 @@ class NetworkMonitor:
|
|||||||
if iface in unused:
|
if iface in unused:
|
||||||
continue # marked unused: no alerts, and it can't count as a regression
|
continue # marked unused: no alerts, and it can't count as a regression
|
||||||
prev = baseline.get(host, {}).get(iface) # 'up', 'initial_down', or None
|
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:
|
if is_up:
|
||||||
new_baseline[host][iface] = '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:
|
else:
|
||||||
if prev is None:
|
if prev is None:
|
||||||
# First observation is down: could be unused port, don't alert
|
# First observation is down: could be unused port, don't alert
|
||||||
@@ -1386,22 +1522,28 @@ class NetworkMonitor:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
else: # prev == 'up'
|
else: # prev == 'up'
|
||||||
# Regression: was UP, now DOWN
|
# Regression: was UP, now DOWN. Only a fresh drop (up on the last
|
||||||
host_has_regression = True
|
# 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 = (
|
sup = (
|
||||||
db.check_suppressed(suppressions, 'interface', host, iface) or
|
db.check_suppressed(suppressions, 'interface', host, iface) or
|
||||||
db.check_suppressed(suppressions, 'host', host)
|
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(
|
event_id, is_new, consec, ticket_id = db.upsert_event(
|
||||||
'interface_down', 'critical', 'prometheus',
|
'interface_down', 'critical', 'prometheus',
|
||||||
host, iface,
|
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:
|
if not sup and consec >= self.fail_thresh and not ticket_id:
|
||||||
self._ticket_interface(event_id, host, iface, consec)
|
self._ticket_interface(event_id, host, iface, consec)
|
||||||
|
|
||||||
if host_has_regression:
|
if host_has_regression:
|
||||||
hosts_with_regression.append(host)
|
hosts_with_regression.append(host)
|
||||||
|
network_evidence.append(host)
|
||||||
|
|
||||||
# A dead host doesn't report its interfaces as down: its series just
|
# 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.
|
# disappear, so a configured host that's absent needs its own check.
|
||||||
@@ -1409,31 +1551,55 @@ class NetworkMonitor:
|
|||||||
if instance in states:
|
if instance in states:
|
||||||
db.resolve_event('host_metrics_missing', host, instance)
|
db.resolve_event('host_metrics_missing', host, instance)
|
||||||
continue
|
continue
|
||||||
hosts_with_regression.append(host)
|
|
||||||
sup = db.check_suppressed(suppressions, 'host', host)
|
sup = db.check_suppressed(suppressions, 'host', host)
|
||||||
event_id, is_new, consec, ticket_id = db.upsert_event(
|
event_id, is_new, consec, ticket_id = db.upsert_event(
|
||||||
'host_metrics_missing', 'critical', 'prometheus',
|
'host_metrics_missing', 'critical', 'prometheus',
|
||||||
host, instance,
|
host, instance,
|
||||||
f'No metrics from {host} ({instance}): host or node_exporter is down ({_now_utc()})',
|
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:
|
if not sup and consec >= self.host_fail_thresh and not ticket_id:
|
||||||
self._ticket_metrics_missing(event_id, host, instance, consec)
|
self._ticket_metrics_missing(event_id, host, instance, consec)
|
||||||
|
|
||||||
db.set_baseline(new_baseline)
|
db.set_baseline(new_baseline)
|
||||||
|
self._check_cluster(hosts_with_regression, network_evidence, suppressions)
|
||||||
|
|
||||||
# Cluster-wide check: only genuine regressions count
|
def _check_cluster(self, failing: List[str], evidence: List[str], suppressions: list) -> None:
|
||||||
if len(hosts_with_regression) >= self.cluster_thresh:
|
"""Ticket a cluster-wide network failure only with network evidence.
|
||||||
sup = db.check_suppressed(suppressions, 'all', '')
|
|
||||||
event_id, is_new, consec, ticket_id = db.upsert_event(
|
Several hosts failing at once with every switch link still up is a stall (memory,
|
||||||
'cluster_network_issue', 'critical', 'prometheus',
|
storage, load), not the network: it's recorded as a warning with no ticket, and
|
||||||
self.cluster_name, '',
|
host health is left to hwmonDaemon.
|
||||||
f'{len(hosts_with_regression)} hosts with simultaneous interface or metrics failures: '
|
"""
|
||||||
f'{", ".join(hosts_with_regression)}',
|
if len(failing) < self.cluster_thresh:
|
||||||
)
|
|
||||||
if not sup and (is_new or not ticket_id):
|
|
||||||
self._ticket_cluster(event_id, hosts_with_regression)
|
|
||||||
else:
|
|
||||||
db.resolve_event('cluster_network_issue', self.cluster_name, '')
|
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:
|
def _ticket_cluster(self, event_id: int, hosts: List[str]) -> None:
|
||||||
switches = self._switches()
|
switches = self._switches()
|
||||||
@@ -1937,11 +2103,13 @@ class NetworkMonitor:
|
|||||||
actionable = modem_api.apply_wan_events(
|
actionable = modem_api.apply_wan_events(
|
||||||
history, [e for e in events if not modem_api.is_update_key(e['key'])])
|
history, [e for e in events if not modem_api.is_update_key(e['key'])])
|
||||||
|
|
||||||
# UniFi repeats "failed multiple times" per failure, so ticket it once a day at most.
|
# UniFi repeats "failed multiple times" per failure, so ticket it once a day at most,
|
||||||
|
# and decide a few minutes later: a modem reboot's own drops trigger it too, and the
|
||||||
|
# uptime reset that proves the reboot only shows once the modem answers again.
|
||||||
unstable = [e for e in actionable if e['key'] == modem_api.LOG_WAN_UNSTABLE]
|
unstable = [e for e in actionable if e['key'] == modem_api.LOG_WAN_UNSTABLE]
|
||||||
ticket_unstable = bool(unstable) and now - history.get('unstable_ticketed_at', 0) >= 86400
|
if (unstable and not history.get('unstable_pending_at')
|
||||||
if ticket_unstable:
|
and now - history.get('unstable_ticketed_at', 0) >= 86400):
|
||||||
history['unstable_ticketed_at'] = now
|
history['unstable_pending_at'] = now
|
||||||
|
|
||||||
# Save first: a failed ticket call shouldn't replay these events next cycle.
|
# Save first: a failed ticket call shouldn't replay these events next cycle.
|
||||||
db.set_state('wan_history', history)
|
db.set_state('wan_history', history)
|
||||||
@@ -1958,21 +2126,94 @@ class NetworkMonitor:
|
|||||||
'The internet connection failed badly enough to trigger auto power-cycle. '
|
'The internet connection failed badly enough to trigger auto power-cycle. '
|
||||||
'Check the WAN / Fiber panel for outages around this time and Rx power for a drop.',
|
'Check the WAN / Fiber panel for outages around this time and Rx power for a drop.',
|
||||||
)
|
)
|
||||||
if ticket_unstable:
|
UNSTABLE_DECIDE_AFTER_S = 600
|
||||||
self._one_shot_ticket(
|
|
||||||
suppressions, 'wan_unstable',
|
|
||||||
'UniFi reports the WAN connection went down multiple times in the last 24 hours.',
|
|
||||||
'WAN connection unstable', '2',
|
|
||||||
'See the WAN history on the modem page. Repeated drops with healthy Rx power '
|
|
||||||
'point toward the provider or the modem rather than the fiber.',
|
|
||||||
)
|
|
||||||
|
|
||||||
def _collect_wan_quality(self) -> None:
|
def _restart_context(self, now: float) -> tuple:
|
||||||
|
"""(restart episodes in the last 7 days, markdown lines, replacement hint)."""
|
||||||
|
raw = db.get_state('modem_restart')
|
||||||
|
try:
|
||||||
|
button = json.loads(raw) if raw else None
|
||||||
|
except ValueError:
|
||||||
|
button = None
|
||||||
|
episodes = modem_api.restart_episodes(self._load_wan_history(), button, now - 7 * 86400)
|
||||||
|
return episodes, modem_api.restart_lines(episodes, now), modem_api.replacement_hint(episodes)
|
||||||
|
|
||||||
|
def _decide_unstable(self, suppressions: list) -> None:
|
||||||
|
"""Ticket UniFi's "WAN failed multiple times" only if drops remain that no modem
|
||||||
|
restart explains. A reboot (from the AT&T app, Smart Power or Gandalf) drops the WAN
|
||||||
|
once or twice by itself, and that alone used to open this ticket."""
|
||||||
|
history = self._load_wan_history()
|
||||||
|
pending = history.get('unstable_pending_at')
|
||||||
|
now = time.time()
|
||||||
|
if not pending or now - pending < self.UNSTABLE_DECIDE_AFTER_S:
|
||||||
|
return
|
||||||
|
history.pop('unstable_pending_at', None)
|
||||||
|
episodes, lines, hint = self._restart_context(now)
|
||||||
|
drops = modem_api.unexplained_drops(history.get('outages'), episodes, now - 86400)
|
||||||
|
if len(drops) < 2:
|
||||||
|
db.set_state('wan_history', history)
|
||||||
|
logger.info(f'WAN "failed multiple times" explained by modem restarts '
|
||||||
|
f'({len(drops)} other drop(s) in 24 h): no ticket')
|
||||||
|
return
|
||||||
|
history['unstable_ticketed_at'] = now
|
||||||
|
db.set_state('wan_history', history)
|
||||||
|
description = (f'UniFi reports the WAN connection went down multiple times in the last 24 hours: '
|
||||||
|
f'{len(drops)} drops not explained by a modem restart.')
|
||||||
|
if lines:
|
||||||
|
description += '\n\nModem restarts in the last 7 days:\n' + '\n'.join(lines)
|
||||||
|
self._one_shot_ticket(
|
||||||
|
suppressions, 'wan_unstable', description, 'WAN connection unstable', '2',
|
||||||
|
'See the WAN history on the modem page. Repeated drops with healthy Rx power '
|
||||||
|
'point toward the provider or the modem rather than the fiber.' + (f' {hint}' if hint else ''),
|
||||||
|
)
|
||||||
|
|
||||||
|
def _collect_wan_quality(self) -> Optional[dict]:
|
||||||
"""Store UniFi's WAN health timeline. If UniFi can't be read, the last copy stays
|
"""Store UniFi's WAN health timeline. If UniFi can't be read, the last copy stays
|
||||||
and goes stale, and the dashboard stops drawing conclusions from it."""
|
and goes stale, and the dashboard stops drawing conclusions from it."""
|
||||||
quality = modem_api.wan_quality(self.unifi.get_wan_dashboard(), time.time())
|
quality = modem_api.wan_quality(self.unifi.get_wan_dashboard(), time.time())
|
||||||
if quality is not None:
|
if quality is not None:
|
||||||
db.set_state('wan_quality', quality)
|
db.set_state('wan_quality', quality)
|
||||||
|
return quality
|
||||||
|
|
||||||
|
def _process_wan_degraded(self, quality: Optional[dict], suppressions: list) -> None:
|
||||||
|
"""Ticket a sustained slowdown: most of the last two hours slow, lossy or down by
|
||||||
|
UniFi's own measure. It closes, with a recovery note, once two hours are mostly fine."""
|
||||||
|
periods = (quality or {}).get('periods') or []
|
||||||
|
if not periods:
|
||||||
|
return # nothing fresh to judge by: leave any open alert as it is
|
||||||
|
newest = periods[-1]['ts']
|
||||||
|
episodes, lines, hint = self._restart_context(time.time())
|
||||||
|
if episodes:
|
||||||
|
# A restart resets the judgement: only what came after it (once it has settled)
|
||||||
|
# counts, so a slowdown it fixed neither opens a ticket nor holds one open.
|
||||||
|
periods = [p for p in periods if p['ts'] >= episodes[-1]['at'] + modem_api.RESTART_SETTLE_S]
|
||||||
|
if not periods:
|
||||||
|
return
|
||||||
|
fraction = float((self.cfg.get('modem') or {}).get('degraded_fraction', modem_api.DEGRADED_FRACTION))
|
||||||
|
bad = modem_api.degradation(periods, newest, fraction)
|
||||||
|
if bad is None:
|
||||||
|
if modem_api.recovered(periods, newest):
|
||||||
|
db.resolve_event('wan_degraded', self.modem_name, '')
|
||||||
|
return
|
||||||
|
parts = [f'{bad[s]} {s}' for s in ('latency', 'loss', 'down') if bad[s]]
|
||||||
|
description = (f'The internet has been degraded for most of the last 2 hours: {bad["bad"]} of '
|
||||||
|
f'{bad["total"]} five-minute periods had {", ".join(parts)} (UniFi WAN health).')
|
||||||
|
try:
|
||||||
|
raw = db.get_state('modem_checks')
|
||||||
|
ping = ((json.loads(raw) if isinstance(raw, str) else raw) or {}).get('ping') or {}
|
||||||
|
except (ValueError, AttributeError):
|
||||||
|
ping = {}
|
||||||
|
if ping.get('verdict') == 'gateway':
|
||||||
|
description += (f' A ping from the modem itself was slow too (avg {ping.get("avg_ms")} ms), '
|
||||||
|
f'so the modem or the line past it is the slow hop, not the LAN.')
|
||||||
|
if lines:
|
||||||
|
description += '\n\nModem restarts in the last 7 days:\n' + '\n'.join(lines)
|
||||||
|
advice = ('Restart the modem from the WAN / Fiber panel (Restart modem): it silences Gandalf '
|
||||||
|
'and Uptime Kuma while it reboots.')
|
||||||
|
if hint:
|
||||||
|
advice += f' {hint}'
|
||||||
|
self._modem_event(suppressions, 'wan_degraded', 'warning', '', description,
|
||||||
|
'Internet degraded (high latency or packet loss)', '2', advice)
|
||||||
|
|
||||||
_RESTART_SETTLE_S = 180 # the modem answering this soon may not have restarted yet
|
_RESTART_SETTLE_S = 180 # the modem answering this soon may not have restarted yet
|
||||||
_RESTART_GIVE_UP_S = 1800
|
_RESTART_GIVE_UP_S = 1800
|
||||||
@@ -1986,7 +2227,13 @@ class NetworkMonitor:
|
|||||||
state = json.loads(raw) if raw else None
|
state = json.loads(raw) if raw else None
|
||||||
except ValueError:
|
except ValueError:
|
||||||
state = None
|
state = None
|
||||||
if not state or state.get('finished_at'):
|
if not state:
|
||||||
|
return
|
||||||
|
if state.get('finished_at'):
|
||||||
|
# Auto power-cycle must not stay off: keep retrying until it's back on
|
||||||
|
if state.get('smart_power_paused') and not state.get('smart_power_restored'):
|
||||||
|
self._restore_smart_power(state)
|
||||||
|
db.set_state('modem_restart', state)
|
||||||
return
|
return
|
||||||
now = time.time()
|
now = time.time()
|
||||||
age = now - state.get('at', now)
|
age = now - state.get('at', now)
|
||||||
@@ -2012,12 +2259,25 @@ class NetworkMonitor:
|
|||||||
state['kuma_error'] = str(e)
|
state['kuma_error'] = str(e)
|
||||||
if state.get('suppression_id'):
|
if state.get('suppression_id'):
|
||||||
db.deactivate_suppression(state['suppression_id'])
|
db.deactivate_suppression(state['suppression_id'])
|
||||||
|
if state.get('smart_power_paused'):
|
||||||
|
self._restore_smart_power(state)
|
||||||
state.update(finished_at=now, back=bool(back), rebooted=rebooted,
|
state.update(finished_at=now, back=bool(back), rebooted=rebooted,
|
||||||
back_after_s=round(age) if back else None)
|
back_after_s=round(age) if back else None)
|
||||||
db.set_state('modem_restart', state)
|
db.set_state('modem_restart', state)
|
||||||
logger.info(f'Modem restart finished: {"back" if back else "gave up waiting"} after {round(age)} s'
|
logger.info(f'Modem restart finished: {"back" if back else "gave up waiting"} after {round(age)} s'
|
||||||
f'{", rebooted" if rebooted else ""}')
|
f'{", rebooted" if rebooted else ""}')
|
||||||
|
|
||||||
|
def _restore_smart_power(self, state: dict) -> None:
|
||||||
|
"""Turn auto power-cycle back on for the outlets the restart paused; note the result."""
|
||||||
|
err = restore_smart_power(self.unifi, state['smart_power_paused'])
|
||||||
|
if err:
|
||||||
|
logger.error(f'Smart Power auto power-cycle is still off: {err}')
|
||||||
|
state['smart_power_error'] = err
|
||||||
|
else:
|
||||||
|
logger.info(f'Smart Power auto power-cycle back on for '
|
||||||
|
f'{len(state["smart_power_paused"])} outlet(s)')
|
||||||
|
state.update(smart_power_restored=True, smart_power_error=None)
|
||||||
|
|
||||||
_NAT_EVERY_S = 1800 # NAT sessions and the gateway's speed test history
|
_NAT_EVERY_S = 1800 # NAT sessions and the gateway's speed test history
|
||||||
_FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes
|
_FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes
|
||||||
_FIREWALL_HOURS = 24
|
_FIREWALL_HOURS = 24
|
||||||
@@ -2283,12 +2543,17 @@ class NetworkMonitor:
|
|||||||
with self._wan_batch():
|
with self._wan_batch():
|
||||||
self._process_wan_log(suppressions)
|
self._process_wan_log(suppressions)
|
||||||
self._collect_modem(suppressions)
|
self._collect_modem(suppressions)
|
||||||
|
self._decide_unstable(suppressions)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f'Modem collection failed: {e}', exc_info=True)
|
logger.error(f'Modem collection failed: {e}', exc_info=True)
|
||||||
|
|
||||||
# Internet quality as UniFi measures it (latency, loss, drops): for the dashboard
|
# Internet quality as UniFi measures it (latency, loss, drops): for the
|
||||||
|
# dashboard, and a ticket when it stays bad
|
||||||
try:
|
try:
|
||||||
self._collect_wan_quality()
|
quality = self._collect_wan_quality()
|
||||||
|
if self.modem:
|
||||||
|
with self._wan_batch():
|
||||||
|
self._process_wan_degraded(quality, suppressions)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f'WAN quality collection failed: {e}', exc_info=True)
|
logger.error(f'WAN quality collection failed: {e}', exc_info=True)
|
||||||
|
|
||||||
|
|||||||
+10
-3
@@ -474,9 +474,16 @@ function _modemQuality(q) {
|
|||||||
function _modemRestartNote(r) {
|
function _modemRestartNote(r) {
|
||||||
if (!r || !r.at) return '';
|
if (!r || !r.at) return '';
|
||||||
const who = r.by ? ` by ${r.by}` : '';
|
const who = r.by ? ` by ${r.by}` : '';
|
||||||
|
const paused = (r.smart_power_paused || []).length;
|
||||||
if (!r.finished_at) {
|
if (!r.finished_at) {
|
||||||
|
const sp = paused ? ' Smart Power auto power-cycle is paused so it can\'t cut power mid-boot.' : '';
|
||||||
return `<div class="modem-restart-note">Restart requested${lt.escHtml(who)} ${lt.escHtml(_modemWhen(r.at))}. ` +
|
return `<div class="modem-restart-note">Restart requested${lt.escHtml(who)} ${lt.escHtml(_modemWhen(r.at))}. ` +
|
||||||
`Alerts are silenced${r.kuma ? ' here and in Uptime Kuma' : ''} until the modem is back.</div>`;
|
`Alerts are silenced${r.kuma ? ' here and in Uptime Kuma' : ''} until the modem is back.${sp}</div>`;
|
||||||
|
}
|
||||||
|
if (paused && !r.smart_power_restored) {
|
||||||
|
return `<div class="modem-restart-note modem-restart-warn">Restarted${lt.escHtml(who)} ` +
|
||||||
|
`${lt.escHtml(_modemWhen(r.at))}, but Smart Power auto power-cycle is still off. ` +
|
||||||
|
`Gandalf keeps trying to turn it back on.</div>`;
|
||||||
}
|
}
|
||||||
if (Date.now() / 1000 - r.finished_at > 3600) return '';
|
if (Date.now() / 1000 - r.finished_at > 3600) return '';
|
||||||
const how = r.back ? `back after ${_modemDuration(r.back_after_s)}` : 'did not come back within 30 minutes';
|
const how = r.back ? `back after ${_modemDuration(r.back_after_s)}` : 'did not come back within 30 minutes';
|
||||||
@@ -486,8 +493,8 @@ function _modemRestartNote(r) {
|
|||||||
|
|
||||||
async function restartModem(btn) {
|
async function restartModem(btn) {
|
||||||
const msg = 'Restart the AT&T modem?\n\nThe internet will be down for about 3 to 5 minutes. ' +
|
const msg = 'Restart the AT&T modem?\n\nThe internet will be down for about 3 to 5 minutes. ' +
|
||||||
'Gandalf alerts and the Uptime Kuma maintenance window are switched on first, and switched off ' +
|
'Gandalf alerts, the Uptime Kuma maintenance window and a Smart Power auto power-cycle pause ' +
|
||||||
'again when the modem is back.';
|
'are switched on first, and switched off again when the modem is back.';
|
||||||
if (!window.confirm(msg)) return;
|
if (!window.confirm(msg)) return;
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1854,3 +1854,4 @@ body > .lt-footer { flex-shrink: 0; }
|
|||||||
.modem-actions { display: inline-flex; gap: 6px; }
|
.modem-actions { display: inline-flex; gap: 6px; }
|
||||||
.modem-restart-note { margin: 8px 12px 0; padding: 6px 10px; font-size: .8em;
|
.modem-restart-note { margin: 8px 12px 0; padding: 6px 10px; font-size: .8em;
|
||||||
border: 1px solid var(--accent-amber); color: var(--text-primary); }
|
border: 1px solid var(--accent-amber); color: var(--text-primary); }
|
||||||
|
.modem-restart-note.modem-restart-warn { border-color: var(--accent-red); }
|
||||||
+34
-4
@@ -879,17 +879,26 @@ class TestCalmDashboard:
|
|||||||
|
|
||||||
class TestModemRestart:
|
class TestModemRestart:
|
||||||
CFG = dict(CONFIG, modem={'url': 'http://192.0.2.254', 'access_code': 'secret'},
|
CFG = dict(CONFIG, modem={'url': 'http://192.0.2.254', 'access_code': 'secret'},
|
||||||
uptime_kuma={'url': 'http://kuma.test', 'username': 'u', 'password': 'p', 'maintenance_id': 7})
|
uptime_kuma={'url': 'http://kuma.test', 'username': 'u', 'password': 'p', 'maintenance_id': 7},
|
||||||
|
unifi={'controller': 'https://udm.test', 'api_key': 'k'})
|
||||||
|
|
||||||
def _post(self, client, body=None, headers=AUTH, cfg=None, kuma_error=None, restart=None):
|
OUTLET = {'device_id': 'pdu1', 'device': 'RPDU', 'index': 13, 'name': 'AT&T Modem'}
|
||||||
|
|
||||||
|
def _post(self, client, body=None, headers=AUTH, cfg=None, kuma_error=None, restart=None,
|
||||||
|
paused=None, restore_error=None):
|
||||||
admin = MagicMock()
|
admin = MagicMock()
|
||||||
if isinstance(restart, Exception):
|
if isinstance(restart, Exception):
|
||||||
admin.restart.side_effect = restart
|
admin.restart.side_effect = restart
|
||||||
else:
|
else:
|
||||||
admin.restart.return_value = restart or 'accepted'
|
admin.restart.return_value = restart or 'accepted'
|
||||||
|
self.pause = MagicMock(return_value=paused or ([self.OUTLET], None))
|
||||||
|
self.restore = MagicMock(return_value=restore_error)
|
||||||
with patch.object(gandalf, '_cfg', cfg or self.CFG), \
|
with patch.object(gandalf, '_cfg', cfg or self.CFG), \
|
||||||
patch.object(gandalf.kuma, 'set_maintenance', side_effect=kuma_error) as km, \
|
patch.object(gandalf.kuma, 'set_maintenance', side_effect=kuma_error) as km, \
|
||||||
patch.object(gandalf.modem_api, 'ModemAdmin', return_value=admin):
|
patch.object(gandalf.modem_api, 'ModemAdmin', return_value=admin), \
|
||||||
|
patch.object(gandalf, 'UnifiClient', MagicMock()), \
|
||||||
|
patch.object(gandalf, 'pause_smart_power', self.pause), \
|
||||||
|
patch.object(gandalf, 'restore_smart_power', self.restore):
|
||||||
gandalf.db.create_suppression.return_value = 42
|
gandalf.db.create_suppression.return_value = 42
|
||||||
resp = client.post('/api/modem/restart', json=body if body is not None else {'confirm': True},
|
resp = client.post('/api/modem/restart', json=body if body is not None else {'confirm': True},
|
||||||
headers=headers)
|
headers=headers)
|
||||||
@@ -910,13 +919,34 @@ class TestModemRestart:
|
|||||||
def test_silences_then_restarts(self, client):
|
def test_silences_then_restarts(self, client):
|
||||||
resp, km, admin = self._post(client)
|
resp, km, admin = self._post(client)
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert resp.get_json() == {'ok': True, 'result': 'accepted', 'kuma': True, 'suppression_id': 42}
|
assert resp.get_json() == {'ok': True, 'result': 'accepted', 'kuma': True, 'suppression_id': 42,
|
||||||
|
'smart_power_paused': 1, 'smart_power_error': None}
|
||||||
km.assert_called_once_with(self.CFG['uptime_kuma'], True)
|
km.assert_called_once_with(self.CFG['uptime_kuma'], True)
|
||||||
args = gandalf.db.create_suppression.call_args.args
|
args = gandalf.db.create_suppression.call_args.args
|
||||||
assert args[:3] == ('all', '', '') and args[4] == 'jared' and args[5] == gandalf.MODEM_RESTART_SILENCE_MIN
|
assert args[:3] == ('all', '', '') and args[4] == 'jared' and args[5] == gandalf.MODEM_RESTART_SILENCE_MIN
|
||||||
admin.restart.assert_called_once_with()
|
admin.restart.assert_called_once_with()
|
||||||
key, state = gandalf.db.set_state.call_args.args
|
key, state = gandalf.db.set_state.call_args.args
|
||||||
assert key == 'modem_restart' and state['suppression_id'] == 42 and state['kuma'] is True
|
assert key == 'modem_restart' and state['suppression_id'] == 42 and state['kuma'] is True
|
||||||
|
assert state['smart_power_paused'] == [self.OUTLET]
|
||||||
|
assert self.pause.called and not self.restore.called
|
||||||
|
|
||||||
|
def test_smart_power_failure_does_not_stop_the_restart(self, client):
|
||||||
|
resp, _, admin = self._post(client, paused=([], 'HTTP 401'))
|
||||||
|
assert resp.status_code == 200 and admin.restart.called
|
||||||
|
assert resp.get_json()['smart_power_error'] == 'HTTP 401'
|
||||||
|
|
||||||
|
def test_failed_restart_turns_smart_power_back_on(self, client):
|
||||||
|
resp, _, _ = self._post(client, restart=gandalf.modem_api.ModemUnreachable('timeout'))
|
||||||
|
assert resp.status_code == 502
|
||||||
|
assert self.restore.call_args.args[1] == [self.OUTLET]
|
||||||
|
|
||||||
|
def test_failed_restart_and_failed_restore_is_remembered(self, client):
|
||||||
|
resp, _, _ = self._post(client, restart=gandalf.modem_api.ModemUnreachable('timeout'),
|
||||||
|
restore_error='HTTP 500')
|
||||||
|
assert resp.status_code == 502
|
||||||
|
key, state = gandalf.db.set_state.call_args.args
|
||||||
|
assert key == 'modem_restart' and state['finished_at'] and state['smart_power_error'] == 'HTTP 500'
|
||||||
|
assert state['smart_power_paused'] == [self.OUTLET] and not state.get('smart_power_restored')
|
||||||
|
|
||||||
def test_kuma_failure_stops_unless_accepted(self, client):
|
def test_kuma_failure_stops_unless_accepted(self, client):
|
||||||
resp, _, admin = self._post(client, kuma_error=gandalf.kuma.KumaError('login refused'))
|
resp, _, admin = self._post(client, kuma_error=gandalf.kuma.KumaError('login refused'))
|
||||||
|
|||||||
@@ -181,3 +181,19 @@ class TestModemChecks:
|
|||||||
|
|
||||||
def test_other_errors_stay_quiet(self):
|
def test_other_errors_stay_quiet(self):
|
||||||
assert self._broken({'error': {'login': False, 'message': 'timeout', 'at': NOW}})['tidy'] == []
|
assert self._broken({'error': {'login': False, 'message': 'timeout', 'at': NOW}})['tidy'] == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestSmartPowerLeftOff:
|
||||||
|
OUTLET = {'device': 'RPDU', 'index': 13}
|
||||||
|
|
||||||
|
def test_left_off_after_restart_is_broken(self):
|
||||||
|
r = {'finished_at': 1.0, 'smart_power_paused': [self.OUTLET], 'smart_power_error': 'HTTP 500'}
|
||||||
|
out = attention.build([], [], None, modem_restart=r)
|
||||||
|
e = out['broken'][0]
|
||||||
|
assert e['severity'] == 'bad' and 'still off' in e['text']
|
||||||
|
assert 'RPDU outlet 13' in e['detail'] and 'HTTP 500' in e['detail']
|
||||||
|
|
||||||
|
def test_restored_or_in_progress_says_nothing(self):
|
||||||
|
for r in ({'finished_at': 1.0, 'smart_power_paused': [self.OUTLET], 'smart_power_restored': True},
|
||||||
|
{'finished_at': None, 'smart_power_paused': [self.OUTLET]}, None):
|
||||||
|
assert attention.build([], [], None, modem_restart=r)['broken'] == []
|
||||||
+39
-17
@@ -7,19 +7,26 @@ import pytest
|
|||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||||
import kuma # noqa: E402
|
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:
|
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.answers = answers or {}
|
||||||
self.connect_error = connect_error
|
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):
|
def connect(self, url, **kw):
|
||||||
if self.connect_error:
|
if self.connect_error:
|
||||||
raise self.connect_error
|
raise self.connect_error
|
||||||
self.url = url
|
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):
|
def call(self, event, data=None, timeout=None):
|
||||||
self.calls.append((event, data))
|
self.calls.append((event, data))
|
||||||
@@ -29,34 +36,49 @@ class FakeSocket:
|
|||||||
self.disconnected = True
|
self.disconnected = True
|
||||||
|
|
||||||
|
|
||||||
def run(active=True, **kw):
|
def run(active=True, cfg=CFG, **kw):
|
||||||
sock = FakeSocket(**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
|
return sock
|
||||||
|
|
||||||
|
|
||||||
class TestKuma:
|
class TestKuma:
|
||||||
def test_configured_needs_every_field(self):
|
def test_configured_needs_url_window_and_a_way_to_sign_in(self):
|
||||||
assert kuma.configured(CFG)
|
assert kuma.configured(CFG) and kuma.configured(PASSWORD_CFG)
|
||||||
assert not kuma.configured(dict(CFG, password=''))
|
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)
|
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)
|
sock = run(True)
|
||||||
assert sock.calls == [('login', {'username': 'gandalf', 'password': 'pw', 'token': ''}),
|
assert sock.calls == [('loginByToken', 'tok'), ('resumeMaintenance', 7)]
|
||||||
('resumeMaintenance', 7)]
|
|
||||||
assert sock.disconnected and sock.url == CFG['url']
|
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):
|
def test_pause(self):
|
||||||
assert run(False).calls[-1] == ('pauseMaintenance', 7)
|
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'):
|
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):
|
def test_two_factor_account_needs_the_token(self):
|
||||||
with pytest.raises(kuma.KumaError, match='two-factor'):
|
with pytest.raises(kuma.KumaError, match='use uptime_kuma.token'):
|
||||||
run(answers={'login': {'ok': False, 'tokenRequired': True}})
|
run(cfg=PASSWORD_CFG, answers={'login': {'ok': False, 'tokenRequired': True}})
|
||||||
|
|
||||||
def test_refused_change(self):
|
def test_refused_change(self):
|
||||||
with pytest.raises(kuma.KumaError, match='resumeMaintenance refused'):
|
with pytest.raises(kuma.KumaError, match='resumeMaintenance refused'):
|
||||||
@@ -65,5 +87,5 @@ class TestKuma:
|
|||||||
def test_unreachable(self):
|
def test_unreachable(self):
|
||||||
sock = FakeSocket(connect_error=ConnectionError('refused'))
|
sock = FakeSocket(connect_error=ConnectionError('refused'))
|
||||||
with pytest.raises(kuma.KumaError, match='ConnectionError'):
|
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
|
assert sock.disconnected
|
||||||
@@ -558,3 +558,56 @@ class TestModemRestart:
|
|||||||
a.session.post = MagicMock(return_value=MagicMock(status_code=200, text=LOGIN_FORM))
|
a.session.post = MagicMock(return_value=MagicMock(status_code=200, text=LOGIN_FORM))
|
||||||
with pytest.raises(modem.ModemDataInvalid, match='not started'):
|
with pytest.raises(modem.ModemDataInvalid, match='not started'):
|
||||||
a.restart()
|
a.restart()
|
||||||
|
|
||||||
|
|
||||||
|
class TestRestartEpisodes:
|
||||||
|
def test_reboot_then_smart_power_is_one_restart(self):
|
||||||
|
h = {'restarts': [{'at': 1000, 'by': None}, {'at': 1200, 'by': 'RPDU'}, {'at': 1590, 'by': 'RPDU'}]}
|
||||||
|
assert modem.restart_episodes(h, None, 0) == [{'at': 1000, 'by': 'smart power'}]
|
||||||
|
|
||||||
|
def test_gandalf_button_names_the_restart(self):
|
||||||
|
h = {'restarts': [{'at': 1100, 'by': 'RPDU'}]}
|
||||||
|
assert modem.restart_episodes(h, {'at': 1000}, 0) == [{'at': 1000, 'by': 'gandalf'}]
|
||||||
|
|
||||||
|
def test_separate_days_are_separate_restarts(self):
|
||||||
|
h = {'restarts': [{'at': 1000, 'by': None}, {'at': 1000 + 86400, 'by': None}]}
|
||||||
|
assert len(modem.restart_episodes(h, None, 0)) == 2
|
||||||
|
|
||||||
|
def test_older_than_since_is_left_out(self):
|
||||||
|
assert modem.restart_episodes({'restarts': [{'at': 10, 'by': None}]}, None, 100) == []
|
||||||
|
|
||||||
|
def test_unexplained_drops(self):
|
||||||
|
eps = [{'at': 1000, 'by': 'outside'}]
|
||||||
|
outs = [{'failed_at': 800}, {'failed_at': 1800}, {'failed_at': 5000}, {'failed_at': 50}]
|
||||||
|
assert modem.unexplained_drops(outs, eps, 100) == [{'failed_at': 5000}]
|
||||||
|
|
||||||
|
def test_lines_and_hint(self):
|
||||||
|
eps = [{'at': 0, 'by': 'gandalf'}, {'at': 3 * 86400 + 4 * 3600, 'by': 'outside'}]
|
||||||
|
lines = modem.restart_lines(eps, 3 * 86400 + 5 * 3600)
|
||||||
|
assert lines[0].endswith("Gandalf's Restart modem button, next restart 3 d 4 h later")
|
||||||
|
assert lines[1].endswith('restarted outside Gandalf (AT&T app, modem button or power), 1 h 0 min ago')
|
||||||
|
assert 'replacement BGW320' in modem.replacement_hint(eps)
|
||||||
|
assert modem.replacement_hint(eps[:1]) == ''
|
||||||
|
|
||||||
|
|
||||||
|
class TestDegradation:
|
||||||
|
def periods(self, states, end=10000.0):
|
||||||
|
return [{'ts': end - (len(states) - 1 - i) * 300, 'state': s} for i, s in enumerate(states)]
|
||||||
|
|
||||||
|
def test_half_of_two_hours_is_degraded(self):
|
||||||
|
d = modem.degradation(self.periods(['ok'] * 12 + ['loss'] * 12), 10000.0)
|
||||||
|
assert d['bad'] == 12 and d['total'] == 24 and d['loss'] == 12
|
||||||
|
|
||||||
|
def test_under_half_is_not(self):
|
||||||
|
assert modem.degradation(self.periods(['ok'] * 13 + ['loss'] * 11), 10000.0) is None
|
||||||
|
|
||||||
|
def test_needs_an_hour_of_data(self):
|
||||||
|
assert modem.degradation(self.periods(['loss'] * 6), 10000.0) is None
|
||||||
|
|
||||||
|
def test_window_ignores_older_periods(self):
|
||||||
|
assert modem.degradation(self.periods(['loss'] * 30 + ['ok'] * 24), 10000.0 + 0) is None
|
||||||
|
|
||||||
|
def test_recovered(self):
|
||||||
|
assert modem.recovered(self.periods(['loss'] * 12 + ['ok'] * 18 + ['latency'] * 6), 10000.0)
|
||||||
|
assert modem.recovered(self.periods(['loss'] * 6 + ['ok'] * 18), 10000.0) # exactly a quarter
|
||||||
|
assert not modem.recovered(self.periods(['latency'] * 7 + ['ok'] * 17), 10000.0)
|
||||||
+294
-1
@@ -138,6 +138,113 @@ class TestDeadHostDetection:
|
|||||||
assert snap['hosts']['beta']['status'] == 'down'
|
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:
|
class TestPrometheusOutage:
|
||||||
def test_empty_result_means_unavailable(self):
|
def test_empty_result_means_unavailable(self):
|
||||||
client = monitor.PrometheusClient('http://prom.test')
|
client = monitor.PrometheusClient('http://prom.test')
|
||||||
@@ -368,13 +475,62 @@ class TestWanLog:
|
|||||||
mon._process_wan_log([])
|
mon._process_wan_log([])
|
||||||
assert not mon.tickets.create.called
|
assert not mon.tickets.create.called
|
||||||
|
|
||||||
def test_unstable_wan_tickets_after_a_day(self, mon, db):
|
def test_unstable_wan_waits_before_deciding(self, mon, db):
|
||||||
now = time.time()
|
now = time.time()
|
||||||
self._state(db, unifi_log_cursor=str(int(now * 1000)))
|
self._state(db, unifi_log_cursor=str(int(now * 1000)))
|
||||||
self._mon(mon, [{'key': modem_api.LOG_WAN_UNSTABLE, 'ts': now, 'device': 'UDM', 'wan': 'WAN1'}])
|
self._mon(mon, [{'key': modem_api.LOG_WAN_UNSTABLE, 'ts': now, 'device': 'UDM', 'wan': 'WAN1'}])
|
||||||
mon._process_wan_log([])
|
mon._process_wan_log([])
|
||||||
|
assert not mon.tickets.create.called
|
||||||
|
saved = dict((c.args[0], c.args[1]) for c in db.set_state.call_args_list)
|
||||||
|
assert saved['wan_history']['unstable_pending_at'] >= now
|
||||||
|
|
||||||
|
def _decide(self, mon, db, outages, restarts, button=None, pending_age=700):
|
||||||
|
now = time.time()
|
||||||
|
history = {'outages': outages, 'restarts': restarts, 'unstable_pending_at': now - pending_age}
|
||||||
|
self._state(db, wan_history=json.dumps(history),
|
||||||
|
modem_restart=json.dumps(button) if button else None)
|
||||||
|
mon._decide_unstable([])
|
||||||
|
return now
|
||||||
|
|
||||||
|
def test_drops_with_no_restart_ticket_after_the_wait(self, mon, db):
|
||||||
|
now = time.time()
|
||||||
|
self._decide(mon, db, [{'failed_at': now - 5000}, {'failed_at': now - 900}], [])
|
||||||
assert 'unstable' in mon.tickets.create.call_args.args[0]
|
assert 'unstable' in mon.tickets.create.call_args.args[0]
|
||||||
|
|
||||||
|
def test_not_decided_before_the_wait(self, mon, db):
|
||||||
|
now = time.time()
|
||||||
|
self._decide(mon, db, [{'failed_at': now - 5000}, {'failed_at': now - 900}], [], pending_age=60)
|
||||||
|
assert not mon.tickets.create.called
|
||||||
|
|
||||||
|
def test_reboot_drops_alone_open_no_ticket(self, mon, db):
|
||||||
|
# 2026-11-24: an AT&T-app reboot, Smart Power cycling it twice, two short drops
|
||||||
|
now = time.time()
|
||||||
|
boot = now - 1500
|
||||||
|
self._decide(mon, db,
|
||||||
|
[{'failed_at': boot + 180}, {'failed_at': boot + 600}],
|
||||||
|
[{'at': boot, 'by': 'RPDU', 'confirmed': True},
|
||||||
|
{'at': boot + 386, 'by': 'RPDU', 'confirmed': False}])
|
||||||
|
assert not mon.tickets.create.called
|
||||||
|
saved = dict((c.args[0], c.args[1]) for c in db.set_state.call_args_list)
|
||||||
|
assert 'unstable_pending_at' not in saved['wan_history']
|
||||||
|
|
||||||
|
def test_restart_by_gandalf_button_explains_its_drop(self, mon, db):
|
||||||
|
now = time.time()
|
||||||
|
self._decide(mon, db, [{'failed_at': now - 1200}, {'failed_at': now - 50000}], [],
|
||||||
|
button={'at': now - 1300})
|
||||||
|
assert not mon.tickets.create.called
|
||||||
|
|
||||||
|
def test_ticket_lists_restarts_and_suggests_replacement(self, mon, db):
|
||||||
|
now = time.time()
|
||||||
|
self._decide(mon, db,
|
||||||
|
[{'failed_at': now - 20000}, {'failed_at': now - 10000}, {'failed_at': now - 900}],
|
||||||
|
[{'at': now - 3 * 86400, 'by': None, 'confirmed': True},
|
||||||
|
{'at': now - 1200 - 2 * 86400, 'by': 'RPDU', 'confirmed': True}])
|
||||||
|
desc = mon.tickets.create.call_args.args[1]
|
||||||
|
assert 'Modem restarts in the last 7 days' in desc
|
||||||
|
assert 'restarted outside Gandalf' in desc and 'Smart Power power-cycled it' in desc
|
||||||
|
assert 'replacement BGW320' in desc
|
||||||
|
|
||||||
def test_suppression_blocks_one_shot_ticket(self, mon, db):
|
def test_suppression_blocks_one_shot_ticket(self, mon, db):
|
||||||
now = time.time()
|
now = time.time()
|
||||||
db.check_suppressed.return_value = True
|
db.check_suppressed.return_value = True
|
||||||
@@ -1050,6 +1206,56 @@ class TestWanQualityCollection:
|
|||||||
assert c.get_wan_dashboard() is None
|
assert c.get_wan_dashboard() is None
|
||||||
|
|
||||||
|
|
||||||
|
def _timeline(states, end=100000.0):
|
||||||
|
"""WAN quality periods ending at *end*, one per state, 5 minutes apart."""
|
||||||
|
return {'periods': [{'ts': end - (len(states) - 1 - i) * 300, 'state': s} for i, s in enumerate(states)]}
|
||||||
|
|
||||||
|
|
||||||
|
class TestWanDegraded:
|
||||||
|
"""2026-11-23/24: about 20 hours of latency and loss with no ticket (gandalf#58)."""
|
||||||
|
|
||||||
|
def test_two_bad_hours_open_a_ticket(self, mon, db):
|
||||||
|
mon._process_wan_degraded(_timeline(['latency'] * 14 + ['ok'] * 6 + ['loss'] * 4), [])
|
||||||
|
assert ('wan_degraded', 'att-modem', '') in upserted(db)
|
||||||
|
title, desc = mon.tickets.create.call_args.args[:2]
|
||||||
|
assert 'Internet degraded' in title
|
||||||
|
assert '18 of 24 five-minute periods had 14 latency, 4 loss' in desc
|
||||||
|
assert 'Restart modem' in desc
|
||||||
|
|
||||||
|
def test_odd_slow_periods_do_nothing(self, mon, db):
|
||||||
|
mon._process_wan_degraded(_timeline(['ok'] * 20 + ['latency'] * 4), [])
|
||||||
|
assert not db.upsert_event.called
|
||||||
|
assert not mon.tickets.create.called
|
||||||
|
|
||||||
|
def test_mostly_fine_hour_resolves(self, mon, db):
|
||||||
|
mon._process_wan_degraded(_timeline(['latency'] * 12 + ['ok'] * 20 + ['latency'] * 4), [])
|
||||||
|
db.resolve_event.assert_called_with('wan_degraded', 'att-modem', '')
|
||||||
|
|
||||||
|
def test_in_between_leaves_it_open(self, mon, db):
|
||||||
|
# 9 of the last 24 bad: under half, but over a quarter, so no change either way
|
||||||
|
mon._process_wan_degraded(_timeline(['ok'] * 15 + ['latency'] * 9), [])
|
||||||
|
assert not db.upsert_event.called and not db.resolve_event.called
|
||||||
|
|
||||||
|
def test_no_timeline_leaves_it_alone(self, mon, db):
|
||||||
|
mon._process_wan_degraded(None, [])
|
||||||
|
assert not db.upsert_event.called and not db.resolve_event.called
|
||||||
|
|
||||||
|
def test_a_restart_resets_the_judgement(self, mon, db):
|
||||||
|
# 2026-11-24: hours of loss, then a reboot 50 minutes ago, fine since
|
||||||
|
end = time.time()
|
||||||
|
history = json.dumps({'outages': [], 'restarts': [{'at': end - 3000, 'by': None}]})
|
||||||
|
db.get_state.side_effect = lambda k, d=None: history if k == 'wan_history' else None
|
||||||
|
mon._process_wan_degraded(_timeline(['loss'] * 16 + ['down'] * 2 + ['ok'] * 6, end), [])
|
||||||
|
assert not db.upsert_event.called
|
||||||
|
db.resolve_event.assert_called_with('wan_degraded', 'att-modem', '')
|
||||||
|
|
||||||
|
def test_slow_ping_from_the_modem_is_mentioned(self, mon, db):
|
||||||
|
checks = json.dumps({'ping': {'verdict': 'gateway', 'avg_ms': 1154}})
|
||||||
|
db.get_state.side_effect = lambda k, d=None: checks if k == 'modem_checks' else None
|
||||||
|
mon._process_wan_degraded(_timeline(['loss'] * 24), [])
|
||||||
|
assert 'ping from the modem itself was slow too (avg 1154 ms)' in mon.tickets.create.call_args.args[1]
|
||||||
|
|
||||||
|
|
||||||
class TestModemChecks:
|
class TestModemChecks:
|
||||||
NOW = 1_000_000.0
|
NOW = 1_000_000.0
|
||||||
|
|
||||||
@@ -1205,3 +1411,90 @@ class TestFinishModemRestart:
|
|||||||
def test_finished_restart_is_left_alone(self, mon, db):
|
def test_finished_restart_is_left_alone(self, mon, db):
|
||||||
out, km = self._run(mon, db, self._restart(300, finished_at=1.0), {'reachable': True})
|
out, km = self._run(mon, db, self._restart(300, finished_at=1.0), {'reachable': True})
|
||||||
assert out is None and not km.called
|
assert out is None and not km.called
|
||||||
|
|
||||||
|
OUTLET = {'device_id': 'pdu1', 'device': 'RPDU', 'index': 13, 'name': 'AT&T Modem'}
|
||||||
|
|
||||||
|
def test_back_turns_smart_power_on_again(self, mon, db):
|
||||||
|
mon.unifi = MagicMock()
|
||||||
|
out, _ = self._run(mon, db, self._restart(300, smart_power_paused=[self.OUTLET]),
|
||||||
|
{'reachable': True, 'wan_problems': [], 'uptime_s': 200})
|
||||||
|
mon.unifi.set_auto_power_cycle.assert_called_once_with('pdu1', 13, True)
|
||||||
|
assert out['smart_power_restored'] is True and out['smart_power_error'] is None
|
||||||
|
|
||||||
|
def test_smart_power_retried_after_the_restart_finished(self, mon, db):
|
||||||
|
mon.unifi = MagicMock()
|
||||||
|
mon.unifi.set_auto_power_cycle.side_effect = monitor.UnifiWriteError('HTTP 500')
|
||||||
|
out, _ = self._run(mon, db, self._restart(300, smart_power_paused=[self.OUTLET]),
|
||||||
|
{'reachable': True, 'wan_problems': [], 'uptime_s': 200})
|
||||||
|
assert out['finished_at'] and not out.get('smart_power_restored')
|
||||||
|
assert 'HTTP 500' in out['smart_power_error']
|
||||||
|
# Next cycle: finished, but auto power-cycle is still off, so it tries again
|
||||||
|
mon.unifi.set_auto_power_cycle.side_effect = None
|
||||||
|
out, _ = self._run(mon, db, out, {'reachable': True})
|
||||||
|
assert out['smart_power_restored'] is True
|
||||||
|
|
||||||
|
def test_restored_smart_power_is_left_alone(self, mon, db):
|
||||||
|
mon.unifi = MagicMock()
|
||||||
|
out, _ = self._run(mon, db, self._restart(300, finished_at=1.0, smart_power_paused=[self.OUTLET],
|
||||||
|
smart_power_restored=True), {'reachable': True})
|
||||||
|
assert out is None and not mon.unifi.set_auto_power_cycle.called
|
||||||
|
|
||||||
|
|
||||||
|
def _pdu(overrides, dev_id='pdu1'):
|
||||||
|
return {'_id': dev_id, 'name': 'RPDU', 'outlet_overrides': overrides}
|
||||||
|
|
||||||
|
|
||||||
|
class TestSmartPowerWrites:
|
||||||
|
MODEM = {'name': 'AT&T Modem', 'index': 13, 'relay_state': True, 'cycle_enabled': True}
|
||||||
|
OTHER = {'name': 'storage-01', 'index': 14, 'relay_state': True, 'cycle_enabled': False}
|
||||||
|
|
||||||
|
def _client(self, reads):
|
||||||
|
c = monitor.UnifiClient({'controller': 'https://udm.test', 'api_key': 'k'})
|
||||||
|
replies = iter(reads)
|
||||||
|
c.session.get = MagicMock(side_effect=lambda *a, **k: MagicMock(json=lambda: {'data': next(replies)}))
|
||||||
|
c.session.put = MagicMock(return_value=MagicMock())
|
||||||
|
return c
|
||||||
|
|
||||||
|
def test_lists_outlets_with_auto_power_cycle(self):
|
||||||
|
c = self._client([[_pdu([self.MODEM, self.OTHER])]])
|
||||||
|
assert c.auto_power_cycle_outlets() == [{'device_id': 'pdu1', 'device': 'RPDU', 'index': 13,
|
||||||
|
'name': 'AT&T Modem'}]
|
||||||
|
|
||||||
|
def test_changes_only_that_flag(self):
|
||||||
|
after = dict(self.MODEM, cycle_enabled=False)
|
||||||
|
c = self._client([[_pdu([self.MODEM, self.OTHER])], [_pdu([after, self.OTHER])]])
|
||||||
|
c.set_auto_power_cycle('pdu1', 13, False)
|
||||||
|
url = c.session.put.call_args.args[0]
|
||||||
|
assert url.endswith('/proxy/network/api/s/default/rest/device/pdu1')
|
||||||
|
sent = c.session.put.call_args.kwargs['json']['outlet_overrides']
|
||||||
|
assert sent == [after, self.OTHER] # relay states and the other outlet untouched
|
||||||
|
|
||||||
|
def test_already_set_sends_nothing(self):
|
||||||
|
c = self._client([[_pdu([self.MODEM])]])
|
||||||
|
c.set_auto_power_cycle('pdu1', 13, True)
|
||||||
|
assert not c.session.put.called
|
||||||
|
|
||||||
|
def test_change_not_confirmed_is_an_error(self):
|
||||||
|
c = self._client([[_pdu([self.MODEM])], [_pdu([self.MODEM])]])
|
||||||
|
with pytest.raises(monitor.UnifiWriteError, match='still reports'):
|
||||||
|
c.set_auto_power_cycle('pdu1', 13, False)
|
||||||
|
|
||||||
|
def test_unknown_outlet_is_an_error(self):
|
||||||
|
c = self._client([[_pdu([self.OTHER])]])
|
||||||
|
with pytest.raises(monitor.UnifiWriteError, match='no override entry'):
|
||||||
|
c.set_auto_power_cycle('pdu1', 13, False)
|
||||||
|
assert not c.session.put.called
|
||||||
|
|
||||||
|
def test_pause_and_restore(self):
|
||||||
|
unifi = MagicMock()
|
||||||
|
unifi.auto_power_cycle_outlets.return_value = [{'device_id': 'pdu1', 'index': 13, 'device': 'RPDU'}]
|
||||||
|
paused, err = monitor.pause_smart_power(unifi)
|
||||||
|
assert err is None and len(paused) == 1
|
||||||
|
unifi.set_auto_power_cycle.assert_called_with('pdu1', 13, False)
|
||||||
|
assert monitor.restore_smart_power(unifi, paused) is None
|
||||||
|
unifi.set_auto_power_cycle.assert_called_with('pdu1', 13, True)
|
||||||
|
|
||||||
|
def test_pause_failure_is_reported(self):
|
||||||
|
unifi = MagicMock()
|
||||||
|
unifi.auto_power_cycle_outlets.side_effect = monitor.UnifiWriteError('reading outlets: 401')
|
||||||
|
assert monitor.pause_smart_power(unifi) == ([], 'reading outlets: 401')
|
||||||
Reference in new issue
Block a user