Restart modem: pause Smart Power auto power-cycle until the modem is back
Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m5s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m13s
Lint / Python (flake8) (pull_request) Successful in 1m14s
Test / Python Tests (pytest) (push) Successful in 1m51s
Security / Python Security (bandit) (pull_request) Successful in 1m25s
Lint / JS (eslint) (pull_request) Successful in 19s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Test / Python Tests (pytest) (pull_request) Successful in 1m32s

UniFi Smart Power on the RPDU's modem outlet saw the internet down while
the modem rebooted and cut its power mid-boot: once during the 11-20
restart and twice after the 11-24 AT&T-app reboot. UniFi only exposes
auto power-cycle as on or off, so the button now turns it off for every
outlet that has it on, and the monitor turns it back on when the restart
ends (back, or after 30 minutes).

- UnifiClient.auto_power_cycle_outlets / set_auto_power_cycle: sends the
  device's outlet_overrides back with only cycle_enabled changed, then
  reads them again to confirm. The only UniFi setting Gandalf changes.
- A failed pause doesn't stop the restart; a failed restart turns it back
  on. A failed restore is retried every cycle and shown as broken in
  Needs attention until it works.
- The panel note and confirm text mention the pause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-24 00:13:46 -05:00
1 parent a7792063ba
commit a5d4fc3156
9 files changed
+304 -19

No files matched your search

+12 -3
View File
@@ -555,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
+23 -5
View File
@@ -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
View File
@@ -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 {})
+103 -1
View File
@@ -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:
@@ -2144,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)
@@ -2170,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
+10 -3
View File
@@ -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 {
+1
View File
@@ -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
View File
@@ -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'))
+16
View File
@@ -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'] == []
+87
View File
@@ -1411,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')