Compare commits
9
Commits
attention-list
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f4cb05f67 | ||
|
|
fa108b2a1e | ||
|
|
ff425dbaee | ||
|
|
99dee62098 | ||
|
|
4ad331ddfe | ||
|
|
7da4cc26e2 | ||
|
|
73787daaec | ||
|
|
6a717af3f2 | ||
|
|
f1355c4bd8 |
No files matched your search
@@ -83,7 +83,7 @@ Two processes share a MariaDB database:
|
|||||||
| Source | What it provides |
|
| Source | What it provides |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Prometheus** (`10.10.10.48:9090`) | Physical NIC link state + traffic/error rates via `node_exporter` |
|
| **Prometheus** (`10.10.10.48:9090`) | Physical NIC link state + traffic/error rates via `node_exporter` |
|
||||||
| **UniFi API** (`https://10.10.10.1`) | Switch port stats, device status, LLDP neighbor table, PoE data |
|
| **UniFi API** (`https://10.10.10.1`) | Switch port stats, device status, LLDP neighbor table, PoE data, the WAN health timeline (latency, loss, drops) |
|
||||||
| **Pulse Worker** | SSH relay: runs `ethtool` + SFP DOM queries on each Proxmox host |
|
| **Pulse Worker** | SSH relay: runs `ethtool` + SFP DOM queries on each Proxmox host |
|
||||||
| **Ping** | Reachability for hosts without `node_exporter` (e.g. PBS) |
|
| **Ping** | Reachability for hosts without `node_exporter` (e.g. PBS) |
|
||||||
| **AT&T BGW320** (`http://192.168.1.254`) | Fiber light levels, PON and WAN state, WAN counters, scraped read-only from the gateway's status pages (no login) |
|
| **AT&T BGW320** (`http://192.168.1.254`) | Fiber light levels, PON and WAN state, WAN counters, scraped read-only from the gateway's status pages (no login) |
|
||||||
@@ -92,7 +92,7 @@ Two processes share a MariaDB database:
|
|||||||
|
|
||||||
| Host | Prometheus Instance |
|
| Host | Prometheus Instance |
|
||||||
|---|---|
|
|---|---|
|
||||||
| large1 | 10.10.10.2:9100 |
|
| compute-storage-02 | 10.10.10.2:9100 |
|
||||||
| compute-storage-01 | 10.10.10.4:9100 |
|
| compute-storage-01 | 10.10.10.4:9100 |
|
||||||
| monitor-01 | 10.10.10.8:9100 |
|
| monitor-01 | 10.10.10.8:9100 |
|
||||||
| monitor-02 | 10.10.10.9:9100 |
|
| monitor-02 | 10.10.10.9:9100 |
|
||||||
@@ -108,8 +108,9 @@ Ping-only (no node_exporter): **pbs** (10.10.10.3)
|
|||||||
### Dashboard (`/`)
|
### Dashboard (`/`)
|
||||||
- **Needs attention** at the top gathers what every page would flag into two lists, each line linking to
|
- **Needs attention** at the top gathers what every page would flag into two lists, each line linking to
|
||||||
where it is fixed:
|
where it is fixed:
|
||||||
- *Broken now*: active alerts (one line, with the devices), an outlet that is off but feeds a device,
|
- *Broken now*: internet trouble in the last hour (see below), active alerts (one line, with the
|
||||||
frozen outlet readings, and cables not where the cutsheet says.
|
devices), an outlet that is off but feeds a device, frozen outlet readings, and cables not where the
|
||||||
|
cutsheet says.
|
||||||
- *Tidy up*: UniFi port names pointing at the wrong device or at an empty port, live links not on the
|
- *Tidy up*: UniFi port names pointing at the wrong device or at an empty port, live links not on the
|
||||||
cutsheet, labels to print, powered outlets with no device assigned, and rack items that overlap or sit
|
cutsheet, labels to print, powered outlets with no device assigned, and rack items that overlap or sit
|
||||||
outside the rack.
|
outside the rack.
|
||||||
@@ -117,7 +118,7 @@ Ping-only (no node_exporter): **pbs** (10.10.10.3)
|
|||||||
Served by `GET /api/attention` (`attention.py`) and refreshed with the rest of the page.
|
Served by `GET /api/attention` (`attention.py`) and refreshed with the rest of the page.
|
||||||
- Device search (see Device pages below)
|
- Device search (see Device pages below)
|
||||||
- Active alerts table with severity, target, consecutive failures, ticket link
|
- Active alerts table with severity, target, consecutive failures, ticket link
|
||||||
- WAN / Fiber panel: WAN and PON state, Rx/Tx power, optics temperature, throughput, errors, gateway uptime and last restart, 7-day Rx trend, recent WAN outages
|
- WAN / Fiber panel: WAN and PON state, Rx/Tx power, optics temperature, throughput, errors, gateway uptime and last restart (just the last restart when the gateway doesn't report uptime), a 24 hour internet health strip from UniFi, 7-day Rx trend, recent WAN outages
|
||||||
- Hosts with per-NIC link state; NICs marked unused fold into a "+N unused" line
|
- Hosts with per-NIC link state; NICs marked unused fold into a "+N unused" line
|
||||||
- UniFi devices as a compact list (name and model; offline ones turn red with a suppress button)
|
- UniFi devices as a compact list (name and model; offline ones turn red with a suppress button)
|
||||||
- Recently resolved alerts, folded until opened
|
- Recently resolved alerts, folded until opened
|
||||||
@@ -135,7 +136,7 @@ holds every page and Start maintenance.
|
|||||||
Every alert Gandalf raised in the last 24 hours to 90 days, including ones that cleared before anyone
|
Every alert Gandalf raised in the last 24 hours to 90 days, including ones that cleared before anyone
|
||||||
saw them: when each started, how long it lasted, failed checks, and its ticket.
|
saw them: when each started, how long it lasted, failed checks, and its ticket.
|
||||||
- Filter by device (name, port or interface), alert type, severity, and open or cleared. Filters are
|
- Filter by device (name, port or interface), alert type, severity, and open or cleared. Filters are
|
||||||
kept in the URL, so `/events?target=large1&range=90d` is a shareable link; device pages and tickets
|
kept in the URL, so `/events?target=compute-storage-02&range=90d` is a shareable link; device pages and tickets
|
||||||
link to their own history this way.
|
link to their own history this way.
|
||||||
- **Recurring** lists the same alert on the same target more than once in the range, worst first, since
|
- **Recurring** lists the same alert on the same target more than once in the range, worst first, since
|
||||||
a flapping cable or optic shows up here before anyone notices the tickets.
|
a flapping cable or optic shows up here before anyone notices the tickets.
|
||||||
@@ -226,7 +227,7 @@ servers along the bottom. Power gear (PDU, UPS, power strip) sits in a rail on t
|
|||||||
named "Patch panel port 1" (the device beyond the panel is unknown); a stub that already has a name
|
named "Patch panel port 1" (the device beyond the panel is unknown); a stub that already has a name
|
||||||
keeps it and adds "via Patch panel port 2". The cable details show where the cutsheet cable goes.
|
keeps it and adds "via Patch panel port 2". The cable details show where the cutsheet cable goes.
|
||||||
- **Port names**: a ⚠ marks a port named after one device with a different one plugged in (a port
|
- **Port names**: a ⚠ marks a port named after one device with a different one plugged in (a port
|
||||||
called "Large1 Management" with the AP on it). Generic names ("Port 4", "SFP+ 2", "Uplink") and
|
called "compute-storage-02 Management" with the AP on it). Generic names ("Port 4", "SFP+ 2", "Uplink") and
|
||||||
"Downlink to X" with X on the other end never flag.
|
"Downlink to X" with X on the other end never flag.
|
||||||
- **Alerts**: a device with active alerts (not suppressed) gets a ring and a count in its worst
|
- **Alerts**: a device with active alerts (not suppressed) gets a ring and a count in its worst
|
||||||
severity colour, and the NIC it is about is marked.
|
severity colour, and the NIC it is about is marked.
|
||||||
@@ -501,6 +502,15 @@ Outages can be over between polls: two real ones lasted about two minutes agains
|
|||||||
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.
|
||||||
|
|
||||||
|
Internet quality (slow or lossy rather than down) comes from UniFi too, not from Gandalf's own pings: the
|
||||||
|
UDM rates every 5 minutes as fine, high latency, packet loss or down, which is the timeline its Network app
|
||||||
|
charts. Each cycle the monitor reads the last day of it from the dashboard API (read only) into
|
||||||
|
`monitor_state.wan_quality`. The panel draws it as a 24 hour strip with the current latency to Cloudflare,
|
||||||
|
Google and Microsoft. Needs attention says *Internet: packet loss* (red) when 2 or more of the last 12
|
||||||
|
periods had loss or downtime, *high latency* (amber) when 3 or more had any problem, and lists drops from
|
||||||
|
the last hour. These are dashboard lines, not tickets, and they go once the hour is clean. A copy older
|
||||||
|
than 30 minutes is ignored.
|
||||||
|
|
||||||
**One ticket per incident.** The modem and WAN reports from one check cycle open a single ticket, led by
|
**One ticket per incident.** The modem and WAN reports from one check cycle open a single ticket, led by
|
||||||
the most urgent (a P2 "WAN modem unreachable" leads, and an RPDU power-cycle seen in the same cycle is listed
|
the most urgent (a P2 "WAN modem unreachable" leads, and an RPDU power-cycle seen in the same cycle is listed
|
||||||
under "Also seen in this incident"). A report that comes while the modem has an open alert, or one that
|
under "Also seen in this incident"). A report that comes while the modem has an open alert, or one that
|
||||||
@@ -578,7 +588,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
|||||||
"trusted_proxies": ["10.10.10.27"]
|
"trusted_proxies": ["10.10.10.27"]
|
||||||
},
|
},
|
||||||
"hosts": [
|
"hosts": [
|
||||||
{ "name": "large1", "prometheus_instance": "10.10.10.2:9100" },
|
{ "name": "compute-storage-02", "prometheus_instance": "10.10.10.2:9100" },
|
||||||
{ "name": "compute-storage-01", "prometheus_instance": "10.10.10.4:9100" },
|
{ "name": "compute-storage-01", "prometheus_instance": "10.10.10.4:9100" },
|
||||||
{ "name": "monitor-01", "prometheus_instance": "10.10.10.8:9100" },
|
{ "name": "monitor-01", "prometheus_instance": "10.10.10.8:9100" },
|
||||||
{ "name": "monitor-02", "prometheus_instance": "10.10.10.9:9100" },
|
{ "name": "monitor-02", "prometheus_instance": "10.10.10.9:9100" },
|
||||||
@@ -910,7 +920,7 @@ Take LED colors from the model's quick start guide. See the comment at the top o
|
|||||||
`recovery_notified` once the recovery note is on its ticket (column added automatically at monitor startup)
|
`recovery_notified` once the recovery note is on its ticket (column added automatically at monitor startup)
|
||||||
- `suppression_rules`: `active=FALSE` when removed; `expires_at` checked at query time
|
- `suppression_rules`: `active=FALSE` when removed; `expires_at` checked at query time
|
||||||
- `monitor_state`: key/value store; `interface_baseline`, `link_stats`, and `modem_stats` are JSON blobs
|
- `monitor_state`: key/value store; `interface_baseline`, `link_stats`, and `modem_stats` are JSON blobs
|
||||||
- `monitor_state` also holds `wan_history` (WAN outages, modem restarts) and `unifi_log_cursor` (how far the UniFi log has been read)
|
- `monitor_state` also holds `wan_history` (WAN outages, modem restarts), `wan_quality` (UniFi's 5 minute WAN health timeline) and `unifi_log_cursor` (how far the UniFi log has been read)
|
||||||
- Database sessions run in UTC (`db.py`), whatever the server's time zone
|
- Database sessions run in UTC (`db.py`), whatever the server's time zone
|
||||||
- `modem_samples`: optical readings per poll, kept 90 days; created automatically at monitor startup
|
- `modem_samples`: optical readings per poll, kept 90 days; created automatically at monitor startup
|
||||||
- `cutsheet_items`, `cutsheet_cables`, `cutsheet_port_labels`, `cutsheet_history`: cutsheet records and
|
- `cutsheet_items`, `cutsheet_cables`, `cutsheet_port_labels`, `cutsheet_history`: cutsheet records and
|
||||||
|
|||||||
@@ -555,6 +555,7 @@ def api_modem():
|
|||||||
logger.error(f'Failed to load modem history: {e}')
|
logger.error(f'Failed to load modem history: {e}')
|
||||||
data['history'] = []
|
data['history'] = []
|
||||||
data['wan_history'] = _state_json('wan_history')
|
data['wan_history'] = _state_json('wan_history')
|
||||||
|
data['wan_quality'] = _state_json('wan_quality') or None
|
||||||
data['configured'] = True
|
data['configured'] = True
|
||||||
return jsonify(data)
|
return jsonify(data)
|
||||||
|
|
||||||
@@ -1359,7 +1360,7 @@ def _attention() -> dict:
|
|||||||
logger.error(f'Cutsheet unavailable for the attention list: {e}')
|
logger.error(f'Cutsheet unavailable for the attention list: {e}')
|
||||||
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)
|
return attention.build(events, power, view, racks, _state_json('wan_quality'))
|
||||||
|
|
||||||
|
|
||||||
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
|
def _topology_graph(events: list, sheet: dict, feeds: list) -> dict:
|
||||||
|
|||||||
+56
-2
@@ -4,8 +4,11 @@ Two groups: 'broken' is something not working right now; 'tidy' is housekeeping,
|
|||||||
the network works but the records or names don't match it. Each entry links to the page
|
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.
|
where it is fixed. Pure functions, so the rules are easy to test.
|
||||||
"""
|
"""
|
||||||
|
import time
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
import modem
|
||||||
|
|
||||||
GROUPS = ('broken', 'tidy')
|
GROUPS = ('broken', 'tidy')
|
||||||
|
|
||||||
|
|
||||||
@@ -100,16 +103,67 @@ def _rack(issues: Dict[str, dict]) -> List[dict]:
|
|||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
# UniFi's WAN timeline: judge the last hour, and ignore a copy the monitor stopped refreshing
|
||||||
|
_WAN_WINDOW_S = 3600
|
||||||
|
_WAN_STALE_S = 1800
|
||||||
|
_WAN_BAD_PERIODS = 3 # periods with any problem before the list mentions it
|
||||||
|
_WAN_LOSS_PERIODS = 2 # periods with packet loss before it counts as broken
|
||||||
|
|
||||||
|
|
||||||
|
def _ago(seconds: float) -> str:
|
||||||
|
minutes = max(1, round(seconds / 60))
|
||||||
|
return f'{minutes} min ago' if minutes < 60 else f'{round(minutes / 60)} h ago'
|
||||||
|
|
||||||
|
|
||||||
|
def _wan(quality: Optional[dict], now: float) -> List[dict]:
|
||||||
|
if not quality or now - (quality.get('updated') or 0) > _WAN_STALE_S:
|
||||||
|
return []
|
||||||
|
out = []
|
||||||
|
periods = quality.get('periods') or []
|
||||||
|
# The last hour is the newest 12 periods (each stamped with its start), so the count
|
||||||
|
# doesn't dip while UniFi is still filling in the current one
|
||||||
|
newest = periods[-1]['ts'] if periods else now
|
||||||
|
recent = modem.quality_counts(periods, newest - _WAN_WINDOW_S + modem.QUALITY_PERIOD_S)
|
||||||
|
total = sum(recent.values())
|
||||||
|
bad = total - recent['ok']
|
||||||
|
day = modem.quality_counts(periods, now - 86400)
|
||||||
|
day_bad = sum(day.values()) - day['ok']
|
||||||
|
latencies = quality.get('latencies') or {}
|
||||||
|
detail = (f'UniFi flagged {day_bad} of the last {sum(day.values())} five-minute periods. '
|
||||||
|
if day_bad else '')
|
||||||
|
if latencies:
|
||||||
|
detail += 'Now: ' + ', '.join(f'{k} {v} ms' for k, v in sorted(latencies.items())) + '. '
|
||||||
|
detail += 'See the 24 hour strip on the WAN / Fiber panel.'
|
||||||
|
lossy = recent['loss'] + recent['down']
|
||||||
|
if lossy >= _WAN_LOSS_PERIODS:
|
||||||
|
out.append(_entry('broken', 'bad', f'Internet: packet loss in {lossy} of the last {total} '
|
||||||
|
'five-minute periods', '#modem-section', detail))
|
||||||
|
elif bad >= _WAN_BAD_PERIODS:
|
||||||
|
out.append(_entry('broken', 'warn', f'Internet: high latency in {bad} of the last {total} '
|
||||||
|
'five-minute periods', '#modem-section', detail))
|
||||||
|
drops = [d for d in quality.get('downtime') or [] if d['ts'] >= now - _WAN_WINDOW_S]
|
||||||
|
if len(drops) == 1:
|
||||||
|
out.append(_entry('broken', 'warn', f'Internet dropped for {round(drops[0]["seconds"])} s, '
|
||||||
|
f'{_ago(now - drops[0]["ts"])}', '#modem-section'))
|
||||||
|
elif drops:
|
||||||
|
out.append(_entry('broken', 'warn', f'Internet dropped {len(drops)} times in the last hour, '
|
||||||
|
f'{round(sum(d["seconds"] for d in drops))} s in all',
|
||||||
|
'#modem-section'))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
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) -> dict:
|
rack_issues: Optional[Dict[str, dict]] = None, wan_quality: Optional[dict] = None,
|
||||||
|
now: Optional[float] = 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. now: for tests.
|
||||||
Entry: {group, severity: bad|warn|info, text, href, detail}.
|
Entry: {group, severity: bad|warn|info, text, href, detail}.
|
||||||
"""
|
"""
|
||||||
entries = _alerts(events) + _power(power)
|
entries = _wan(wan_quality, time.time() if now is None else now) + _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 {})
|
||||||
|
|||||||
@@ -310,3 +310,53 @@ def record_uptime_reset(history: dict, boot_ts: float) -> None:
|
|||||||
return
|
return
|
||||||
restarts.append({'at': boot_ts, 'by': None, 'confirmed': True})
|
restarts.append({'at': boot_ts, 'by': None, 'confirmed': True})
|
||||||
del restarts[:-_HISTORY_LIMIT]
|
del restarts[:-_HISTORY_LIMIT]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# WAN quality: UniFi's own 5 minute health timeline (high latency, packet loss, down),
|
||||||
|
# the same data its Network app charts. Read only; Gandalf doesn't measure it again.
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
QUALITY_STATES = ('ok', 'latency', 'loss', 'down') # mildest to worst
|
||||||
|
QUALITY_PERIOD_S = 300
|
||||||
|
|
||||||
|
|
||||||
|
def wan_quality(dashboard: dict, now: float) -> Optional[dict]:
|
||||||
|
"""The primary WAN's health timeline from UniFi's aggregated dashboard, or None.
|
||||||
|
|
||||||
|
Returns {'wan', 'periods': [{'ts', 'state'}], 'downtime': [{'ts', 'seconds'}],
|
||||||
|
'latencies': {service: ms}, 'updated'}. Each period is 5 minutes; its state is the
|
||||||
|
worst flag UniFi set for it.
|
||||||
|
"""
|
||||||
|
details = ((dashboard or {}).get('wan_history') or {}).get('wan_history_details') or []
|
||||||
|
if not details:
|
||||||
|
return None
|
||||||
|
primary = next((d for d in details if d.get('network_group') == 'WAN'), details[0])
|
||||||
|
periods = []
|
||||||
|
for h in primary.get('health_history') or []:
|
||||||
|
if not isinstance(h.get('timestamp'), (int, float)):
|
||||||
|
continue
|
||||||
|
state = ('down' if h.get('wan_downtime') else 'loss' if h.get('packet_loss')
|
||||||
|
else 'latency' if h.get('high_latency') else 'ok')
|
||||||
|
periods.append({'ts': h['timestamp'] / 1000, 'state': state})
|
||||||
|
periods.sort(key=lambda p: p['ts'])
|
||||||
|
downtime = sorted(
|
||||||
|
({'ts': d['timestamp'] / 1000, 'seconds': d.get('downtime_in_seconds') or 0}
|
||||||
|
for d in primary.get('downtime_history') or [] if isinstance(d.get('timestamp'), (int, float))),
|
||||||
|
key=lambda d: d['ts'])
|
||||||
|
latencies = {}
|
||||||
|
for w in ((dashboard.get('wan') or {}).get('wan_details') or []):
|
||||||
|
if w.get('network_group') == primary.get('network_group'):
|
||||||
|
for s in (w.get('stats') or {}).get('service_latencies') or []:
|
||||||
|
if s.get('service_name') and isinstance(s.get('latency'), (int, float)):
|
||||||
|
latencies[s['service_name']] = s['latency']
|
||||||
|
return {'wan': primary.get('network_group') or '', 'periods': periods, 'downtime': downtime,
|
||||||
|
'latencies': latencies, 'updated': now}
|
||||||
|
|
||||||
|
|
||||||
|
def quality_counts(periods: List[dict], since: float) -> Dict[str, int]:
|
||||||
|
"""How many periods starting at or after *since* were in each state."""
|
||||||
|
counts = {s: 0 for s in QUALITY_STATES}
|
||||||
|
for p in periods:
|
||||||
|
if p['ts'] >= since and p['state'] in counts:
|
||||||
|
counts[p['state']] += 1
|
||||||
|
return counts
|
||||||
+27
-1
@@ -229,6 +229,19 @@ class UnifiClient:
|
|||||||
logger.error(f'UniFi system log error: {e}')
|
logger.error(f'UniFi system log error: {e}')
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def get_wan_dashboard(self) -> Optional[dict]:
|
||||||
|
"""UniFi's aggregated dashboard for the last day (WAN health timeline and service
|
||||||
|
latencies, as the Network app charts them), or None if unavailable. Read only."""
|
||||||
|
url = f'{self.base_url}/proxy/network/v2/api/site/{self.site_id}/aggregated-dashboard'
|
||||||
|
try:
|
||||||
|
resp = self.session.get(url, headers=self.headers, timeout=20, params={'historySeconds': 86400})
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
return data if isinstance(data, dict) else None
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'UniFi dashboard error: {e}')
|
||||||
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _update_fields(params: dict) -> dict:
|
def _update_fields(params: dict) -> dict:
|
||||||
"""The app and versions of an update entry; nothing for other entries."""
|
"""The app and versions of an update entry; nothing for other entries."""
|
||||||
@@ -901,7 +914,7 @@ class LinkStatsCollector:
|
|||||||
"""
|
"""
|
||||||
Collect full link stats for all Prometheus-monitored hosts.
|
Collect full link stats for all Prometheus-monitored hosts.
|
||||||
|
|
||||||
*instance_map*: ``{'10.10.10.2:9100': 'large1', ...}``
|
*instance_map*: ``{'10.10.10.2:9100': 'compute-storage-02', ...}``
|
||||||
|
|
||||||
Returns a dict suitable for ``db.set_state('link_stats', ...)``.
|
Returns a dict suitable for ``db.set_state('link_stats', ...)``.
|
||||||
"""
|
"""
|
||||||
@@ -1950,6 +1963,13 @@ class NetworkMonitor:
|
|||||||
'point toward the provider or the modem rather than the fiber.',
|
'point toward the provider or the modem rather than the fiber.',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _collect_wan_quality(self) -> None:
|
||||||
|
"""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."""
|
||||||
|
quality = modem_api.wan_quality(self.unifi.get_wan_dashboard(), time.time())
|
||||||
|
if quality is not None:
|
||||||
|
db.set_state('wan_quality', quality)
|
||||||
|
|
||||||
def _collect_modem(self, suppressions: list) -> None:
|
def _collect_modem(self, suppressions: list) -> None:
|
||||||
"""Poll the modem, then store its status and raise any alerts."""
|
"""Poll the modem, then store its status and raise any alerts."""
|
||||||
try:
|
try:
|
||||||
@@ -2135,6 +2155,12 @@ class NetworkMonitor:
|
|||||||
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
|
||||||
|
try:
|
||||||
|
self._collect_wan_quality()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f'WAN quality collection failed: {e}', exc_info=True)
|
||||||
|
|
||||||
# Note on the tickets of anything that cleared this cycle (or failed to post before)
|
# Note on the tickets of anything that cleared this cycle (or failed to post before)
|
||||||
try:
|
try:
|
||||||
self._post_recovery_notes()
|
self._post_recovery_notes()
|
||||||
|
|||||||
+57
-12
@@ -363,6 +363,16 @@ function _modemLastRestart(history) {
|
|||||||
return `restarted ${_modemWhen(last.at)}${last.by ? ` by ${last.by}` : ''}`;
|
return `restarted ${_modemWhen(last.at)}${last.by ? ` by ${last.by}` : ''}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function _modemUptimeStat(data) {
|
||||||
|
if (data.uptime_s !== null && data.uptime_s !== undefined) {
|
||||||
|
return _modemStat('Uptime', _modemUptime(data.uptime_s), '', _modemLastRestart(data.wan_history));
|
||||||
|
}
|
||||||
|
const restarts = (data.wan_history && data.wan_history.restarts) || [];
|
||||||
|
if (!restarts.length) return '';
|
||||||
|
const last = restarts[restarts.length - 1];
|
||||||
|
return _modemStat('Last restart', _modemWhen(last.at), '', last.by ? `by ${last.by}` : '');
|
||||||
|
}
|
||||||
|
|
||||||
function _modemDuration(seconds) {
|
function _modemDuration(seconds) {
|
||||||
if (seconds < 60) return `${Math.round(seconds)}s`;
|
if (seconds < 60) return `${Math.round(seconds)}s`;
|
||||||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
|
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
|
||||||
@@ -385,6 +395,39 @@ function _modemOutages(history) {
|
|||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const _QUALITY_LABELS = { ok: 'fine', latency: 'high latency', loss: 'packet loss', down: 'down' };
|
||||||
|
|
||||||
|
// UniFi's own internet health timeline, one block per 5 minutes, worst flag wins
|
||||||
|
function _modemQuality(q) {
|
||||||
|
const periods = (q && q.periods) || [];
|
||||||
|
if (!periods.length) return '';
|
||||||
|
const counts = { ok: 0, latency: 0, loss: 0, down: 0 };
|
||||||
|
periods.forEach(p => { if (p.state in counts) counts[p.state] += 1; });
|
||||||
|
const t0 = periods[0].ts, span = Math.max(periods[periods.length - 1].ts + 300 - t0, 300);
|
||||||
|
const blocks = periods.map(p => {
|
||||||
|
const x = (p.ts - t0) / span * 1000, w = Math.max(300 / span * 1000, 1);
|
||||||
|
const tip = `${_modemWhen(p.ts)}: ${_QUALITY_LABELS[p.state] || p.state}`;
|
||||||
|
return `<rect class="wq-${lt.escHtml(p.state)}" x="${x.toFixed(1)}" y="0" width="${w.toFixed(2)}" height="20">` +
|
||||||
|
`<title>${lt.escHtml(tip)}</title></rect>`;
|
||||||
|
}).join('');
|
||||||
|
const flagged = ['latency', 'loss', 'down'].filter(s => counts[s])
|
||||||
|
.map(s => `${_QUALITY_LABELS[s]} ${counts[s]}`).join(', ');
|
||||||
|
const summary = flagged ? `${flagged} of ${periods.length} periods` : 'no problems';
|
||||||
|
const lat = Object.entries(q.latencies || {}).sort()
|
||||||
|
.map(([k, v]) => `${lt.escHtml(k)} ${lt.escHtml(String(v))} ms`).join(', ');
|
||||||
|
const legend = ['latency', 'loss', 'down']
|
||||||
|
.map(s => `<span><i class="wq-key wq-${s}"></i>${_QUALITY_LABELS[s]}</span>`).join('');
|
||||||
|
return `
|
||||||
|
<div class="modem-chart modem-quality">
|
||||||
|
<div class="modem-chart-title">Internet, last 24 hours (from UniFi) <span>${lt.escHtml(summary)}</span></div>
|
||||||
|
<svg viewBox="0 0 1000 20" preserveAspectRatio="none" role="img"
|
||||||
|
aria-label="Internet health over the last 24 hours: ${lt.escHtml(summary)}">${blocks}</svg>
|
||||||
|
<div class="wq-foot"><span>${lt.escHtml(_modemWhen(t0))}</span>
|
||||||
|
<span class="wq-legend">${legend}</span><span>now</span></div>
|
||||||
|
${lat ? `<div class="modem-stat-note">Latency now: ${lat}</div>` : ''}
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
|
||||||
function updateModem(data) {
|
function updateModem(data) {
|
||||||
const section = document.getElementById('modem-section');
|
const section = document.getElementById('modem-section');
|
||||||
const body = document.getElementById('modem-body');
|
const body = document.getElementById('modem-body');
|
||||||
@@ -405,6 +448,7 @@ function updateModem(data) {
|
|||||||
body.innerHTML = `
|
body.innerHTML = `
|
||||||
<div class="modem-error">Modem status unavailable: ${lt.escHtml(data.error || 'unknown error')}
|
<div class="modem-error">Modem status unavailable: ${lt.escHtml(data.error || 'unknown error')}
|
||||||
<span class="modem-stat-note">Last attempt ${lt.escHtml(data.updated || '-')}</span></div>
|
<span class="modem-stat-note">Last attempt ${lt.escHtml(data.updated || '-')}</span></div>
|
||||||
|
${_modemQuality(data.wan_quality)}
|
||||||
${_modemChart(data.history)}`;
|
${_modemChart(data.history)}`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -433,8 +477,9 @@ function updateModem(data) {
|
|||||||
${_modemOptic('Optics temp', optics.temperature, status.temperature, '°C')}
|
${_modemOptic('Optics temp', optics.temperature, status.temperature, '°C')}
|
||||||
${_modemStat('Throughput', `↓ ${_modemRate(rates.rx_bytes)}`, '', `↑ ${_modemRate(rates.tx_bytes)}`)}
|
${_modemStat('Throughput', `↓ ${_modemRate(rates.rx_bytes)}`, '', `↑ ${_modemRate(rates.tx_bytes)}`)}
|
||||||
${_modemStat('Errors / drops', `${errs} / ${drops}`, errs ? 'lt-text-amber' : '', 'since modem reboot')}
|
${_modemStat('Errors / drops', `${errs} / ${drops}`, errs ? 'lt-text-amber' : '', 'since modem reboot')}
|
||||||
${_modemStat('Uptime', _modemUptime(data.uptime_s), '', _modemLastRestart(data.wan_history))}
|
${_modemUptimeStat(data)}
|
||||||
</div>
|
</div>
|
||||||
|
${_modemQuality(data.wan_quality)}
|
||||||
${_modemChart(data.history)}
|
${_modemChart(data.history)}
|
||||||
${_modemOutages(data.wan_history)}
|
${_modemOutages(data.wan_history)}
|
||||||
<div class="modem-stat-note modem-updated">Updated ${lt.escHtml(data.updated || '-')}</div>`;
|
<div class="modem-stat-note modem-updated">Updated ${lt.escHtml(data.updated || '-')}</div>`;
|
||||||
@@ -491,16 +536,16 @@ function updateEventsTable(events, totalActive) {
|
|||||||
: '';
|
: '';
|
||||||
return `
|
return `
|
||||||
<tr class="row-${e.severity}${e.is_suppressed ? ' row-suppressed' : ''}">
|
<tr class="row-${e.severity}${e.is_suppressed ? ' row-suppressed' : ''}">
|
||||||
<td><span class="lt-badge badge-${e.severity}">${e.severity}</span>${supBadge}${staleBadge}${closedBadge}</td>
|
<td data-label="Sev"><span class="lt-badge badge-${e.severity}">${e.severity}</span>${supBadge}${staleBadge}${closedBadge}</td>
|
||||||
<td>${lt.escHtml(e.event_type.replace(/_/g,' '))}</td>
|
<td data-label="Type">${lt.escHtml(e.event_type.replace(/_/g,' '))}</td>
|
||||||
<td><strong>${lt.escHtml(e.target_name)}</strong></td>
|
<td data-label="Target"><strong>${lt.escHtml(e.target_name)}</strong></td>
|
||||||
<td>${lt.escHtml(e.target_detail || '-')}</td>
|
<td data-label="Detail">${lt.escHtml(e.target_detail || '-')}</td>
|
||||||
<td class="desc-cell" title="${lt.escHtml(e.description || '')}">${lt.escHtml((e.description||'').substring(0,60))}${(e.description||'').length>60?'…':''}</td>
|
<td data-label="Description" class="desc-cell" title="${lt.escHtml(e.description || '')}">${lt.escHtml((e.description||'').substring(0,60))}${(e.description||'').length>60?'…':''}</td>
|
||||||
<td class="ts-cell" title="${lt.escHtml(e.first_seen||'')}">${lt.time.ago(_toIso(e.first_seen))}</td>
|
<td data-label="First seen" class="ts-cell" title="${lt.escHtml(e.first_seen||'')}">${lt.time.ago(_toIso(e.first_seen))}</td>
|
||||||
<td class="ts-cell" title="${lt.escHtml(e.last_seen||'')}">${lt.time.ago(_toIso(e.last_seen))}</td>
|
<td data-label="Last seen" class="ts-cell" title="${lt.escHtml(e.last_seen||'')}">${lt.time.ago(_toIso(e.last_seen))}</td>
|
||||||
<td>${e.consecutive_failures}</td>
|
<td data-label="Failures">${e.consecutive_failures}</td>
|
||||||
<td>${ticket}</td>
|
<td data-label="Ticket">${ticket}</td>
|
||||||
<td>
|
<td data-label="Actions">
|
||||||
<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress"
|
<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress"
|
||||||
data-sup-type="${lt.escHtml(supType)}"
|
data-sup-type="${lt.escHtml(supType)}"
|
||||||
data-sup-name="${lt.escHtml(e.target_name)}"
|
data-sup-name="${lt.escHtml(e.target_name)}"
|
||||||
@@ -513,7 +558,7 @@ function updateEventsTable(events, totalActive) {
|
|||||||
wrap.innerHTML = `
|
wrap.innerHTML = `
|
||||||
${countNotice}
|
${countNotice}
|
||||||
<div class="lt-table-wrap">
|
<div class="lt-table-wrap">
|
||||||
<table class="lt-table" id="events-table">
|
<table class="lt-table lt-table-responsive" id="events-table">
|
||||||
<caption class="lt-sr-only">Active network alerts</caption>
|
<caption class="lt-sr-only">Active network alerts</caption>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
|
|||||||
@@ -488,6 +488,7 @@
|
|||||||
const date = value instanceof Date ? value : new Date(value);
|
const date = value instanceof Date ? value : new Date(value);
|
||||||
if (isNaN(date)) return '-';
|
if (isNaN(date)) return '-';
|
||||||
const diff = Math.floor((Date.now() - date.getTime()) / 1000);
|
const diff = Math.floor((Date.now() - date.getTime()) / 1000);
|
||||||
|
if (diff < 5) return 'just now'; // also a clock a little ahead of this browser's
|
||||||
if (diff < 60) return diff + 's ago';
|
if (diff < 60) return diff + 's ago';
|
||||||
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
|
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
|
||||||
if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
|
if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
|
||||||
|
|||||||
+42
-8
@@ -177,13 +177,18 @@
|
|||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: .08em;
|
letter-spacing: .08em;
|
||||||
}
|
}
|
||||||
|
/* A count. Neutral by default; red only where it counts problems (active alerts, follow-ups). */
|
||||||
.g-section-badge {
|
.g-section-badge {
|
||||||
font-size: .72em;
|
font-size: .72em;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
color: var(--accent-red);
|
color: var(--text-muted);
|
||||||
border: 1px solid var(--accent-red);
|
border: 1px solid var(--border-color);
|
||||||
padding: 1px 7px;
|
padding: 1px 7px;
|
||||||
}
|
}
|
||||||
|
.g-section-badge-alert {
|
||||||
|
color: var(--accent-red);
|
||||||
|
border-color: var(--accent-red);
|
||||||
|
}
|
||||||
.g-section-badge-resolved {
|
.g-section-badge-resolved {
|
||||||
font-size: .68em;
|
font-size: .68em;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
@@ -330,7 +335,6 @@
|
|||||||
letter-spacing: .04em;
|
letter-spacing: .04em;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
}
|
}
|
||||||
.source-prometheus { color: var(--orange); border-color: var(--orange-dim); }
|
|
||||||
.source-ping { color: var(--cyan); border-color: var(--cyan-dim); }
|
.source-ping { color: var(--cyan); border-color: var(--cyan-dim); }
|
||||||
.iface-list { border-top: 1px solid var(--border-color); padding-top: 6px; margin-bottom: 8px; }
|
.iface-list { border-top: 1px solid var(--border-color); padding-top: 6px; margin-bottom: 8px; }
|
||||||
.iface-row { display: flex; align-items: center; gap: 6px; padding: 2px 0; }
|
.iface-row { display: flex; align-items: center; gap: 6px; padding: 2px 0; }
|
||||||
@@ -345,8 +349,9 @@
|
|||||||
/* ── Form layout helpers (used in suppressions.html form grids) ───── */
|
/* ── Form layout helpers (used in suppressions.html form grids) ───── */
|
||||||
.form-row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
|
.form-row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }
|
||||||
.form-row-align { align-items: flex-end; }
|
.form-row-align { align-items: flex-end; }
|
||||||
|
.form-row > .lt-form-group { flex: 1 1 220px; }
|
||||||
.form-group-wide { flex: 3; }
|
.form-group-wide { flex: 3; }
|
||||||
.form-group-submit { flex: 0 0 auto; min-width: unset; }
|
.form-group-submit, .form-row > .form-group-submit { flex: 0 0 auto; min-width: unset; }
|
||||||
.required { color: var(--red); }
|
.required { color: var(--red); }
|
||||||
|
|
||||||
/* ── Duration pills ───────────────────────────────────────────────── */
|
/* ── Duration pills ───────────────────────────────────────────────── */
|
||||||
@@ -844,6 +849,18 @@
|
|||||||
.modem-chart svg { display: block; width: 100%; height: 70px; border: 1px solid var(--border-color); }
|
.modem-chart svg { display: block; width: 100%; height: 70px; border: 1px solid var(--border-color); }
|
||||||
.modem-chart svg polyline { stroke: var(--terminal-cyan, #0ff); stroke-width: 1.5; }
|
.modem-chart svg polyline { stroke: var(--terminal-cyan, #0ff); stroke-width: 1.5; }
|
||||||
.modem-chart-empty { padding: 0 12px 8px; font-size: .72em; color: var(--text-muted); }
|
.modem-chart-empty { padding: 0 12px 8px; font-size: .72em; color: var(--text-muted); }
|
||||||
|
.modem-quality svg { height: 20px; }
|
||||||
|
.wq-ok { fill: var(--accent-green-dim, rgba(0, 255, 0, .25)); }
|
||||||
|
.wq-latency { fill: var(--accent-amber); }
|
||||||
|
.wq-loss { fill: var(--accent-red); }
|
||||||
|
.wq-down { fill: var(--text-primary, #fff); }
|
||||||
|
.wq-foot { display: flex; justify-content: space-between; gap: 8px; flex-wrap: wrap;
|
||||||
|
font-size: .68em; color: var(--text-muted); margin-top: 3px; }
|
||||||
|
.wq-legend { display: inline-flex; gap: 10px; flex-wrap: wrap; }
|
||||||
|
.wq-key { display: inline-block; width: 9px; height: 9px; margin-right: 4px; vertical-align: -1px; }
|
||||||
|
.wq-key.wq-latency { background: var(--accent-amber); }
|
||||||
|
.wq-key.wq-loss { background: var(--accent-red); }
|
||||||
|
.wq-key.wq-down { background: var(--text-primary, #fff); }
|
||||||
.modem-updated { padding: 0 12px 10px; }
|
.modem-updated { padding: 0 12px 10px; }
|
||||||
|
|
||||||
/* ── Device search (home page) ────────────────────────────────────── */
|
/* ── Device search (home page) ────────────────────────────────────── */
|
||||||
@@ -902,10 +919,6 @@ a.device-link:hover { color: var(--text-accent); border-bottom-color: current
|
|||||||
.device-table th, .device-table td { padding-left: 6px; padding-right: 6px; }
|
.device-table th, .device-table td { padding-left: 6px; padding-right: 6px; }
|
||||||
}
|
}
|
||||||
.device-search-row.is-active { box-shadow: inset 3px 0 0 var(--terminal-cyan, #0ff); }
|
.device-search-row.is-active { box-shadow: inset 3px 0 0 var(--terminal-cyan, #0ff); }
|
||||||
@media (max-width: 700px) {
|
|
||||||
/* Scroll inside the wrapper rather than squeezing every column to a few letters */
|
|
||||||
#events-table { min-width: 760px; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── Port inspector on the device page ────────────────────────────── */
|
/* ── Port inspector on the device page ────────────────────────────── */
|
||||||
.device-inspector { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 14px 16px; align-items: start; }
|
.device-inspector { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 14px 16px; align-items: start; }
|
||||||
@@ -1815,3 +1828,24 @@ body.fp-marks-off .fp-svg .fp-mark { display: none; }
|
|||||||
.lt-header-user, .lt-cmd-hint-btn, .lt-header-right [data-action="start-maintenance"] { display: none; }
|
.lt-header-user, .lt-cmd-hint-btn, .lt-header-right [data-action="start-maintenance"] { display: none; }
|
||||||
}
|
}
|
||||||
.g-drawer-action { background: none; border: 0; width: 100%; text-align: left; font: inherit; cursor: pointer; }
|
.g-drawer-action { background: none; border: 0; width: 100%; text-align: left; font: inherit; cursor: pointer; }
|
||||||
|
|
||||||
|
/* ── Footer: the CFG and HELP buttons read like the keyboard hints beside them ── */
|
||||||
|
button.lt-footer-hint {
|
||||||
|
background: none; border: 0; padding: 0; margin: 0;
|
||||||
|
font: inherit; color: inherit; letter-spacing: inherit; text-transform: inherit; cursor: pointer;
|
||||||
|
}
|
||||||
|
button.lt-footer-hint:hover, button.lt-footer-hint:focus-visible { color: var(--accent-cyan, var(--cyan)); }
|
||||||
|
|
||||||
|
/* ── Footer at the bottom of the window on short pages, not halfway up ── */
|
||||||
|
body { display: flex; flex-direction: column; }
|
||||||
|
body > .lt-main { flex: 1 0 auto; width: 100%; }
|
||||||
|
body > .lt-footer { flex-shrink: 0; }
|
||||||
|
|
||||||
|
/* ── Active alerts: room for the filter's hint; full-width cards on phones ── */
|
||||||
|
#events-search { min-width: 300px; }
|
||||||
|
@media (max-width: 767px) {
|
||||||
|
#events-search { min-width: 0; }
|
||||||
|
#events-table, #events-table tbody { display: block; width: 100%; }
|
||||||
|
#events-table td { max-width: none; }
|
||||||
|
#events-table td.desc-cell { white-space: normal; text-align: right; }
|
||||||
|
}
|
||||||
+1
-1
@@ -290,7 +290,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="lt-form-group" id="sup-name-group">
|
<div class="lt-form-group" id="sup-name-group">
|
||||||
<label class="lt-label" for="sup-name">Target Name</label>
|
<label class="lt-label" for="sup-name">Target Name</label>
|
||||||
<input type="text" class="lt-input" id="sup-name" name="target_name" placeholder="e.g. large1">
|
<input type="text" class="lt-input" id="sup-name" name="target_name" placeholder="e.g. compute-storage-02">
|
||||||
</div>
|
</div>
|
||||||
<div class="lt-form-group" id="sup-detail-group" style="display:none">
|
<div class="lt-form-group" id="sup-detail-group" style="display:none">
|
||||||
<label class="lt-label" for="sup-detail">Interface <span class="lt-field-hint">(interface type only)</span></label>
|
<label class="lt-label" for="sup-detail">Interface <span class="lt-field-hint">(interface type only)</span></label>
|
||||||
|
|||||||
+14
-14
@@ -53,7 +53,7 @@
|
|||||||
<section class="g-section">
|
<section class="g-section">
|
||||||
<div class="g-section-header">
|
<div class="g-section-header">
|
||||||
<h2 class="g-section-title">Active Alerts</h2>
|
<h2 class="g-section-title">Active Alerts</h2>
|
||||||
<span class="g-section-badge" id="alert-count-badge"
|
<span class="g-section-badge g-section-badge-alert" id="alert-count-badge"
|
||||||
{% if not summary.critical and not summary.warning %}style="display:none"{% endif %}>{{ (summary.critical or 0) + (summary.warning or 0) }}</span>
|
{% if not summary.critical and not summary.warning %}style="display:none"{% endif %}>{{ (summary.critical or 0) + (summary.warning or 0) }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="lt-toolbar">
|
<div class="lt-toolbar">
|
||||||
@@ -80,7 +80,7 @@
|
|||||||
<div class="pagination-notice">Showing {{ events|length }} of {{ total_active }} active alerts. Use the search box to filter, or <a href="/api/events?limit=1000" target="_blank" rel="noopener">export all as JSON</a></div>
|
<div class="pagination-notice">Showing {{ events|length }} of {{ total_active }} active alerts. Use the search box to filter, or <a href="/api/events?limit=1000" target="_blank" rel="noopener">export all as JSON</a></div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
<div class="lt-table-wrap">
|
<div class="lt-table-wrap">
|
||||||
<table class="lt-table" id="events-table">
|
<table class="lt-table lt-table-responsive" id="events-table">
|
||||||
<caption class="lt-sr-only">Active network alerts</caption>
|
<caption class="lt-sr-only">Active network alerts</caption>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -100,30 +100,30 @@
|
|||||||
{% for e in events %}
|
{% for e in events %}
|
||||||
{% if e.severity != 'info' %}
|
{% if e.severity != 'info' %}
|
||||||
<tr class="row-{{ e.severity }}{% if e.is_suppressed %} row-suppressed{% endif %}">
|
<tr class="row-{{ e.severity }}{% if e.is_suppressed %} row-suppressed{% endif %}">
|
||||||
<td>
|
<td data-label="Sev">
|
||||||
<span class="lt-badge badge-{{ e.severity }}">{{ e.severity }}</span>
|
<span class="lt-badge badge-{{ e.severity }}">{{ e.severity }}</span>
|
||||||
{% if e.is_suppressed %}<span class="lt-badge badge-suppressed" title="Alert suppressed">🔕 sup</span>{% endif %}
|
{% if e.is_suppressed %}<span class="lt-badge badge-suppressed" title="Alert suppressed">🔕 sup</span>{% endif %}
|
||||||
{% if e.stale_days is not none %}<span class="lt-badge badge-stale" title="Active for {{ e.stale_days }} days with no fix yet">⏳ {{ e.stale_days }}d</span>{% endif %}
|
{% if e.stale_days is not none %}<span class="lt-badge badge-stale" title="Active for {{ e.stale_days }} days with no fix yet">⏳ {{ e.stale_days }}d</span>{% endif %}
|
||||||
{% if e.ticket_closed %}<span class="lt-badge badge-ticket-closed" title="Ticket #{{ e.ticket_id }} was closed in Tinker, but this alert is still active">ticket closed</span>{% endif %}
|
{% if e.ticket_closed %}<span class="lt-badge badge-ticket-closed" title="Ticket #{{ e.ticket_id }} was closed in Tinker, but this alert is still active">ticket closed</span>{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>{{ e.event_type | replace('_', ' ') }}</td>
|
<td data-label="Type">{{ e.event_type | replace('_', ' ') }}</td>
|
||||||
<td><strong>{{ e.target_name }}</strong></td>
|
<td data-label="Target"><strong>{{ e.target_name }}</strong></td>
|
||||||
<td>{{ e.target_detail or '-' }}</td>
|
<td data-label="Detail">{{ e.target_detail or '-' }}</td>
|
||||||
<td class="desc-cell" title="{{ e.description | e }}">{{ e.description | truncate(60) }}</td>
|
<td data-label="Description" class="desc-cell" title="{{ e.description | e }}">{{ e.description | truncate(60) }}</td>
|
||||||
<td class="ts-cell" title="{{ e.first_seen }}">
|
<td data-label="First seen" class="ts-cell" title="{{ e.first_seen }}">
|
||||||
<span class="event-age" data-ts="{{ e.first_seen }}">{{ e.first_seen }}</span>
|
<span class="event-age" data-ts="{{ e.first_seen }}">{{ e.first_seen }}</span>
|
||||||
</td>
|
</td>
|
||||||
<td class="ts-cell" title="{{ e.last_seen }}">
|
<td data-label="Last seen" class="ts-cell" title="{{ e.last_seen }}">
|
||||||
<span class="event-age" data-ts="{{ e.last_seen }}">{{ e.last_seen }}</span>
|
<span class="event-age" data-ts="{{ e.last_seen }}">{{ e.last_seen }}</span>
|
||||||
</td>
|
</td>
|
||||||
<td>{{ e.consecutive_failures }}</td>
|
<td data-label="Failures">{{ e.consecutive_failures }}</td>
|
||||||
<td>
|
<td data-label="Ticket">
|
||||||
{% if e.ticket_id %}
|
{% if e.ticket_id %}
|
||||||
<a href="{{ config.ticket_api.web_url }}{{ e.ticket_id }}" target="_blank"
|
<a href="{{ config.ticket_api.web_url }}{{ e.ticket_id }}" target="_blank"
|
||||||
class="ticket-link">#{{ e.ticket_id }}</a>
|
class="ticket-link">#{{ e.ticket_id }}</a>
|
||||||
{% else %}-{% endif %}
|
{% else %}-{% endif %}
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td data-label="Actions">
|
||||||
<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress"
|
<button class="lt-btn lt-btn-ghost lt-btn-sm btn-suppress"
|
||||||
data-sup-type="{{ 'unifi_device' if e.event_type == 'unifi_device_offline' else 'interface' if e.event_type == 'interface_down' else 'host' }}"
|
data-sup-type="{{ 'unifi_device' if e.event_type == 'unifi_device_offline' else 'interface' if e.event_type == 'interface_down' else 'host' }}"
|
||||||
data-sup-name="{{ e.target_name }}"
|
data-sup-name="{{ e.target_name }}"
|
||||||
@@ -157,7 +157,7 @@
|
|||||||
<section class="g-section" id="followup"{% if not stale_tickets %} hidden{% endif %}>
|
<section class="g-section" id="followup"{% if not stale_tickets %} hidden{% endif %}>
|
||||||
<div class="g-section-header">
|
<div class="g-section-header">
|
||||||
<h2 class="g-section-title">Needs Follow-up</h2>
|
<h2 class="g-section-title">Needs Follow-up</h2>
|
||||||
<span class="g-section-badge" id="followup-badge">{{ stale_tickets | length }}</span>
|
<span class="g-section-badge g-section-badge-alert" id="followup-badge">{{ stale_tickets | length }}</span>
|
||||||
</div>
|
</div>
|
||||||
<p class="followup-intro">These tickets are still open in Tinker, but their alert cleared over a day ago. Close them if the problem is fixed.</p>
|
<p class="followup-intro">These tickets are still open in Tinker, but their alert cleared over a day ago. Close them if the problem is fixed.</p>
|
||||||
<div class="lt-frame">
|
<div class="lt-frame">
|
||||||
@@ -212,7 +212,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="host-meta">
|
<div class="host-meta">
|
||||||
<span class="host-ip">{{ host.ip }}</span>
|
<span class="host-ip">{{ host.ip }}</span>
|
||||||
<span class="host-source source-{{ host.source }}">{{ host.source }}</span>
|
{% if host.source != 'prometheus' %}<span class="host-source source-{{ host.source }}">{{ host.source }}</span>{% endif %}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -50,7 +50,7 @@
|
|||||||
<div class="lt-form-group form-group-wide">
|
<div class="lt-form-group form-group-wide">
|
||||||
<label class="lt-label" for="s-reason">Reason <span class="required">*</span></label>
|
<label class="lt-label" for="s-reason">Reason <span class="required">*</span></label>
|
||||||
<input type="text" class="lt-input" id="s-reason" name="reason"
|
<input type="text" class="lt-input" id="s-reason" name="reason"
|
||||||
placeholder="e.g. Planned switch maintenance, replacing SFP on large1/enp43s0"
|
placeholder="e.g. Planned switch maintenance, replacing SFP on compute-storage-02/enp43s0"
|
||||||
required aria-required="true">
|
required aria-required="true">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -820,6 +820,19 @@ class TestAttention:
|
|||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert set(resp.get_json()) == {'broken', 'tidy'}
|
assert set(resp.get_json()) == {'broken', 'tidy'}
|
||||||
|
|
||||||
|
def test_internet_quality_from_unifi(self, client):
|
||||||
|
now = time.time()
|
||||||
|
quality = {'periods': [{'ts': now - (12 - i) * 300, 'state': 'loss'} for i in range(12)],
|
||||||
|
'downtime': [], 'latencies': {}, 'updated': now}
|
||||||
|
state = {'wan_quality': json.dumps(quality), 'modem_stats': json.dumps({'reachable': True})}
|
||||||
|
with patch.object(gandalf.db, 'get_state', side_effect=lambda k, d=None: state.get(k, d)), \
|
||||||
|
patch.object(gandalf.db, 'get_modem_history', return_value=[]), \
|
||||||
|
patch.object(gandalf.db, 'cutsheet_load', side_effect=RuntimeError('db down')):
|
||||||
|
data = client.get('/api/attention', headers=AUTH).get_json()
|
||||||
|
modem = client.get('/api/modem', headers=AUTH).get_json()
|
||||||
|
assert data['broken'][0]['text'] == 'Internet: packet loss in 12 of the last 12 five-minute periods'
|
||||||
|
assert len(modem['wan_quality']['periods']) == 12
|
||||||
|
|
||||||
def test_dashboard_has_the_list_and_says_what_gandalf_stands_for(self, client):
|
def test_dashboard_has_the_list_and_says_what_gandalf_stands_for(self, client):
|
||||||
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||||
assert 'id="attention-body"' in html
|
assert 'id="attention-body"' in html
|
||||||
@@ -837,6 +850,25 @@ class TestCalmDashboard:
|
|||||||
assert '>eth0<' in html and '>eth1<' not in html
|
assert '>eth0<' in html and '>eth1<' not in html
|
||||||
assert '+2 unused' in html
|
assert '+2 unused' in html
|
||||||
|
|
||||||
|
def test_source_tag_only_for_hosts_without_node_exporter(self, client):
|
||||||
|
snap = json.dumps({'hosts': {
|
||||||
|
'large1': {'ip': '10.0.0.2', 'status': 'up', 'source': 'prometheus', 'interfaces': {'eth0': 'up'}},
|
||||||
|
'pbs': {'ip': '10.0.0.3', 'status': 'up', 'source': 'ping', 'interfaces': {}}}, 'unifi': []})
|
||||||
|
state = dict(STATE, network_snapshot=snap)
|
||||||
|
with patch.object(gandalf.db, 'get_state', side_effect=lambda k, d=None: state.get(k, d)):
|
||||||
|
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||||
|
assert 'source-prometheus' not in html
|
||||||
|
assert '<span class="host-source source-ping">ping</span>' in html
|
||||||
|
|
||||||
|
def test_alert_table_turns_into_cards_on_phones(self, client):
|
||||||
|
ev = {'id': 1, 'event_type': 'host_down', 'severity': 'critical', 'target_name': 'pbs',
|
||||||
|
'target_detail': '', 'description': 'pbs is down', 'consecutive_failures': 3,
|
||||||
|
'first_seen': '2026-11-15 01:00:00', 'last_seen': '2026-11-15 02:00:00'}
|
||||||
|
with patch.object(gandalf.db, 'get_active_events', return_value=[ev]):
|
||||||
|
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||||
|
assert 'class="lt-table lt-table-responsive" id="events-table"' in html
|
||||||
|
assert 'data-label="Target"><strong>pbs</strong>' in html
|
||||||
|
|
||||||
def test_resolved_alerts_are_folded(self, client):
|
def test_resolved_alerts_are_folded(self, client):
|
||||||
ev = {'target_name': 'large1', 'target_detail': '', 'severity': 'warning', 'event_type': 'host_down',
|
ev = {'target_name': 'large1', 'target_detail': '', 'severity': 'warning', 'event_type': 'host_down',
|
||||||
'first_seen': '2026-11-15 01:00:00 UTC', 'resolved_at': '2026-11-15 02:00:00 UTC'}
|
'first_seen': '2026-11-15 01:00:00 UTC', 'resolved_at': '2026-11-15 02:00:00 UTC'}
|
||||||
|
|||||||
@@ -84,3 +84,62 @@ class TestRack:
|
|||||||
|
|
||||||
def test_nothing_to_report(self):
|
def test_nothing_to_report(self):
|
||||||
assert attention.build([], [], {}, {}) == {'broken': [], 'tidy': []}
|
assert attention.build([], [], {}, {}) == {'broken': [], 'tidy': []}
|
||||||
|
|
||||||
|
|
||||||
|
NOW = 1_000_000.0
|
||||||
|
|
||||||
|
|
||||||
|
def _quality(states, downtime=(), latencies=None, updated=NOW):
|
||||||
|
"""states: newest last, one per 5 minutes ending at NOW."""
|
||||||
|
n = len(states)
|
||||||
|
return {'periods': [{'ts': NOW - (n - i) * 300, 'state': s} for i, s in enumerate(states)],
|
||||||
|
'downtime': [{'ts': NOW - ago, 'seconds': s} for ago, s in downtime],
|
||||||
|
'latencies': latencies or {}, 'updated': updated}
|
||||||
|
|
||||||
|
|
||||||
|
def _wan(q):
|
||||||
|
return [e for e in attention.build([], [], None, wan_quality=q, now=NOW)['broken']
|
||||||
|
if e['text'].startswith('Internet')]
|
||||||
|
|
||||||
|
|
||||||
|
class TestWan:
|
||||||
|
def test_healthy_says_nothing(self):
|
||||||
|
assert _wan(_quality(['ok'] * 288)) == []
|
||||||
|
|
||||||
|
def test_latency_in_the_last_hour(self):
|
||||||
|
[e] = _wan(_quality(['ok'] * 276 + ['latency', 'ok'] * 3 + ['latency'] * 3 + ['ok'] * 3,
|
||||||
|
latencies={'google': 26, 'cloudflare': 12}))
|
||||||
|
assert e['severity'] == 'warn' and e['href'] == '#modem-section'
|
||||||
|
assert e['text'] == 'Internet: high latency in 6 of the last 12 five-minute periods'
|
||||||
|
assert 'UniFi flagged 6 of the last 288' in e['detail']
|
||||||
|
assert 'Now: cloudflare 12 ms, google 26 ms' in e['detail']
|
||||||
|
|
||||||
|
def test_a_couple_of_slow_periods_are_not_worth_a_line(self):
|
||||||
|
assert _wan(_quality(['ok'] * 10 + ['latency'] * 2)) == []
|
||||||
|
|
||||||
|
def test_old_trouble_has_cleared(self):
|
||||||
|
assert _wan(_quality(['latency'] * 100 + ['ok'] * 12)) == []
|
||||||
|
|
||||||
|
def test_packet_loss_is_broken(self):
|
||||||
|
[e] = _wan(_quality(['ok'] * 9 + ['loss', 'latency', 'down']))
|
||||||
|
assert e['severity'] == 'bad'
|
||||||
|
assert e['text'] == 'Internet: packet loss in 2 of the last 12 five-minute periods'
|
||||||
|
|
||||||
|
def test_a_drop_in_the_last_hour(self):
|
||||||
|
[e] = _wan(_quality(['ok'] * 12, downtime=[(900, 90), (7200, 30)]))
|
||||||
|
assert e['text'] == 'Internet dropped for 90 s, 15 min ago'
|
||||||
|
|
||||||
|
def test_several_drops(self):
|
||||||
|
[e] = _wan(_quality(['ok'] * 12, downtime=[(900, 90), (1800, 30)]))
|
||||||
|
assert e['text'] == 'Internet dropped 2 times in the last hour, 120 s in all'
|
||||||
|
|
||||||
|
def test_stale_copy_is_ignored(self):
|
||||||
|
assert _wan(_quality(['loss'] * 12, updated=NOW - 3600)) == []
|
||||||
|
|
||||||
|
def test_none_is_fine(self):
|
||||||
|
assert _wan(None) == [] and _wan({}) == []
|
||||||
|
|
||||||
|
def test_internet_comes_before_alerts_of_the_same_severity(self):
|
||||||
|
out = attention.build([_alert('x', 'warning')], [], None,
|
||||||
|
wan_quality=_quality(['latency'] * 12), now=NOW)['broken']
|
||||||
|
assert out[0]['text'].startswith('Internet')
|
||||||
@@ -255,3 +255,49 @@ class TestWanHistory:
|
|||||||
h = {}
|
h = {}
|
||||||
modem.record_uptime_reset(h, 5000)
|
modem.record_uptime_reset(h, 5000)
|
||||||
assert h['restarts'] == [{'at': 5000, 'by': None, 'confirmed': True}]
|
assert h['restarts'] == [{'at': 5000, 'by': None, 'confirmed': True}]
|
||||||
|
|
||||||
|
|
||||||
|
def _dashboard(health, downtime=(), latencies=None, group='WAN'):
|
||||||
|
return {
|
||||||
|
'wan_history': {'wan_history_details': [{
|
||||||
|
'network_group': group,
|
||||||
|
'health_history': [dict({'timestamp': ts * 1000, 'high_latency': False, 'packet_loss': False,
|
||||||
|
'wan_downtime': False}, **flags) for ts, flags in health],
|
||||||
|
'downtime_history': [{'timestamp': ts * 1000, 'downtime_in_seconds': s} for ts, s in downtime],
|
||||||
|
}]},
|
||||||
|
'wan': {'wan_details': [{'network_group': group, 'stats': {'service_latencies': [
|
||||||
|
{'service_name': k, 'latency': v} for k, v in (latencies or {}).items()]}}]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestWanQuality:
|
||||||
|
def test_worst_flag_wins_and_periods_are_in_time_order(self):
|
||||||
|
q = modem.wan_quality(_dashboard([
|
||||||
|
(600, {'high_latency': True, 'packet_loss': True}),
|
||||||
|
(0, {}),
|
||||||
|
(300, {'high_latency': True}),
|
||||||
|
(900, {'wan_downtime': True, 'packet_loss': True}),
|
||||||
|
]), now=1000)
|
||||||
|
assert [p['state'] for p in q['periods']] == ['ok', 'latency', 'loss', 'down']
|
||||||
|
assert [p['ts'] for p in q['periods']] == [0, 300, 600, 900]
|
||||||
|
assert q['updated'] == 1000 and q['wan'] == 'WAN'
|
||||||
|
|
||||||
|
def test_downtime_and_latencies(self):
|
||||||
|
q = modem.wan_quality(_dashboard([(0, {})], downtime=[(500, 90)],
|
||||||
|
latencies={'cloudflare': 12, 'google': 26}), now=1)
|
||||||
|
assert q['downtime'] == [{'ts': 500, 'seconds': 90}]
|
||||||
|
assert q['latencies'] == {'cloudflare': 12, 'google': 26}
|
||||||
|
|
||||||
|
def test_prefers_the_primary_wan(self):
|
||||||
|
d = _dashboard([(0, {'high_latency': True})], group='WAN2')
|
||||||
|
d['wan_history']['wan_history_details'].append(
|
||||||
|
_dashboard([(0, {})])['wan_history']['wan_history_details'][0])
|
||||||
|
assert modem.wan_quality(d, 0)['periods'][0]['state'] == 'ok'
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('dashboard', [None, {}, {'wan_history': {}}, {'wan_history': {'wan_history_details': []}}])
|
||||||
|
def test_missing_history_is_none(self, dashboard):
|
||||||
|
assert modem.wan_quality(dashboard, 0) is None
|
||||||
|
|
||||||
|
def test_counts_since(self):
|
||||||
|
periods = [{'ts': 0, 'state': 'latency'}, {'ts': 300, 'state': 'ok'}, {'ts': 600, 'state': 'loss'}]
|
||||||
|
assert modem.quality_counts(periods, 300) == {'ok': 1, 'latency': 0, 'loss': 1, 'down': 0}
|
||||||
@@ -1018,3 +1018,33 @@ class TestSyncOpenTickets:
|
|||||||
mon._open_tickets_synced -= monitor.OPEN_TICKETS_SYNC_S + 1
|
mon._open_tickets_synced -= monitor.OPEN_TICKETS_SYNC_S + 1
|
||||||
mon._sync_open_tickets()
|
mon._sync_open_tickets()
|
||||||
assert mon.tickets.open_tickets.call_count == 2
|
assert mon.tickets.open_tickets.call_count == 2
|
||||||
|
|
||||||
|
|
||||||
|
class TestWanQualityCollection:
|
||||||
|
def test_stores_the_timeline(self, mon, db):
|
||||||
|
mon.unifi = MagicMock()
|
||||||
|
mon.unifi.get_wan_dashboard.return_value = {'wan_history': {'wan_history_details': [
|
||||||
|
{'network_group': 'WAN', 'health_history': [{'timestamp': 1000, 'high_latency': True}]}]}}
|
||||||
|
mon._collect_wan_quality()
|
||||||
|
key, value = db.set_state.call_args.args
|
||||||
|
assert key == 'wan_quality'
|
||||||
|
assert value['periods'] == [{'ts': 1.0, 'state': 'latency'}]
|
||||||
|
|
||||||
|
def test_unavailable_keeps_the_last_copy(self, mon, db):
|
||||||
|
mon.unifi = MagicMock()
|
||||||
|
mon.unifi.get_wan_dashboard.return_value = None
|
||||||
|
mon._collect_wan_quality()
|
||||||
|
assert not db.set_state.called
|
||||||
|
|
||||||
|
def test_client_reads_the_day(self):
|
||||||
|
c = monitor.UnifiClient({'controller': 'https://udm.test', 'api_key': 'k'})
|
||||||
|
c.session.get = MagicMock(return_value=MagicMock(json=lambda: {'wan_history': {}}))
|
||||||
|
assert c.get_wan_dashboard() == {'wan_history': {}}
|
||||||
|
url = c.session.get.call_args.args[0]
|
||||||
|
assert url.endswith('/proxy/network/v2/api/site/default/aggregated-dashboard')
|
||||||
|
assert c.session.get.call_args.kwargs['params'] == {'historySeconds': 86400}
|
||||||
|
|
||||||
|
def test_client_error_is_none(self):
|
||||||
|
c = monitor.UnifiClient({'controller': 'https://udm.test', 'api_key': 'k'})
|
||||||
|
c.session.get = MagicMock(side_effect=RuntimeError('boom'))
|
||||||
|
assert c.get_wan_dashboard() is None
|
||||||
+1
-1
@@ -62,7 +62,7 @@ def link(text: str, url: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def port_text(switch: str, port_name: str, port: dict) -> str:
|
def port_text(switch: str, port_name: str, port: dict) -> str:
|
||||||
"""'8SFP-AGG port 7 "Large1": up at 10 Gbps, DAC'"""
|
"""'8SFP-AGG port 7 "compute-storage-02": up at 10 Gbps, DAC'"""
|
||||||
idx = port.get('port_idx')
|
idx = port.get('port_idx')
|
||||||
text = f'{switch} port {idx}' if idx is not None else f'{switch} {port_name}'
|
text = f'{switch} port {idx}' if idx is not None else f'{switch} {port_name}'
|
||||||
if port_name and idx is not None and port_name != f'Port {idx}':
|
if port_name and idx is not None and port_name != f'Port {idx}':
|
||||||
|
|||||||
+2
-2
@@ -25,7 +25,7 @@ _TOKEN_RE = re.compile(r'[a-z0-9]+')
|
|||||||
|
|
||||||
|
|
||||||
def _norm(name: str) -> str:
|
def _norm(name: str) -> str:
|
||||||
"""A name with case, spaces, dashes and underscores ignored: "Large1" == "large-1"."""
|
"""A name with case, spaces, dashes and underscores ignored: "Storage-01" == "storage_01"."""
|
||||||
return ''.join(_TOKEN_RE.findall((name or '').lower()))
|
return ''.join(_TOKEN_RE.findall((name or '').lower()))
|
||||||
|
|
||||||
|
|
||||||
@@ -114,7 +114,7 @@ def name_mismatch(port_name: str, neighbour: str, own: str, known: Dict[str, str
|
|||||||
"""A port named after a different device than the one plugged into it.
|
"""A port named after a different device than the one plugged into it.
|
||||||
|
|
||||||
known: {normalised name: display name} of every device. Runs of up to four words of
|
known: {normalised name: display name} of every device. Runs of up to four words of
|
||||||
the port name are compared with them, so "Large1 Management" names large1 and
|
the port name are compared with them, so "Storage-01 Management" names storage-01 and
|
||||||
"Downlink to 24RJ45-POE" names 24RJ45-POE. Ports named only "Port 4" never match.
|
"Downlink to 24RJ45-POE" names 24RJ45-POE. Ports named only "Port 4" never match.
|
||||||
"""
|
"""
|
||||||
if not port_name or _is_generic_port_name(port_name):
|
if not port_name or _is_generic_port_name(port_name):
|
||||||
|
|||||||
Reference in new issue
Block a user