Files
gandalf/reboots.py
T
jaredandClaude Opus 5.5 1db932f10e
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
Host down: tell a planned reboot from a crash using the journal in Loki
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>
2026-11-25 14:28:17 -05:00

85 lines
3.4 KiB
Python

"""Tell a planned host reboot from a host that has just died (gandalf#47).
When a host stops reporting to Prometheus, its journal in Loki says whether someone asked
it to go down: systemd-logind logs "The system will reboot now!" (or "power off now!")
about ten seconds before node_exporter stops. A crash, a watchdog reset or a power loss
logs nothing of the kind.
This module only reads Loki. Kept free of Gandalf's database and ticketing so the check
can move to thor (the out-of-band health app) later without changes.
"""
import logging
import re
import time
from typing import Optional
import requests
logger = logging.getLogger('gandalf.reboots')
# What systemd-logind logs when a shutdown is requested (reboot, poweroff, halt, kexec)
SHUTDOWN_RE = re.compile(r'The system will (reboot|power off|halt|suspend|kexec) now')
LOGQL_FILTER = 'will (reboot|power off|halt|kexec) now'
# How far before a host went missing to look for its shutdown line
LOOKBACK_S = 600
DEFAULT_GRACE_S = 1200
class LokiError(Exception):
"""Loki could not answer. Callers fall back to treating the host as not planned."""
class LokiClient:
def __init__(self, url: str, timeout: float = 10):
self.url = url.rstrip('/')
self.timeout = timeout
def lines(self, logql: str, start: float, end: float, limit: int = 20) -> list:
"""[(unix seconds, line)] newest first. Raises LokiError when Loki can't answer."""
try:
resp = requests.get(
f'{self.url}/loki/api/v1/query_range',
params={'query': logql, 'start': f'{int(start * 1e9)}', 'end': f'{int(end * 1e9)}',
'limit': limit, 'direction': 'backward'},
timeout=self.timeout,
)
resp.raise_for_status()
data = resp.json()
except Exception as e:
raise LokiError(str(e)) from e
if data.get('status') != 'success':
raise LokiError(f'unsuccessful: {str(data)[:200]}')
out = []
for stream in data.get('data', {}).get('result', []):
for ts, line in stream.get('values', []):
out.append((int(ts) / 1e9, line))
return sorted(out, reverse=True)
def shutdown_query(host: str) -> str:
# Host names are config values, but quote them safely all the same
safe = host.replace('\\', '\\\\').replace('"', '\\"')
return f'{{host="{safe}", job="journal", unit="systemd-logind.service"}} |~ "{LOGQL_FILTER}"'
def find_shutdown(loki: LokiClient, host: str, missing_for_s: float,
now: Optional[float] = None) -> Optional[dict]:
"""The shutdown request a host logged just before it went missing, or None.
missing_for_s: how long the host has been gone; the search covers that plus LOOKBACK_S.
Raises LokiError when Loki can't answer, so "no line" is never confused with "no data".
"""
now = time.time() if now is None else now
start = now - missing_for_s - LOOKBACK_S
for ts, line in loki.lines(shutdown_query(host), start, now):
m = SHUTDOWN_RE.search(line)
if m:
return {'at': ts, 'kind': m.group(1), 'line': line.strip()}
return None
def grace_for(host: str, monitor_cfg: dict) -> int:
"""How long a planned reboot may take before it counts as not coming back."""
per_host = monitor_cfg.get('planned_reboot_grace_hosts') or {}
return int(per_host.get(host) or monitor_cfg.get('planned_reboot_grace') or DEFAULT_GRACE_S)