"""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)