diff --git a/README.md b/README.md index a4b68a0..4c1b6e5 100644 --- a/README.md +++ b/README.md @@ -430,6 +430,7 @@ swap or recabling. | Proxmox host NIC link-down regression (≥2 consecutive checks) | P2 High | | Host unreachable via ping (≥`host_failure_threshold` consecutive checks) | P2 High | | Configured host has no metrics in Prometheus (host or `node_exporter` down, ≥`host_failure_threshold` consecutive checks) | P2 High | +| Planned reboot did not come back: the host logged a shutdown request but has sent no metrics for `planned_reboot_grace` (see below) | P2 High | | Prometheus unavailable, so host and interface alerting is paused (≥2 consecutive checks) | P2 High | | ≥`cluster_threshold` hosts failing at once, with network evidence, for ≥2 consecutive checks (see below) | P1 Critical | | WAN down: broadband or optical status not Up, or PON not in O5 (≥`modem.failure_threshold`) | P1 Critical | @@ -456,6 +457,26 @@ A failed Pulse ping check counts as "unknown": it neither raises nor resolves `h - **No evidence:** if the failing hosts' switch links all stayed up, Gandalf records a `cluster_hosts_stalled` warning with no ticket. The warning reads "not a network fault", names any host with recent OOM kills (`node_vmstat_oom_kill`), and leaves host health to hwmonDaemon. - **Flapping links:** a NIC that drops `3` or more times within an hour is flapping. It keeps one open `interface_down` alert, which closes once it has been stable for an hour, and doesn't count toward the cluster check. Mark a dead NIC unused to silence it entirely. + +### Planned reboots (gandalf#47) +When a configured host stops reporting to Prometheus, Gandalf asks Loki (`loki.url`) whether that +host's `systemd-logind` logged a shutdown request (`The system will reboot now!`, `power off now!`) +just before it went quiet. That line is written when someone runs `reboot`, `shutdown` or a Proxmox +host reboot, about ten seconds before node_exporter stops. A crash, watchdog reset or power loss +writes nothing of the kind. + +- **Shutdown requested:** the host shows as **rebooting (planned)** in Needs attention and as an + info-level `host_rebooting` event, not as an outage, and it doesn't count toward the cluster check. + If it has not come back `planned_reboot_grace` after the shutdown (default 20 minutes, per host + with `planned_reboot_grace_hosts`), Gandalf opens a P2 "Planned reboot did not come back" ticket. +- **No shutdown line:** alerted exactly as before, on `host_failure_threshold`. +- **Loki unreachable or not configured:** alerted exactly as before. A failed log query never + delays or silences an alert. + +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. ### What a ticket contains Tickets are Markdown. Besides the alert's own facts and a numbered "What to check" list, each one adds @@ -636,6 +657,9 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/ "prometheus": { "url": "http://10.10.10.48:9090" }, + "loki": { + "url": "http://10.10.10.69:3100" + }, "unifi": { "controller": "https://10.10.10.1", "api_key": "...", @@ -670,6 +694,8 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/ "poll_interval": 120, "failure_threshold": 2, "host_failure_threshold": 5, + "planned_reboot_grace": 1200, + "planned_reboot_grace_hosts": { "storage-01": 1800 }, "unifi_failure_threshold": 5, "cluster_threshold": 3, "ping_hosts": [ @@ -692,6 +718,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/ |---|---| | `database.*` | MariaDB credentials (LXC 149 at 10.10.10.50) | | `prometheus.url` | Prometheus base URL | +| `loki.url` | Loki base URL (optional), e.g. `http://10.10.10.69:3100`: tells planned reboots from crashes (see Planned reboots) | | `unifi.controller` | UniFi controller base URL (HTTPS, self-signed cert ignored) | | `unifi.api_key` | UniFi API key from controller Settings → API | | `unifi.site_id` | UniFi site ID (default: `default`) | @@ -713,6 +740,8 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/ | `monitor.poll_interval` | Seconds between full check cycles (default: 120) | | `monitor.failure_threshold` | Consecutive failures before creating ticket (default: 2) | | `monitor.host_failure_threshold` | Consecutive failures before ticketing a host that has disappeared, whether it has no metrics or doesn't answer ping (default: 5). A normal reboot takes about 3-5 minutes, so the default rides it out: the host still shows as down on the dashboard, but a ticket opens only after about 8 minutes at the default poll interval. For longer maintenance, suppress the host first. | +| `monitor.planned_reboot_grace` | Seconds a host that logged a shutdown request may stay away before a "Planned reboot did not come back" ticket (default: 1200). Measured from the shutdown line, not from when Gandalf noticed. | +| `monitor.planned_reboot_grace_hosts` | Per-host overrides of `planned_reboot_grace`, e.g. `{"storage-01": 1800}` for a slow-booting Ceph node. | | `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) | diff --git a/attention.py b/attention.py index da2feb7..52c5153 100644 --- a/attention.py +++ b/attention.py @@ -6,6 +6,7 @@ where it is fixed. Pure functions, so the rules are easy to test. """ import time from typing import Dict, List, Optional +from urllib.parse import quote import modem @@ -33,6 +34,13 @@ def _alerts(events: List[dict]) -> List[dict]: return [_entry('broken', 'bad' if critical else 'warn', text, '#events-table-wrap', shown)] +def _rebooting(events: List[dict]) -> List[dict]: + """Hosts in a planned reboot (gandalf#47): shown so a missing host isn't read as an outage.""" + return [_entry('broken', 'info', f'{e["target_name"]} is rebooting (planned)', + f'/device/{quote(str(e["target_name"]), safe="")}', e.get('description') or '') + for e in events if e.get('event_type') == 'host_rebooting' and not e.get('resolved_at')] + + def _power(power: List[dict]) -> List[dict]: out = [] for src in power or []: @@ -217,7 +225,7 @@ def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict], """ now = time.time() if now is None else now entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks) - + _smart_power(modem_restart) + _alerts(events) + _power(power)) + + _smart_power(modem_restart) + _alerts(events) + _rebooting(events) + _power(power)) if cutsheet_view is not None: entries += _cutsheet(cutsheet_view) entries += _rack(rack_issues or {}) diff --git a/monitor.py b/monitor.py index 41931c1..d51ee57 100644 --- a/monitor.py +++ b/monitor.py @@ -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. diff --git a/reboots.py b/reboots.py new file mode 100644 index 0000000..3d78f35 --- /dev/null +++ b/reboots.py @@ -0,0 +1,84 @@ +"""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) diff --git a/tests/test_attention.py b/tests/test_attention.py index bbd21df..4101575 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -29,6 +29,21 @@ class TestAlerts: assert line['severity'] == 'warn' and line['text'] == '1 active alert' +class TestPlannedReboot: + def test_rebooting_host_is_one_info_line_linking_to_it(self): + ev = _alert('monitor-01', 'info', event_type='host_rebooting', + description='Planned reboot: monitor-01 rebooted on request at 2026-11-06 23:17:49 UTC') + [line] = attention.build([ev], [], None)['broken'] + assert line['text'] == 'monitor-01 is rebooting (planned)' + assert line['severity'] == 'info' and line['href'] == '/device/monitor-01' + assert line['detail'].startswith('Planned reboot') + + def test_it_ranks_below_real_alerts(self): + ev = _alert('monitor-01', 'info', event_type='host_rebooting') + out = attention.build([ev, _alert('pbs')], [], None)['broken'] + assert [x['severity'] for x in out] == ['bad', 'info'] + + class TestPower: def test_frozen_readings_and_an_off_outlet_feeding_a_device(self): power = [{'node': 'RPDU', 'stale_since': '2026-11-15 05:26:54 UTC', diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 9009375..72c5abc 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -138,6 +138,110 @@ class TestDeadHostDetection: assert snap['hosts']['beta']['status'] == 'down' +class _Loki: + """Stands in for reboots.LokiClient: returns the given journal lines, or fails.""" + def __init__(self, lines=(), error=None): + self._lines, self._error, self.calls = list(lines), error, 0 + + def lines(self, logql, start, end, limit=20): + self.calls += 1 + if self._error: + raise monitor.reboots.LokiError(self._error) + return [(ts, line) for ts, line in self._lines if start <= ts <= end] + + +class TestPlannedReboot: + """gandalf#47: a host that logged a shutdown request is rebooting, not down.""" + + def _types(self, db): + return [u[0] for u in upserted(db)] + + def test_planned_reboot_is_shown_as_one_with_no_ticket(self, mon, db): + mon.loki = _Loki([(time.time() - 60, 'The system will reboot now!')]) + db.upsert_event.return_value = (1, False, 5, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert ('host_rebooting', 'beta', HOST_B) in upserted(db) + assert 'host_metrics_missing' not in self._types(db) + db.resolve_event.assert_any_call('host_metrics_missing', 'beta', HOST_B) + assert not mon.tickets.create.called + msg = next(c.args[5] for c in db.upsert_event.call_args_list if c.args[0] == 'host_rebooting') + assert msg.startswith('Planned reboot: beta rebooted on request') and 'up to 20 min' in msg + + def test_planned_reboots_are_not_a_cluster_failure(self, mon, db): + # 2026-11-25: two hosts powered off on request at the same moment + mon._instance_map[HOST_C] = 'gamma' + mon.loki = _Loki([(time.time() - 30, 'The system will power off now!')]) + mon._process_interfaces({'10.9.9.9:9100': {'eth0': True}}, []) + assert 'cluster_network_issue' not in self._types(db) + assert 'cluster_hosts_stalled' not in self._types(db) + + def test_answer_is_remembered_until_the_host_returns(self, mon, db): + mon.loki = _Loki([(time.time() - 60, 'The system will reboot now!')]) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert mon.loki.calls == 1 + mon._process_interfaces({HOST_A: {'eth0': True}, HOST_B: {'eth0': True}}, []) + db.resolve_event.assert_any_call('host_rebooting', 'beta', HOST_B) + assert 'beta' not in mon._shutdowns and 'beta' not in mon._missing_since + + @staticmethod + def _found(minutes_ago): + # A shutdown seen early in the reboot, remembered while the host stays away + return {'beta': {'at': time.time() - minutes_ago * 60, 'kind': 'reboot', + 'line': 'The system will reboot now!'}} + + def test_reboot_that_outlasts_its_grace_tickets_at_once(self, mon, db): + mon.loki = _Loki() + mon._shutdowns = self._found(25) + db.upsert_event.return_value = (1, False, 1, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + db.resolve_event.assert_any_call('host_rebooting', 'beta', HOST_B) + msg = next(c.args[5] for c in db.upsert_event.call_args_list if c.args[0] == 'host_metrics_missing') + assert msg.startswith('Planned reboot of beta did not come back') + assert 'Planned reboot did not come back' in mon.tickets.create.call_args.args[0] + + def test_per_host_grace(self, mon, db): + mon.cfg = {'monitor': {'planned_reboot_grace_hosts': {'beta': 1800}}} + mon.loki = _Loki() + mon._shutdowns = self._found(25) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert ('host_rebooting', 'beta', HOST_B) in upserted(db) + assert not mon.tickets.create.called + + def test_crash_alerts_as_before(self, mon, db): + # compute-storage-02 2026-11-21: gone with no shutdown line + mon.loki = _Loki([]) + db.upsert_event.return_value = (1, False, 5, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert 'No metrics from host' in mon.tickets.create.call_args.args[0] + assert 'host_rebooting' not in self._types(db) + + def test_loki_down_never_delays_or_silences(self, mon, db): + mon.loki = _Loki(error='connection refused') + db.upsert_event.return_value = (1, False, 5, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert 'No metrics from host' in mon.tickets.create.call_args.args[0] + + def test_found_after_a_monitor_restart_mid_reboot(self, mon, db): + # The monitor restarted 1 min ago; the host went down on request 12 min ago + mon.loki = _Loki([(time.time() - 12 * 60, 'The system will reboot now!')]) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert ('host_rebooting', 'beta', HOST_B) in upserted(db) + + def test_stops_asking_once_a_normal_reboot_would_be_over(self, mon, db): + mon.loki = _Loki([(time.time() - 30 * 60, 'The system will reboot now!')]) + mon._missing_since = {'beta': time.time() - 11 * 60} + db.upsert_event.return_value = (1, False, 6, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert mon.loki.calls == 0 + assert 'No metrics from host' in mon.tickets.create.call_args.args[0] + + def test_without_loki_configured_nothing_changes(self, mon, db): + db.upsert_event.return_value = (1, False, 5, None) + mon._process_interfaces({HOST_A: {'eth0': True}}, []) + assert 'No metrics from host' in mon.tickets.create.call_args.args[0] + + HOST_C = '10.0.0.3:9100' diff --git a/tests/test_reboots.py b/tests/test_reboots.py new file mode 100644 index 0000000..8e3035c --- /dev/null +++ b/tests/test_reboots.py @@ -0,0 +1,90 @@ +"""Tests for reboots.py: telling a planned reboot from a crash using the journal in Loki.""" +import os +import sys +from unittest.mock import MagicMock, patch + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) + +import reboots # noqa: E402 + +NOW = 1_794_007_200.0 # 2026-11-06 23:20 UTC, during monitor-01's planned reboot + + +class FakeLoki: + def __init__(self, lines=None, error=None): + self._lines, self._error, self.calls = lines or [], error, [] + + def lines(self, logql, start, end, limit=20): + self.calls.append((logql, start, end)) + if self._error: + raise reboots.LokiError(self._error) + return [(ts, line) for ts, line in self._lines if start <= ts <= end] + + +class TestFindShutdown: + def test_planned_reboot_line(self): + # monitor-01 2026-11-06: logind logged this ~10s before node_exporter stopped + loki = FakeLoki([(NOW - 131, 'The system will reboot now!')]) + found = reboots.find_shutdown(loki, 'monitor-01', 120, NOW) + assert found['kind'] == 'reboot' and found['at'] == NOW - 131 + assert 'host="monitor-01"' in loki.calls[0][0] and 'systemd-logind.service' in loki.calls[0][0] + + def test_power_off_counts(self): + loki = FakeLoki([(NOW - 60, 'The system will power off now!')]) + assert reboots.find_shutdown(loki, 'compute-storage-01', 120, NOW)['kind'] == 'power off' + + def test_crash_has_no_line(self): + # compute-storage-02 2026-11-21: the journal just stops, nothing from logind + assert reboots.find_shutdown(FakeLoki([]), 'compute-storage-02', 120, NOW) is None + + def test_an_old_shutdown_is_not_this_one(self): + loki = FakeLoki([(NOW - 3 * 3600, 'The system will reboot now!')]) + assert reboots.find_shutdown(loki, 'monitor-01', 120, NOW) is None + + def test_window_covers_the_whole_outage_plus_lookback(self): + loki = FakeLoki([]) + reboots.find_shutdown(loki, 'pbs', 600, NOW) + _, start, end = loki.calls[0] + assert end == NOW and start == NOW - 600 - reboots.LOOKBACK_S + + def test_loki_failure_is_raised_not_hidden(self): + with pytest.raises(reboots.LokiError): + reboots.find_shutdown(FakeLoki(error='timeout'), 'pbs', 120, NOW) + + def test_host_name_is_quoted(self): + assert 'host="a\\"b"' in reboots.shutdown_query('a"b') + + +class TestLokiClient: + def test_parses_streams_newest_first(self): + resp = MagicMock() + resp.json.return_value = {'status': 'success', 'data': {'result': [ + {'stream': {'host': 'x'}, 'values': [['1794007069971036000', 'The system will reboot now!'], + ['1794007000000000000', 'older']]}]}} + with patch.object(reboots.requests, 'get', return_value=resp) as get: + out = reboots.LokiClient('http://loki:3100/').lines('{q}', 1, 2) + assert out[0] == (1794007069.971036, 'The system will reboot now!') and len(out) == 2 + assert get.call_args.args[0] == 'http://loki:3100/loki/api/v1/query_range' + assert get.call_args.kwargs['params']['start'] == '1000000000' + + def test_http_error_is_a_loki_error(self): + with patch.object(reboots.requests, 'get', side_effect=OSError('refused')): + with pytest.raises(reboots.LokiError): + reboots.LokiClient('http://loki:3100').lines('{q}', 1, 2) + + def test_unsuccessful_status_is_a_loki_error(self): + resp = MagicMock() + resp.json.return_value = {'status': 'error', 'error': 'query too long'} + with patch.object(reboots.requests, 'get', return_value=resp): + with pytest.raises(reboots.LokiError): + reboots.LokiClient('http://loki:3100').lines('{q}', 1, 2) + + +class TestGrace: + def test_default_global_and_per_host(self): + assert reboots.grace_for('pbs', {}) == reboots.DEFAULT_GRACE_S + assert reboots.grace_for('pbs', {'planned_reboot_grace': 900}) == 900 + cfg = {'planned_reboot_grace': 900, 'planned_reboot_grace_hosts': {'storage-01': 2400}} + assert reboots.grace_for('storage-01', cfg) == 2400 and reboots.grace_for('pbs', cfg) == 900