diff --git a/README.md b/README.md index 2b28ecd..9260e9c 100644 --- a/README.md +++ b/README.md @@ -478,6 +478,23 @@ Loki is asked once per check while the host could still be in an ordinary reboot (`host_failure_threshold` checks), and the answer is kept until the host returns. Telling a crash that recovers inside the window from a planned reboot (an "unexpected reboot" alert) is host health, so it belongs to thor, not Gandalf. +### Gateway reachability from each host (gandalf#66 item 7) + +Every check, the SSH session Gandalf already opens on each host (through Pulse, for ethtool) also +pings each gateway in `monitor.reachability` 3 times (0.2 s apart, about 0.4 s per gateway), e.g. `{"management": "10.10.10.1", "ceph": "10.10.90.1"}`. +This took over hwmonDaemon's "Management network is unreachable" and "Ceph network is unreachable" +(network is Gandalf's to ticket; hwmonDaemon's `NETWORK_ENABLED` switch turns its version off). + +- **Alert:** all 3 pings lost raises `network_unreachable` (target the host, detail the network). Partial + loss doesn't. A host whose SSH collection failed has no result that check, so nothing changes for it. +- **Ticket:** after `failure_threshold` checks in a row, a P2. hwmonDaemon pinged once and ticketed on a + single miss. + - One host: `host::ceph_net_unreachable` (or `mgmt_` for management), the same keys hwmonDaemon + used, so its open tickets carry on instead of being duplicated. + - Several hosts in the same check: one cluster-wide ticket listing them all + (`cluster:_net:unreachable`), since the switch, VLAN or router is the likely cause. +- The result per host is kept in `link_stats.reachability`. + ### What a ticket contains Tickets are Markdown. Besides the alert's own facts and a numbered "What to check" list, each one adds @@ -855,6 +872,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/ | `monitor.unifi_failure_threshold` | Consecutive failures before ticketing a UniFi device as offline (default: same as `failure_threshold`). Set higher than `failure_threshold`: UniFi switches/APs can take several minutes to rejoin after a firmware-update reboot, so a low threshold cuts tickets for momentary maintenance reboots instead of real failures. | | `monitor.cluster_threshold` | Hosts failing at once (with network evidence, see Alert Logic) to trigger the cluster-wide P1 (default: 3) | | `monitor.ping_hosts` | Hosts checked only by ping (no node_exporter) | +| `monitor.reachability` | `{network: gateway IPv4}` pinged from each host every check (see Gateway reachability); empty or absent turns it off | | `monitor.stale_alert_days` | Days an alert can stay active before the dashboard flags it as stale (default: 3) | | `monitor.stale_ticket_hours` | Hours a ticket can stay open after all its alerts cleared before it is listed under Needs Follow-up (default: 24) | | `cutsheet.mismatch_ticket_hours` | Hours a cutsheet mismatch must last before it opens a P4 ticket (default: 24; `0` never tickets). The mismatch shows on the dashboard and the switch's page straight away, so recabling never pages anyone. Suppressing the switch or its port also stops the ticket. | diff --git a/monitor.py b/monitor.py index f7adec0..e6a4630 100644 --- a/monitor.py +++ b/monitor.py @@ -7,6 +7,7 @@ are detected, with deduplication and suppression support. Run as a separate systemd service alongside the Flask web app. """ +import ipaddress import json import logging import re @@ -822,6 +823,9 @@ class LinkStatsCollector: f' ethtool -m {q} 2>/dev/null;' f' echo "___END___"' ) + # Gateways to ping from the host itself (gandalf#66 item 7): monitor.reachability + for name, ip in self._reachability_targets(): + parts.append(f'echo "___PING:{name}___"; ping -c 3 -i 0.2 -W 1 -q {ip} 2>&1; echo "___END___"') shell_cmd = ' '.join(parts) ssh_cmd = ( @@ -837,8 +841,33 @@ class LinkStatsCollector: return self._parse_ssh_output(output) + def _reachability_targets(self) -> List[tuple]: + """[(name, ip)] from monitor.reachability, keeping only safe names and valid IPv4 addresses.""" + out = [] + for name, ip in sorted(((self.cfg.get('monitor') or {}).get('reachability') or {}).items()): + try: + ok = re.match(r'^[a-z0-9_-]{1,32}$', str(name)) and ipaddress.ip_address(str(ip)).version == 4 + except ValueError: + ok = False + if ok: + out.append((str(name), str(ip))) + else: + logger.warning(f'Ignoring monitor.reachability entry {name!r}: {ip!r}') + return out + + @staticmethod + def parse_ping_summary(text: str) -> Optional[dict]: + """{'sent', 'received', 'loss_pct'} from ping -q output, or None if it has no summary.""" + m = re.search(r'(\d+) packets transmitted, (\d+) (?:packets )?received', text) + if not m: + return None + sent, received = int(m.group(1)), int(m.group(2)) + loss = round(100 * (sent - received) / sent) if sent else 100 + return {'sent': sent, 'received': received, 'loss_pct': loss} + @staticmethod def _parse_ssh_output(output: str) -> Dict[str, dict]: + """{iface: {...}} from the ethtool sections, plus '__reach__': {name: ping summary}.""" result: Dict[str, dict] = {} current_iface: Optional[str] = None current_section: Optional[str] = None @@ -856,6 +885,10 @@ class LinkStatsCollector: sfp = LinkStatsCollector._parse_ethtool_m(text) if sfp: result.setdefault(iface, {})['sfp'] = sfp + elif section == 'ping': + summary = LinkStatsCollector.parse_ping_summary(text) + if summary: + result.setdefault('__reach__', {})[iface] = summary for line in output.splitlines(): if line.startswith('___IFACE:') and line.endswith('___'): @@ -868,6 +901,11 @@ class LinkStatsCollector: current_iface = line[7:-3] current_section = 'dom' buf = [] + elif line.startswith('___PING:') and line.endswith('___'): + flush(current_iface, current_section, buf) + current_iface = line[8:-3] + current_section = 'ping' + buf = [] elif line == '___END___': flush(current_iface, current_section, buf) current_iface = None @@ -1016,6 +1054,7 @@ class LinkStatsCollector: """ prom_metrics = self._collect_prom_metrics() result_hosts: Dict[str, Dict[str, dict]] = {} + reachability: Dict[str, dict] = {} exclude_ips = set(self.cfg.get('monitor', {}).get('links_exclude_ips', [])) for instance, iface_metrics in prom_metrics.items(): @@ -1034,6 +1073,9 @@ class LinkStatsCollector: ethtool_data = self._ssh_batch(host_ip, ifaces) except Exception as e: logger.warning(f'ethtool collection failed for {host} ({host_ip}): {e}') + reach = ethtool_data.pop('__reach__', None) + if reach: + reachability[host] = reach # Merge Prometheus metrics + ethtool data per interface merged: Dict[str, dict] = {} @@ -1073,6 +1115,8 @@ class LinkStatsCollector: 'unifi_devices': unifi_devices, # Which host NIC owns each MAC, for matching outlets and neighbours named by MAC 'host_macs': {mac: list(owner) for mac, owner in host_macs.items()}, + # {host: {network: {sent, received, loss_pct}}}: gateways pinged from each host + 'reachability': reachability, 'updated': datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC'), } @@ -1915,6 +1959,74 @@ class NetworkMonitor: if (target_name, target_detail) not in current: db.resolve_event('cable_mismatch', target_name, target_detail) + # ------------------------------------------------------------------ + # Gateway reachability from each host (gandalf#66 item 7) + # ------------------------------------------------------------------ + def _process_reachability(self, link_data: dict, suppressions: list) -> None: + """Alert when a host can't reach a network's gateway (all pings lost), for fail_thresh cycles. + + Replaces hwmonDaemon's "Management/Ceph network is unreachable" (one ping, one miss). + Partial loss doesn't alert. A host whose SSH collection failed this cycle has no + result, so it neither alerts nor clears. When several hosts lose the same network in + one cycle, the cause is the switch or VLAN, so they share one ticket. + """ + targets = dict(self.link_stats._reachability_targets()) if getattr(self, 'link_stats', None) else {} + reach = link_data.get('reachability') or {} + due: Dict[str, list] = {} + for host, nets in reach.items(): + for name, r in (nets or {}).items(): + if r.get('received'): + db.resolve_event('network_unreachable', host, name) + continue + ip = targets.get(name, '') + event_id, _, consec, ticket_id = db.upsert_event( + 'network_unreachable', 'critical', 'ping', host, name, + f'{host} cannot reach the {name} network: {r.get("sent", 0)} pings to its gateway ' + f'{ip} all lost ({_now_utc()})', + ) + sup = (db.check_suppressed(suppressions, 'host', host) or + db.check_suppressed(suppressions, 'interface', host, name)) + if not sup and consec >= self.fail_thresh and not ticket_id: + due.setdefault(name, []).append((event_id, host, consec)) + for name, items in due.items(): + self._ticket_unreachable_network(name, targets.get(name, ''), items) + + def _ticket_unreachable_network(self, name: str, ip: str, items: list) -> None: + checks = [f'From an affected host, `ping {ip}` and `ip route get {ip}`: which interface does it leave by?', + f'Check that interface and its switch port below; for the {name} VLAN, check the switch port ' + 'carries the VLAN and the host bridge or VLAN interface is up.', + 'If several hosts are listed, check the switch or router that serves this network first.'] + if len(items) == 1: + event_id, host, consec = items[0] + self._open_ticket( + event_id, 'network_unreachable', host, name, + title=ticket_text.title(host, f'{name.capitalize()} network is unreachable'), + heading='Network Reachability Alert', + facts=[('Host', host), ('Network', name), ('Gateway', ip), ('Detected', _now_utc()), + ('Consecutive check failures', str(consec))], + summary=(f'{host} is up and answering Gandalf over SSH, but every ping from it to the {name} ' + f'gateway ({ip}) is lost, for {consec} checks in a row.'), + checks=checks, priority='2', host=host, + ) + return + hosts = sorted(h for _, h, _ in items) + first = items[0][0] + sections = [('Hosts', [f'- {h}' for h in hosts])] + desc = ticket_text.description( + 'Network Reachability Alert', + [('Network', name), ('Gateway', ip), ('Hosts affected', str(len(hosts))), ('Detected', _now_utc())], + f'{len(hosts)} hosts cannot reach the {name} gateway ({ip}) at the same time, so the cause is ' + f'most likely the switch, VLAN or router serving that network rather than the hosts.', + checks, sections) + tid = self.tickets.create( + ticket_text.title(self.cluster_name, f'{name.capitalize()} network is unreachable from {len(hosts)} hosts', + 'cluster-wide'), + desc, priority='2', dedup_key=ticket_text.network_down_key(name)) + if tid: + for event_id, _, _ in items: + db.set_ticket_id(event_id, tid) + logger.info(f'Ticket #{tid}: {name} network unreachable from {", ".join(hosts)} (event {first})') + def _ticket_cable_mismatch(self, event_id: int, p: dict, hours: float) -> None: url = ticket_text.cutsheet_url(self._base_url(), p['cable_id']) self._open_ticket( @@ -2817,6 +2929,13 @@ class NetworkMonitor: self._process_ping_hosts(suppressions, ping_states) + # Gateways pinged from each host (gandalf#66 item 7, taken over from hwmonDaemon) + if link_data is not None: + try: + self._process_reachability(link_data, suppressions) + except Exception as e: + logger.error(f'Gateway reachability check failed: {e}', exc_info=True) + # Cutsheet: compare documented cabling with what was just discovered if link_data is not None: try: diff --git a/tests/test_monitor.py b/tests/test_monitor.py index cb2cf39..fe2e19b 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -1909,3 +1909,103 @@ class TestTicketClientDedupKey: assert post.call_args.kwargs['json']['dedup_key'] == 'host:a:metrics_missing' c.create('u', 'd') assert 'dedup_key' not in post.call_args.kwargs['json'] + + +class TestGatewayReachability: + """gandalf#66 item 7: gateways pinged from each host, taken over from hwmonDaemon.""" + PING_OK = ('PING 10.10.90.1 (10.10.90.1) 56(84) bytes of data.\n\n--- 10.10.90.1 ping statistics ---\n' + '3 packets transmitted, 3 received, 0% packet loss, time 2003ms\n' + 'rtt min/avg/max/mdev = 0.2/0.3/0.4/0.1 ms') + PING_LOST = ('PING 10.10.90.1 (10.10.90.1) 56(84) bytes of data.\n\n--- 10.10.90.1 ping statistics ---\n' + '3 packets transmitted, 0 received, 100% packet loss, time 2050ms') + + def test_parse_ping_summary(self): + p = monitor.LinkStatsCollector.parse_ping_summary + assert p(self.PING_OK) == {'sent': 3, 'received': 3, 'loss_pct': 0} + assert p(self.PING_LOST) == {'sent': 3, 'received': 0, 'loss_pct': 100} + assert p('3 packets transmitted, 2 packets received, 33% packet loss') == \ + {'sent': 3, 'received': 2, 'loss_pct': 33} # busybox wording + assert p('ping: connect: Network is unreachable') is None + + def test_ssh_output_carries_ping_sections_apart_from_interfaces(self): + out = ('___IFACE:eno1___\nSpeed: 1000Mb/s\nLink detected: yes\n___DOM:eno1___\n___END___\n' + f'___PING:ceph___\n{self.PING_LOST}\n___END___\n___PING:management___\n{self.PING_OK}\n___END___\n') + parsed = monitor.LinkStatsCollector._parse_ssh_output(out) + assert parsed['__reach__'] == {'ceph': {'sent': 3, 'received': 0, 'loss_pct': 100}, + 'management': {'sent': 3, 'received': 3, 'loss_pct': 0}} + assert parsed['eno1']['speed_mbps'] == 1000 + + def _collector(self, reach): + c = monitor.LinkStatsCollector.__new__(monitor.LinkStatsCollector) + c.cfg = {'monitor': {'reachability': reach}} + return c + + def test_targets_keep_only_safe_names_and_ipv4(self): + c = self._collector({'ceph': '10.10.90.1', 'management': '10.10.10.1', 'Bad Name': '10.0.0.1', + 'evil': '10.0.0.1; rm -rf /', 'v6': '::1'}) + assert c._reachability_targets() == [('ceph', '10.10.90.1'), ('management', '10.10.10.1')] + + def test_ssh_command_pings_each_gateway(self): + c = self._collector({'ceph': '10.10.90.1'}) + c.pulse = MagicMock(url='http://pulse.test') + c.pulse.run_command.return_value = '' + c._ssh_batch('10.0.0.1', ['eno1']) + cmd = c.pulse.run_command.call_args.args[0] + assert 'ping -c 3 -i 0.2 -W 1 -q 10.10.90.1' in cmd and '___PING:ceph___' in cmd + + def _mon(self, mon): + mon.link_stats = self._collector({'ceph': '10.10.90.1', 'management': '10.10.10.1'}) + mon.public_url = 'https://gandalf.test' + mon.poll_interval = 120 + mon._link_data = {'unifi_switches': {}} + return mon + + LOST = {'sent': 3, 'received': 0, 'loss_pct': 100} + OK = {'sent': 3, 'received': 3, 'loss_pct': 0} + + def test_one_host_gets_a_ticket_with_hwmondaemons_key(self, mon, db): + m = self._mon(mon) + m._process_reachability({'reachability': {'alpha': {'ceph': self.LOST, 'management': self.OK}}}, []) + assert ('network_unreachable', 'alpha', 'ceph') in upserted(db) + db.resolve_event.assert_any_call('network_unreachable', 'alpha', 'management') + title = m.tickets.create.call_args.args[0] + assert title.startswith('[alpha][auto][gandalf][network] Ceph network is unreachable') + assert m.tickets.create.call_args.kwargs['dedup_key'] == 'host:alpha:ceph_net_unreachable' + + def test_management_uses_hwmondaemons_mgmt_key(self): + assert monitor.ticket_text.dedup_key('network_unreachable', 'alpha', 'management') == \ + 'host:alpha:mgmt_net_unreachable' + + def test_several_hosts_share_one_ticket(self, mon, db): + m = self._mon(mon) + ids = iter(range(1, 10)) + db.upsert_event.side_effect = lambda *a, **k: (next(ids), False, 2, None) + m._process_reachability({'reachability': {'alpha': {'ceph': self.LOST}, 'beta': {'ceph': self.LOST}}}, []) + assert m.tickets.create.call_count == 1 + title, desc = m.tickets.create.call_args.args[:2] + assert 'Ceph network is unreachable from 2 hosts' in title and '[cluster-wide]' in title + assert '- alpha' in desc and '- beta' in desc + assert m.tickets.create.call_args.kwargs['dedup_key'] == 'cluster:ceph_net:unreachable' + assert sorted(c.args[0] for c in db.set_ticket_id.call_args_list) == [1, 2] + + def test_partial_loss_and_first_failure_open_nothing(self, mon, db): + m = self._mon(mon) + partial = {'sent': 3, 'received': 1, 'loss_pct': 67} + m._process_reachability({'reachability': {'alpha': {'ceph': partial}}}, []) + assert upserted(db) == [] + db.upsert_event.return_value = (1, True, 1, None) # first failed check + m._process_reachability({'reachability': {'alpha': {'ceph': self.LOST}}}, []) + m.tickets.create.assert_not_called() + + def test_suppressed_or_already_ticketed_opens_nothing(self, mon, db): + m = self._mon(mon) + db.check_suppressed.return_value = True + m._process_reachability({'reachability': {'alpha': {'ceph': self.LOST}}}, []) + db.check_suppressed.return_value = False + db.upsert_event.return_value = (1, False, 5, '999') + m._process_reachability({'reachability': {'alpha': {'ceph': self.LOST}}}, []) + m.tickets.create.assert_not_called() + + def test_no_result_for_a_host_neither_alerts_nor_clears(self, mon, db): + self._mon(mon)._process_reachability({'reachability': {}}, []) + assert upserted(db) == [] and not db.resolve_event.called diff --git a/ticket_text.py b/ticket_text.py index 1bc721e..25782ef 100644 --- a/ticket_text.py +++ b/ticket_text.py @@ -50,10 +50,22 @@ def _key_part(text) -> str: return _KEY_BAD.sub('-', str(text or '').strip().lower()).strip('-') +def _net_key(name: str) -> str: + return {'management': 'mgmt'}.get(name, name) + + +def network_down_key(network: str) -> str: + """Key for one ticket covering several hosts that lost the same network at once.""" + return f'cluster:{_net_key(_key_part(network))}_net:unreachable'[:128] + + def dedup_key(event_type: str, target: str, detail: str = '') -> Optional[str]: """Tinker's dedup_key for an event, or None for a type without one (Tinker then hashes the title, as before). Format ^[a-z0-9_.:-]{1,128}$.""" t, d = _key_part(target), _key_part(detail) + if event_type == 'network_unreachable': + # hwmonDaemon's keys, so its open tickets carry on (gandalf#66 item 7) + return f'host:{t}:{_net_key(d)}_net_unreachable'[:128] if event_type in WAN_EVENTS: key = f'site:wan:{event_type}' + (f':{d}' if d else '') elif event_type in _DEDUP_KEYS: