Host down: tell a planned reboot from a crash using the journal in Loki
Lint / JS (eslint) (push) Successful in 12s
Lint / Python (flake8) (push) Successful in 1m34s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m54s
Lint / JS (eslint) (pull_request) Successful in 37s
Security / Python Security (bandit) (pull_request) Successful in 2m36s
Test / Python Tests (pytest) (push) Successful in 2m17s
Lint / Python (flake8) (pull_request) Successful in 57s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Test / Python Tests (pytest) (pull_request) Successful in 1m16s

When a host stops reporting, ask Loki whether its systemd-logind logged a
shutdown request just before. If so, show it as "rebooting (planned)"
instead of an outage, keep it out of the cluster check, and ticket only if
it has not come back within planned_reboot_grace (default 20 min, per host
overrides) as "Planned reboot did not come back". No line, no Loki config,
or a Loki error: alert exactly as before.

Refs #47 (the "unexpected reboot" alert for crashes that recover goes to thor)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-25 14:28:17 -05:00
1 parent 16b8f763c4
commit 1db932f10e
7 files changed
+424 -6

No files matched your search

+93 -5
View File
@@ -26,6 +26,7 @@ import cutsheet
import devices
import kuma
import modem as modem_api
import reboots
import ticket_text
@@ -1134,6 +1135,10 @@ def _now_utc() -> str:
return datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
def _fmt_ts(ts: float) -> str:
return datetime.fromtimestamp(ts, timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
def _utcnow() -> datetime:
"""Naive UTC, to compare with database times."""
return datetime.now(timezone.utc).replace(tzinfo=None)
@@ -1189,6 +1194,9 @@ class NetworkMonitor:
# that has disappeared. A NIC going down on a running host stays on fail_thresh.
self.host_fail_thresh = mon.get('host_failure_threshold', 5)
self.cluster_thresh = mon.get('cluster_threshold', 3)
# Loki tells a planned reboot (logind logged a shutdown request) from a host that died
loki_url = (self.cfg.get('loki') or {}).get('url')
self.loki = reboots.LokiClient(loki_url) if loki_url else None
self.cluster_name = mon.get('cluster_name', CLUSTER_NAME)
# Optional WAN modem (AT&T BGW-series); see modem.py
@@ -1547,26 +1555,106 @@ class NetworkMonitor:
# A dead host doesn't report its interfaces as down: its series just
# disappear, so a configured host that's absent needs its own check.
missing_since = self.__dict__.setdefault('_missing_since', {})
for instance, host in self._instance_map.items():
if instance in states:
db.resolve_event('host_metrics_missing', host, instance)
db.resolve_event('host_rebooting', host, instance)
missing_since.pop(host, None)
self.__dict__.setdefault('_shutdowns', {}).pop(host, None)
continue
missing_since.setdefault(host, now)
sup = db.check_suppressed(suppressions, 'host', host)
shutdown = self._planned_shutdown(host, now - missing_since[host], now)
if shutdown and self._still_rebooting(host, instance, shutdown, now):
continue # within its grace: not an outage, and no evidence of anything
if shutdown:
db.resolve_event('host_rebooting', host, instance)
down_min = int((now - shutdown['at']) // 60)
description = (f'Planned reboot of {host} did not come back: it logged a shutdown at '
f'{_fmt_ts(shutdown["at"])} and has sent no metrics for {down_min} min')
else:
description = f'No metrics from {host} ({instance}): host or node_exporter is down ({_now_utc()})'
event_id, is_new, consec, ticket_id = db.upsert_event(
'host_metrics_missing', 'critical', 'prometheus',
host, instance,
f'No metrics from {host} ({instance}): host or node_exporter is down ({_now_utc()})',
'host_metrics_missing', 'critical', 'prometheus', host, instance, description,
)
if consec >= self.fail_thresh:
if consec >= self.fail_thresh or shutdown:
hosts_with_regression.append(host)
if not self._switch_links_up(host):
network_evidence.append(host)
if not sup and consec >= self.host_fail_thresh and not ticket_id:
if sup or ticket_id:
continue
if shutdown:
# Its grace already ran out, so there is nothing more to wait for
self._ticket_reboot_stuck(event_id, host, instance, shutdown)
elif consec >= self.host_fail_thresh:
self._ticket_metrics_missing(event_id, host, instance, consec)
db.set_baseline(new_baseline)
self._check_cluster(hosts_with_regression, network_evidence, suppressions)
def _planned_shutdown(self, host: str, missing_for: float, now: float) -> Optional[dict]:
"""The shutdown request a missing host logged in Loki, or None (gandalf#47).
Looked up while the host could still be within an ordinary reboot (host_fail_thresh
checks), then remembered until it comes back. When Loki can't answer, the host is
treated as not planned: a failed log query never delays or silences an alert.
"""
found = self.__dict__.setdefault('_shutdowns', {})
if host in found:
return found[host]
if not getattr(self, 'loki', None):
return None
window = self.host_fail_thresh * self._poll_seconds()
if missing_for > window:
return None # too late to call it planned: the normal alert is already under way
try:
shutdown = reboots.find_shutdown(self.loki, host, max(missing_for, window), now)
except reboots.LokiError as e:
logger.warning(f'Loki shutdown check for {host} failed, alerting as usual: {e}')
return None
if shutdown:
found[host] = shutdown
logger.info(f'{host} logged "{shutdown["line"]}" at {_fmt_ts(shutdown["at"])}: planned reboot')
return shutdown
def _still_rebooting(self, host: str, instance: str, shutdown: dict, now: float) -> bool:
"""Show a planned reboot as one while it is within its grace. False once the grace is over."""
grace = reboots.grace_for(host, self.cfg.get('monitor', {}))
if now - shutdown['at'] >= grace:
return False
# The first check may have counted it missing before Loki had the line: no ticket was
# opened (that takes host_fail_thresh checks), so the plain outage event just goes
db.resolve_event('host_metrics_missing', host, instance)
verb = {'power off': 'powered off', 'halt': 'halted'}.get(shutdown['kind'], 'rebooted')
db.upsert_event(
'host_rebooting', 'info', 'prometheus', host, instance,
f'Planned reboot: {host} {verb} on request at {_fmt_ts(shutdown["at"])}; '
f'Gandalf waits up to {grace // 60} min for it to come back before ticketing',
)
return True
def _ticket_reboot_stuck(self, event_id: int, host: str, instance: str, shutdown: dict) -> None:
grace = reboots.grace_for(host, self.cfg.get('monitor', {}))
self._open_ticket(
event_id, 'host_metrics_missing', host, instance,
title=f'[{host}][auto][production][issue][network][single-node] Planned reboot did not come back',
heading='Host Reboot Alert',
facts=[('Host', host), ('Prometheus instance', instance),
('Shutdown requested', f'{_fmt_ts(shutdown["at"])} ({shutdown["kind"]})'),
('Logged', f'`{shutdown["line"]}`'),
('Grace allowed', ticket_text.duration(grace)), ('Detected', _now_utc())],
summary=(f'{host} logged a requested {shutdown["kind"]} (systemd-logind), so this began as a '
f'planned reboot. It has sent no metrics for longer than the {grace // 60} min a '
f'planned reboot is given, so it may be stuck in firmware, POST or boot, or still '
f'powered off.'),
checks=[f'Open the console for {host} (IPMI, Proxmox, or a monitor): is it stuck at POST, '
'the boot menu, or an emergency shell?',
'If it was powered off on purpose, power it on, or suppress it in Gandalf.',
'If it is up, check `systemctl status prometheus-node-exporter` on the host.'],
priority='2', host=host,
)
def _check_cluster(self, failing: List[str], evidence: List[str], suppressions: list) -> None:
"""Ticket a cluster-wide network failure only with network evidence.