diff --git a/app.py b/app.py
index 27ff38a..3421f8a 100644
--- a/app.py
+++ b/app.py
@@ -22,6 +22,7 @@ from urllib.parse import quote, urlparse
from flask import Flask, jsonify, make_response, redirect, render_template, request, send_file, url_for
+import attention
import cutsheet
import db
import devices
@@ -1335,6 +1336,32 @@ def api_topology():
return jsonify(_topology_graph(events, sheet, feeds))
+@app.route('/api/attention')
+@require_auth
+def api_attention():
+ """Everything that needs looking at, from every page, for the dashboard (see attention.build)."""
+ return jsonify(_attention())
+
+
+def _attention() -> dict:
+ events = db.get_active_events(limit=_PAGE_LIMIT)
+ _annotate_suppressions(events, db.get_active_suppressions())
+ view, racks, feeds = None, {}, []
+ try:
+ view = _cutsheet_view()
+ feeds = db.get_power_feeds()
+ all_racks = _racks(view['items'])
+ for rack in all_racks:
+ here = [i for i in view['items'] if not i.get('shelf')
+ and (i.get('rack') or all_racks[0]['name']) == rack['name']]
+ racks[rack['name']] = cutsheet.rack_layout(here, rack['units'])
+ except Exception as e:
+ logger.error(f'Cutsheet unavailable for the attention list: {e}')
+ 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)
+
+
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
return topology.build_graph(
_state_json('network_snapshot'), _state_json('link_stats'), _state_json('modem_stats'),
diff --git a/attention.py b/attention.py
new file mode 100644
index 0000000..fc00f65
--- /dev/null
+++ b/attention.py
@@ -0,0 +1,122 @@
+"""What needs looking at, gathered from every page into one list for the dashboard.
+
+Two groups: 'broken' is something not working right now; 'tidy' is housekeeping, where
+the network works but the records or names don't match it. Each entry links to the page
+where it is fixed. Pure functions, so the rules are easy to test.
+"""
+from typing import Dict, List, Optional
+
+GROUPS = ('broken', 'tidy')
+
+
+def _plural(n: int, one: str, many: Optional[str] = None) -> str:
+ return f'{n} {one if n == 1 else (many or one + "s")}'
+
+
+def _entry(group: str, severity: str, text: str, href: str, detail: str = '') -> dict:
+ return {'group': group, 'severity': severity, 'text': text, 'href': href, 'detail': detail}
+
+
+def _alerts(events: List[dict]) -> List[dict]:
+ live = [e for e in events if not e.get('is_suppressed') and e.get('severity') != 'info']
+ if not live:
+ return []
+ critical = sum(1 for e in live if e.get('severity') == 'critical')
+ targets = sorted({str(e.get('target_name') or '') for e in live if e.get('target_name')}, key=str.lower)
+ text = _plural(len(live), 'active alert')
+ if critical:
+ text += f' ({critical} critical)'
+ shown = ', '.join(targets[:4]) + (f' and {len(targets) - 4} more' if len(targets) > 4 else '')
+ return [_entry('broken', 'bad' if critical else 'warn', text, '#events-table-wrap', shown)]
+
+
+def _power(power: List[dict]) -> List[dict]:
+ out = []
+ for src in power or []:
+ name = src.get('node') or ''
+ if src.get('stale_since'):
+ out.append(_entry('broken', 'warn', f'{name}: outlet watts are frozen', '/topology',
+ 'UniFi keeps sending the same per-outlet readings; the total is still live. '
+ 'Restarting the unit usually clears it.'))
+ for o in src.get('outlets') or []:
+ if not o.get('on') and o.get('target'):
+ out.append(_entry('broken', 'bad', f'{name} outlet {o.get("index")} is off, and it feeds {o["target"]}',
+ '/topology'))
+ idle = []
+ for src in power or []:
+ for o in src.get('outlets') or []:
+ # Drawing real power, but nothing in Gandalf says what is plugged in
+ if o.get('on') and not o.get('target') and o.get('match') != 'cleared' and (o.get('power_w') or 0) >= 5:
+ idle.append(f'{src.get("node")} {o.get("index")}')
+ if idle:
+ out.append(_entry('tidy', 'info', f'{_plural(len(idle), "powered outlet")} with no device assigned',
+ '/topology', ', '.join(idle[:6]) + (' ...' if len(idle) > 6 else '')))
+ return out
+
+
+def _cutsheet(view: dict) -> List[dict]:
+ out = []
+ cables = [c for c in view.get('cables') or [] if c.get('status') != 'retired']
+ bad = [c for c in cables if c.get('problem')]
+ if bad:
+ names = ', '.join(c.get('label') or f'#{c["id"]}' for c in bad[:5])
+ out.append(_entry('broken', 'bad', f'{_plural(len(bad), "cable")} not where the cutsheet says',
+ '/cutsheet?problems=1#cs-cables-section', names))
+
+ names = view.get('port_names') or []
+ wrong = [r for r in names if r.get('kind') in ('wrong', 'moved')]
+ if wrong:
+ out.append(_entry('tidy', 'warn', f'{_plural(len(wrong), "UniFi port name")} pointing at the wrong device',
+ '/cutsheet#cs-portnames-section',
+ ', '.join(f'{r["switch"]} port {r["port_idx"]} "{r["port_name"]}"' for r in wrong[:3])))
+ empty = [r for r in names if r.get('kind') == 'empty']
+ if empty:
+ out.append(_entry('tidy', 'info', f'{_plural(len(empty), "named port")} with nothing plugged in',
+ '/cutsheet#cs-portnames-section',
+ ', '.join(f'"{r["port_name"]}"' for r in empty[:4])))
+
+ missing = view.get('suggestions') or []
+ if missing:
+ out.append(_entry('tidy', 'info', f'{_plural(len(missing), "live link")} not on the cutsheet',
+ '/cutsheet#cs-suggest-section'))
+
+ labels = view.get('labels') or {}
+ todo = len(labels.get('cables') or []) + len(labels.get('ports') or [])
+ if todo:
+ out.append(_entry('tidy', 'info', f'{_plural(todo, "label")} to print and stick on',
+ '/cutsheet#cs-labels-section'))
+ return out
+
+
+def _rack(issues: Dict[str, dict]) -> List[dict]:
+ out = []
+ for rack, r in (issues or {}).items():
+ for o in r.get('overlaps') or []:
+ out.append(_entry('tidy', 'warn', f'{o["name"]} overlaps {", ".join(o["with"])} at {o["units"]}',
+ '/cutsheet#cs-items-section', rack))
+ for o in r.get('outside') or []:
+ out.append(_entry('tidy', 'warn', f'{o["name"]} at {o["units"]} is outside {rack}',
+ '/cutsheet#cs-items-section'))
+ return out
+
+
+def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict],
+ rack_issues: Optional[Dict[str, 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()}.
+ Entry: {group, severity: bad|warn|info, text, href, detail}.
+ """
+ entries = _alerts(events) + _power(power)
+ if cutsheet_view is not None:
+ entries += _cutsheet(cutsheet_view)
+ entries += _rack(rack_issues or {})
+ rank = {'bad': 0, 'warn': 1, 'info': 2}
+ out = {g: [] for g in GROUPS}
+ for e in entries:
+ out[e['group']].append(e)
+ for g in GROUPS:
+ out[g].sort(key=lambda e: rank[e['severity']])
+ return out
diff --git a/static/app.js b/static/app.js
index 4c50b1b..34c606e 100644
--- a/static/app.js
+++ b/static/app.js
@@ -43,6 +43,7 @@ async function refreshAll() {
lt.api.get('/api/network'),
lt.api.get('/api/status'),
refreshModem(),
+ refreshAttention(),
]);
if (netResult.status === 'fulfilled') {
const net = netResult.value;
@@ -68,6 +69,40 @@ async function refreshAll() {
}
}
+// ── Needs attention ───────────────────────────────────────────────────
+const ATTENTION_GROUPS = [
+ { key: 'broken', title: 'Broken now', clear: 'Nothing broken' },
+ { key: 'tidy', title: 'Tidy up', clear: 'Records match the network' },
+];
+
+async function refreshAttention() {
+ const body = document.getElementById('attention-body');
+ if (!body) return;
+ try {
+ renderAttention(body, await lt.api.get('/api/attention'));
+ } catch (e) {
+ body.innerHTML = `
Couldn't gather the list: ${lt.escHtml(e.message || e)}
@@ -229,7 +230,7 @@
|
- GANDALF | TDS v1.2
+ GANDALF: Global Advanced Network Detection And Link Facilitator | TDS v1.2
{% if user.groups and 'admin' in user.groups and not maintenance %}
@@ -331,6 +332,7 @@
+
GANDALF: Global Advanced Network Detection And Link Facilitator. It watches the UniFi switches and the hosts' links, works out what is plugged in where, and raises a ticket when something breaks.