From b8d45648eaf6023b283e4ffad8e2b2bd266ea25b Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Thu, 26 Nov 2026 22:50:20 -0500 Subject: [PATCH] Smart Power: never leave auto power-cycle off; restarts in maintenance aren't "needed" 2026-11-26: the Restart modem button asked UniFi to pause auto power-cycle on the modem's outlet. Read back at once, UniFi still showed the old setting, so Gandalf recorded nothing paused; UniFi then applied the change, and nothing turned it back on. Now Gandalf waits up to 10 s for UniFi to show the change, and lists every outlet it tried to pause, so the restore always runs (turning on an outlet that is on is a no-op). A modem restart inside a Gandalf silence for everything (the planned 2026-11-25 UPS update cut the rack's power) is shown as planned maintenance and no longer counts toward "the modem has needed N restarts". Co-Authored-By: Claude Opus 5.5 --- modem.py | 31 ++++++++++++++++++-------- monitor.py | 52 ++++++++++++++++++++++++++++++++++++++----- tests/test_modem.py | 30 +++++++++++++++++++++++++ tests/test_monitor.py | 52 +++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 148 insertions(+), 17 deletions(-) diff --git a/modem.py b/modem.py index cdd16ae..032a7f4 100644 --- a/modem.py +++ b/modem.py @@ -422,13 +422,16 @@ _EPISODE_GAP_S = 900 RESTART_SETTLE_S = 900 -def restart_episodes(history: dict, button: Optional[dict], since: float) -> List[dict]: - """Modem restarts since *since*, oldest first: [{'at', 'by'}]. +def restart_episodes(history: dict, button: Optional[dict], since: float, + maintenance: Optional[List[dict]] = None) -> List[dict]: + """Modem restarts since *since*, oldest first: [{'at', 'by'}, plus 'note' for maintenance]. 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". + cause seen: the Gandalf button, then Smart Power, then "outside Gandalf". A restart not + from the button that falls in a *maintenance* window ([{'start', 'end', 'reason'}], + Gandalf silenced for everything) is 'maintenance': planned work, not one the modem needed. """ 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))] @@ -446,7 +449,14 @@ def restart_episodes(history: dict, button: Optional[dict], since: float) -> Lis ep['by'] = by else: episodes.append({'at': at, 'last': at, 'by': by}) - return [{'at': e['at'], 'by': e['by']} for e in episodes] + out = [] + for e in episodes: + ep = {'at': e['at'], 'by': e['by']} + window = next((w for w in maintenance or [] if w['start'] <= e['at'] <= w['end']), None) + if window and e['by'] != 'gandalf': + ep.update(by='maintenance', note=window.get('reason') or '') + out.append(ep) + return out def unexplained_drops(outages: List[dict], episodes: List[dict], since: float) -> List[dict]: @@ -459,7 +469,8 @@ def unexplained_drops(outages: List[dict], episodes: List[dict], since: float) - _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)'} + 'outside': 'restarted outside Gandalf (AT&T app, modem button or power)', + 'maintenance': 'during planned maintenance (Gandalf silenced)'} def _span(seconds: float) -> str: @@ -476,14 +487,16 @@ def restart_lines(episodes: List[dict], now: float) -> List[str]: 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}') + by = _RESTART_BY[e['by']] + (f': "{e["note"]}"' if e.get('note') else '') + lines.append(f'- {when}: {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 ' + """Advice when restarts keep being needed: two or more in a week, not counting planned work.""" + needed = [e for e in episodes if e.get('by') != 'maintenance'] + if len(needed) >= 2: + return (f'The modem has needed {len(needed)} 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 '' diff --git a/monitor.py b/monitor.py index f51ca06..e0aeb5f 100644 --- a/monitor.py +++ b/monitor.py @@ -116,8 +116,10 @@ def pause_smart_power(unifi) -> tuple: paused: List[dict] = [] try: for outlet in unifi.auto_power_cycle_outlets(): - unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], False) + # Listed before the write: a change UniFi applies after Gandalf stopped waiting for + # it (2026-11-26) still gets undone. Turning on an outlet that is already on is a no-op. paused.append(outlet) + unifi.set_auto_power_cycle(outlet['device_id'], outlet['index'], False) return paused, None except UnifiWriteError as e: return paused, str(e) @@ -138,6 +140,9 @@ class UnifiClient: # Devices whose port tables are collected: switches and the gateway/router _PORT_DEVICE_TYPES = ('usw', 'udm', 'ugw', 'uxg') _SYSTEM_LOG_MAX_PAGES = 10 + # How long to wait for UniFi to show an outlet setting it accepted + CONFIRM_TRIES = 6 + CONFIRM_WAIT_S = 2 def __init__(self, cfg: dict): self.base_url = cfg['controller'] @@ -255,10 +260,17 @@ class UnifiClient: 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') + # UniFi can take a few seconds to show a change it accepted (2026-11-26: read back at + # once, it still showed the old setting, then applied it), so wait for it + for attempt in range(self.CONFIRM_TRIES): + if attempt: + time.sleep(self.CONFIRM_WAIT_S) + 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 enabled: + return + raise UnifiWriteError(f'UniFi accepted the change but still reports the old setting after ' + f'{(self.CONFIRM_TRIES - 1) * self.CONFIRM_WAIT_S} s') except UnifiWriteError: raise except Exception as e: @@ -2221,9 +2233,37 @@ class NetworkMonitor: 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) + since = now - 7 * 86400 + episodes = modem_api.restart_episodes(self._load_wan_history(), button, since, + self._maintenance_windows(since, now)) return episodes, modem_api.restart_lines(episodes, now), modem_api.replacement_hint(episodes) + @staticmethod + def _maintenance_windows(since: float, now: float) -> List[dict]: + """Times Gandalf was silenced for everything: [{'start', 'end', 'reason'}] (unix). + + A modem restart inside one is planned work (2026-11-25: the rack's UPS update cut its + power), not a restart the modem needed. Gandalf's own modem-restart silence is left + out: that restart is already shown as the button's. + """ + try: + rows = db.get_suppression_windows(datetime.fromtimestamp(since, timezone.utc).replace(tzinfo=None)) + except Exception as e: + logger.warning(f'Suppression history unavailable for the restart list: {e}') + return [] + + def ts(iso): + return datetime.fromisoformat(iso.rstrip('Z')).replace(tzinfo=timezone.utc).timestamp() if iso else None + out = [] + for r in rows: + if r.get('target_type') != 'all' or (r.get('reason') or '').startswith('Modem restart'): + continue + start, end = ts(r.get('started_at')), ts(r.get('ended_at')) + if start is None or (end is None and r.get('state') != 'active'): + continue # removed before end times were recorded: its length is unknown + out.append({'start': start, 'end': end or now, 'reason': r.get('reason') or ''}) + return out + 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 diff --git a/tests/test_modem.py b/tests/test_modem.py index 7e13bd5..b665ecb 100644 --- a/tests/test_modem.py +++ b/tests/test_modem.py @@ -611,3 +611,33 @@ class TestDegradation: 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) + + +class TestRestartsDuringMaintenance: + """2026-11-25: the rack's planned UPS update cut the modem's power inside a Gandalf silence; + the next day's ticket counted it as one of "3 restarts the modem needed".""" + + H = 3600 + + def _eps(self, maintenance): + history = {'restarts': [{'at': 10 * self.H, 'by': 'RPDU'}, {'at': 40 * self.H, 'by': None}]} + return modem.restart_episodes(history, {'at': 70 * self.H}, 0, maintenance) + + def test_restart_inside_a_silence_is_maintenance(self): + eps = self._eps([{'start': 39.5 * self.H, 'end': 40.5 * self.H, 'reason': 'switch update'}]) + assert [e['by'] for e in eps] == ['smart power', 'maintenance', 'gandalf'] + assert eps[1]['note'] == 'switch update' + lines = modem.restart_lines(eps, 80 * self.H) + assert 'during planned maintenance (Gandalf silenced): "switch update"' in lines[1] + + def test_maintenance_is_not_a_needed_restart(self): + eps = self._eps([{'start': 39.5 * self.H, 'end': 40.5 * self.H, 'reason': 'switch update'}]) + assert 'needed 2 restarts' in modem.replacement_hint(eps) + assert modem.replacement_hint([e for e in eps if e['by'] != 'smart power'][:2]) == '' + + def test_the_restart_button_stays_the_buttons(self): + eps = self._eps([{'start': 69.9 * self.H, 'end': 70.5 * self.H, 'reason': 'mistake'}]) + assert eps[-1]['by'] == 'gandalf' + + def test_no_windows_changes_nothing(self): + assert [e['by'] for e in self._eps(None)] == ['smart power', 'outside', 'gandalf'] diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 0ce8db8..a5252d8 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -1548,6 +1548,10 @@ def _pdu(overrides, dev_id='pdu1'): return {'_id': dev_id, 'name': 'RPDU', 'outlet_overrides': overrides} +def c_tries(): + return monitor.UnifiClient.CONFIRM_TRIES + + 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} @@ -1579,9 +1583,29 @@ class TestSmartPowerWrites: 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 = self._client([[_pdu([self.MODEM])]] * (1 + c_tries())) + with patch.object(monitor.time, 'sleep') as sleep: + with pytest.raises(monitor.UnifiWriteError, match='still reports the old setting after 10 s'): + c.set_auto_power_cycle('pdu1', 13, False) + assert sleep.call_count == monitor.UnifiClient.CONFIRM_TRIES - 1 + + def test_waits_for_a_change_unifi_shows_late(self): + # 2026-11-26: read back at once UniFi still showed the old setting, then applied it + after = dict(self.MODEM, cycle_enabled=False) + c = self._client([[_pdu([self.MODEM])], [_pdu([self.MODEM])], [_pdu([self.MODEM])], [_pdu([after])]]) + with patch.object(monitor.time, 'sleep') as sleep: c.set_auto_power_cycle('pdu1', 13, False) + assert sleep.call_count == 2 + + def test_unconfirmed_pause_is_still_undone(self): + # The pause raised, but UniFi may apply it later: the outlet must still be turned back on + unifi = MagicMock() + unifi.auto_power_cycle_outlets.return_value = [{'device_id': 'pdu1', 'index': 13, 'device': 'RPDU'}] + unifi.set_auto_power_cycle.side_effect = [monitor.UnifiWriteError('still reports the old setting'), None] + paused, err = monitor.pause_smart_power(unifi) + assert 'still reports' in err and [o['index'] for o in paused] == [13] + assert monitor.restore_smart_power(unifi, paused) is None + unifi.set_auto_power_cycle.assert_called_with('pdu1', 13, True) def test_unknown_outlet_is_an_error(self): c = self._client([[_pdu([self.OTHER])]]) @@ -1602,3 +1626,27 @@ class TestSmartPowerWrites: unifi = MagicMock() unifi.auto_power_cycle_outlets.side_effect = monitor.UnifiWriteError('reading outlets: 401') assert monitor.pause_smart_power(unifi) == ([], 'reading outlets: 401') + + +class TestMaintenanceWindows: + def test_silences_for_everything_become_windows(self, db): + db.get_suppression_windows.return_value = [ + {'target_type': 'all', 'reason': 'switch update', 'state': 'expired', + 'started_at': '2026-11-25T03:11:39Z', 'ended_at': '2026-11-25T03:41:39Z'}, + {'target_type': 'all', 'reason': 'Modem restart from Gandalf', 'state': 'expired', + 'started_at': '2026-11-26T16:57:30Z', 'ended_at': '2026-11-26T17:17:30Z'}, + {'target_type': 'host', 'reason': 'pbs disk swap', 'state': 'active', + 'started_at': '2026-11-26T10:00:00Z', 'ended_at': None}, + {'target_type': 'all', 'reason': 'old, removed by hand', 'state': 'ended', + 'started_at': '2026-11-22T10:00:00Z', 'ended_at': None}, + {'target_type': 'all', 'reason': 'now', 'state': 'active', + 'started_at': '2026-11-26T18:00:00Z', 'ended_at': None}, + ] + now = 1795752000.0 + out = monitor.NetworkMonitor._maintenance_windows(now - 7 * 86400, now) + assert [w['reason'] for w in out] == ['switch update', 'now'] + assert out[0]['end'] - out[0]['start'] == 1800 and out[1]['end'] == now + + def test_history_unavailable_means_no_windows(self, db): + db.get_suppression_windows.side_effect = RuntimeError('db down') + assert monitor.NetworkMonitor._maintenance_windows(0, 1) == [] -- 2.47.3