diff --git a/README.md b/README.md index b1091ed..fc71d49 100644 --- a/README.md +++ b/README.md @@ -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 without it), 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 -(at least 3 minutes later), switches the Kuma window off, ends the suppression, and records how long it -took (`monitor_state.modem_restart`). After 30 minutes it ends both regardless. One restart at a time. +(at least 3 minutes later), switches the Kuma window off, ends the suppression, turns auto power-cycle +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 session is kept between checks and renewed when it expires. A refused code is reported in Needs diff --git a/app.py b/app.py index 214340e..e398292 100644 --- a/app.py +++ b/app.py @@ -30,7 +30,7 @@ import diagnose import kuma import modem as modem_api import topology -from monitor import PulseClient, UnifiClient +from monitor import PulseClient, UnifiClient, pause_smart_power, restore_smart_power logging.basicConfig( level=logging.INFO, @@ -605,10 +605,24 @@ def api_modem_restart(): sup_id = db.create_suppression('all', '', '', 'Modem restart from Gandalf', user, 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: result = modem_api.ModemAdmin(modem_cfg).restart() except (modem_api.ModemUnreachable, modem_api.ModemDataInvalid, modem_api.ModemLoginFailed) as 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) if kuma_on: try: @@ -618,10 +632,13 @@ def api_modem_restart(): return jsonify({'error': f'The modem did not restart: {e}'}), 502 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 ' - f'{"on" if kuma_on else "not set"}, suppression #{sup_id}') - return jsonify({'ok': True, 'result': result, 'kuma': kuma_on, 'suppression_id': sup_id}) + f'{"on" if kuma_on else "not set"}, suppression #{sup_id}, Smart Power paused on ' + 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') @@ -1425,7 +1442,8 @@ def _attention() -> dict: sheet = {'items': (view or {}).get('items') or [], 'cables': (view or {}).get('cables') or []} power = _topology_graph(events, sheet, feeds).get('power') or [] 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: diff --git a/attention.py b/attention.py index 28c7d86..da2feb7 100644 --- a/attention.py +++ b/attention.py @@ -188,21 +188,36 @@ def _wan(quality: Optional[dict], now: float, checks: Optional[dict] = None) -> 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], 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. events: active alerts, annotated with 'is_suppressed'. power: topology.build_power output. 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()}. 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}. """ now = time.time() if now is None else now 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: entries += _cutsheet(cutsheet_view) entries += _rack(rack_issues or {}) diff --git a/monitor.py b/monitor.py index bfac551..41931c1 100644 --- a/monitor.py +++ b/monitor.py @@ -103,6 +103,36 @@ class PrometheusClient: # -------------------------------------------------------------------------- # 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: # Devices whose port tables are collected: switches and the gateway/router _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]: """Return wired clients as {mac, sw_mac, sw_port}; empty if unavailable.""" try: @@ -2144,7 +2227,13 @@ class NetworkMonitor: state = json.loads(raw) if raw else None except ValueError: 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 now = time.time() age = now - state.get('at', now) @@ -2170,12 +2259,25 @@ class NetworkMonitor: state['kuma_error'] = str(e) if state.get('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, back_after_s=round(age) if back else None) db.set_state('modem_restart', state) logger.info(f'Modem restart finished: {"back" if back else "gave up waiting"} after {round(age)} s' 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 _FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes _FIREWALL_HOURS = 24 diff --git a/static/app.js b/static/app.js index 938ff6b..cc6c8ec 100644 --- a/static/app.js +++ b/static/app.js @@ -474,9 +474,16 @@ function _modemQuality(q) { function _modemRestartNote(r) { if (!r || !r.at) return ''; const who = r.by ? ` by ${r.by}` : ''; + const paused = (r.smart_power_paused || []).length; if (!r.finished_at) { + const sp = paused ? ' Smart Power auto power-cycle is paused so it can\'t cut power mid-boot.' : ''; return `