From f0b26f29af1fa0b90956211a8967e1a3e166cba8 Mon Sep 17 00:00:00 2001 From: Garrett Allen <98648590+Gerrrt@users.noreply.github.com> Date: Mon, 23 Nov 2026 05:30:52 +0000 Subject: [PATCH] fix(morpheus): alert when NUT loses the UPS and the syslog leaves' expiry; true up the audit's docs The repository side of the 2026-11-13 morpheus audit, apart from the firewall's own addresses and key-only sshd (#1503). - loki/rules/ups.rules.yaml: NutUpsDataStaleSustained (a stale period two minutes long) and NutUpsDataStaleFrequent (over twenty in an hour). The fortnight to 2026-11-23 had 1,363 periods, none over 5.2 s, at most nine an hour. Five behaviour tests. Neither sees a gap that lasts days, as the 2026-11-05 driver outage did, because syslogd folds repeats; so scripts/collect-nut-state.sh asks upsc on the firewall from make gateway-state, and NutUpsUnreadable pages after 30 minutes. - collect-cert-expiry.sh --file, for a client certificate with no handshake to read. make gateway-state reads the syslog listener's leaf and morpheus's pinned client leaf; SyslogTlsCertificateExpiringSoon warns at 30 days, and the console rules exclude syslog-*. - network.md: the undeclared Hicks SSH pass into smaug (ten passes), Skids' eighth reservation at .24, and the thirteen static ARP reservations. - hardware.md: check_versions.py does collect pfSense's release. - Changelog: the audit, and where each finding stood on 2026-11-23. Co-Authored-By: Claude Opus 5.5 --- Makefile | 11 ++ README.md | 6 +- docs/changelog.md | 37 ++++++ docs/hardware.md | 12 +- docs/network.md | 35 +++++- docs/observability.md | 15 ++- docs/runbooks/deploy-stack.md | 2 +- docs/runbooks/generate-certificates.md | 9 ++ docs/security.md | 2 +- scripts/README.md | 3 +- scripts/collect-cert-expiry.sh | 85 ++++++++++---- scripts/collect-nut-state.sh | 105 ++++++++++++++++++ scripts/self-tests.sh | 2 + stacks/observability/README.md | 4 +- .../observability/loki/rules/ups.rules.yaml | 80 +++++++++++++ stacks/observability/loki/tests/ups.test.yaml | 71 ++++++++++++ .../prometheus/rules/host.rules.yaml | 34 +++++- .../prometheus/rules/ups.rules.yaml | 27 +++++ .../prometheus/tests/cert-expiry.test.yaml | 46 ++++++++ .../prometheus/tests/ups.test.yaml | 46 ++++++++ 20 files changed, 588 insertions(+), 44 deletions(-) create mode 100755 scripts/collect-nut-state.sh create mode 100644 stacks/observability/loki/rules/ups.rules.yaml create mode 100644 stacks/observability/loki/tests/ups.test.yaml diff --git a/Makefile b/Makefile index 5086afb4e..c8130c749 100644 --- a/Makefile +++ b/Makefile @@ -470,6 +470,17 @@ gateway-state: ## Collect the firewall's view of its uplinks, DDNS record and GU @# it needs no new timer; a failure fails the job like any other. ./scripts/collect-cert-expiry.sh --ssh $(FW_USER)@$(FW_HOST) --host morpheus \ --probe pfsense-ui=morpheus=127.0.0.1:443 + @# + @# And the two syslog TLS leaves (#1049): the listener's, off its handshake + @# here, and morpheus's client leaf, from the copy the listener pins. Both + @# were issued for 825 days; the day either lapses, morpheus's logs stop. + ./scripts/collect-cert-expiry.sh --host syslog-tls \ + --probe syslog-listener=prometheus=10.0.99.20:6514 \ + --file syslog-client=morpheus=certificates/morpheus.matrix.elysium.pem + @# + @# And whether NUT on the firewall can read the UPS, asked the way a + @# secondary asks (#1656's eight days): NutUpsUnreadable reads it. + ./scripts/collect-nut-state.sh --ssh $(FW_USER)@$(FW_HOST) --host morpheus .PHONY: silence-state silence-state: ## Collect Alertmanager's silences as metrics (#575) diff --git a/README.md b/README.md index d22ac3da7..44f3b5864 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ documents for different readers. can't run an agent (firewall, switch, UPS, iLO). One agent config, deployed identically everywhere. [How](docs/architecture.md#observability-data-flow) - **Dashboards and alerting as code.** 8 provisioned dashboards, 156 panels, and - 182 alert rules — 161 metric-based in Prometheus, 21 log-based in Loki — sharing + 186 alert rules — 163 metric-based in Prometheus, 23 log-based in Loki — sharing one Alertmanager routing tree. No dashboard exists only in a database. - **Secrets encrypted in-repo with SOPS + age.** Per-device credentials, decrypted at deploy time into gitignored paths, with `git log` showing which @@ -207,9 +207,9 @@ inbound passes may still reach it. Data flow and the maintained Mermaid topology . ├── stacks/ │ ├── observability/ # the estate's stack on prometheus — ten services -│ │ ├── prometheus/ # config, file_sd targets, 161 alert rules +│ │ ├── prometheus/ # config, file_sd targets, 163 alert rules │ │ ├── alertmanager/ # routing and inhibition -│ │ ├── loki/ # single-binary config + 21 LogQL rules +│ │ ├── loki/ # single-binary config + 23 LogQL rules │ │ ├── alloy/ # the agent config directory, shipped to every host │ │ ├── snmp-exporter/ # generator.yaml is the source of truth │ │ └── grafana/ # provisioning + 8 dashboards diff --git a/docs/changelog.md b/docs/changelog.md index 61192a4b2..ae521be2e 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -45,6 +45,43 @@ docstring gives: it is a record, not a claim about now. [`shut-down-on-the-ups.md`](runbooks/shut-down-on-the-ups.md) §0.2 had sent the operator to *Configuration → UPS → General*, which does not have it. §3.8 and §6.5 send you back to 0.2, so the one fix corrects all three. +- **`morpheus` audited, read-only, on 2026-11-13, and re-read on 2026-11-23.** + Segmentation held: `make check-firewall` passed, NAT had one `rdr`, and the + VLANs, Hicks' passes, the resolver and Suricata matched the repository. Two + findings were worse than anything else, and + [#1503](https://github.com/Gerrrt/HomeLab/pull/1503) carries them: every + segment reached the admin UI and `sshd` on the firewall's WAN address, and + `sshd` accepted passwords. On 2026-11-23 both were still so on the box. The + rest, as they stood on 2026-11-23: + - **Fixed here.** `network.md` now declares the undeclared Hicks SSH pass + into `smaug` (the count is ten), the eighth Skids reservation at `.24`, + and the thirteen reservations `morpheus` pins in its ARP table. + `hardware.md` no longer says nothing collects pfSense's release: + `check_versions.py` does, from SNMP. + - **Alerts added.** NUT on `morpheus` marked the UPS's data stale 1,363 + times in the fortnight to 2026-11-23, never for more than 5.2 seconds and + never more than 9 times in an hour. Nothing watched it. + `NutUpsDataStaleSustained` and `NutUpsDataStaleFrequent`, in a new + `loki/rules/ups.rules.yaml`, fire when a gap lasts two minutes or an hour + has twenty. Neither sees a gap that lasts days, like the driver outage + above, so `NutUpsUnreadable` asks `upsc` on the firewall every 15 minutes + from `make gateway-state` (`scripts/collect-nut-state.sh`) and pages at + 30 minutes. The cause of the stale gaps is not found. The two syslog TLS + leaves, due 2029-01-09, had no expiry alert. `make gateway-state` now + reads them, morpheus's client leaf from the pinned file through a new + `--file` in `collect-cert-expiry.sh`, and + `SyslogTlsCertificateExpiringSoon` warns at 30 days. + - **Done elsewhere.** `trinity` subscribes to NUT + ([#1596](https://github.com/Gerrrt/HomeLab/pull/1596)). The `netstat` + left running on `em0` since 2026-11-07 is gone. + - **Left for the operator, on the box.** The dead *Allow SSH from Mac to + WSL* rule, whose two ends are both on Hicks, is still loaded. The 41 + pending package updates are still pending; the base system is current. + The GUI still serves pfSense's default self-signed certificate, due + 2027-04-16 and watched by `ManagementCertificateExpiringSoon`. A root + console session is still open on `ttyv0`. Two Hicks leases with no row + in `network.md`, one with an Amazon prefix, had expired by 2026-11-23, + so they were not identified. The NVMe read 61 °C, against 64 on the 13th. ## 2026-11-22 diff --git a/docs/hardware.md b/docs/hardware.md index 79fbbf2d5..69c4b95e0 100644 --- a/docs/hardware.md +++ b/docs/hardware.md @@ -305,10 +305,14 @@ hardware depends on — recorded as a USB NIC in four documents until 2026-09-09, when the box was read directly: `pciconf` shows it on a PCIe root port, and the only USB device is the Wi-Fi module's Bluetooth half. The table records the release line -only, as [`check_docs.py`](../scripts/check_docs.py) requires, and unlike the -Linux hosts nothing collects the running release from pfSense — so it is -written here with its date: **pfSense CE 2.9.0-RELEASE**, build -`20260817-1836`, from `/etc/version` on 2026-09-09. Restoring the config +only, as [`check_docs.py`](../scripts/check_docs.py) requires. The running +release is collected, but not into this table: the SNMP scrape carries +pfSense's `sysDescr`, and [`check_versions.py`](../scripts/check_versions.py) +compares it every Wednesday with the one prose claim of it, in +[`enable-suricata.md`](runbooks/enable-suricata.md). The build is not +collected, so it is written here with its date: **pfSense CE 2.9.0-RELEASE**, +build `20260817-1836`, from `/etc/version` on 2026-09-09 and the same on +2026-11-23. Restoring the config needs a release at least that new ([`restore-the-firewall.md`](runbooks/restore-the-firewall.md) §3). diff --git a/docs/network.md b/docs/network.md index eac730175..0e57a6198 100644 --- a/docs/network.md +++ b/docs/network.md @@ -183,6 +183,20 @@ truth for what a box actually does. [`swap-the-switch.md`](runbooks/swap-the-switch.md) does. - NTP comes from `10.7.7.1`. The default `admin` user is disabled. - DHCP disabled. +- **`morpheus` pins thirteen reservations in its ARP table, on every + segment but Skids and Degens.** Each is a Kea reservation with *Create a + static ARP table entry* set: `mjolnir`, `prometheus` and `oracle` on + Winterfell; `laptop-01`, `desktop-01`, `workstation-01`, `workstation-02`, + `laptop-02` and `desktop-02` on Hicks; `nibelheim`, `hyrule` and `mediatv` + on CasaBonita; and `shiva`'s iLO on ImaginationLAN. `arp -an` shows 21 + permanent entries, these thirteen and the firewall's own eight interface + addresses. Read on 2026-11-23 for the audit of 2026-11-13. Only `mediatv`'s + has a recorded reason, the wake across the VLAN (CasaBonita, below). The + cost of the others: a host whose NIC or MAC changes keeps its address in + DHCP and is still unreachable through the firewall until the reservation's + MAC is edited, because the pinned entry never ages out. Check this list + first when a replaced or re-imaged machine answers on its own segment and + nowhere else. > [!CAUTION] > Do not re-enable DHCP on this interface. It races the DHCP servers on every @@ -528,7 +542,13 @@ Televisions and consoles. Internet only. [#485](https://github.com/Gerrrt/HomeLab/issues/485)). It was created on 2026-10-03 by [`build-the-backup-guest.md`](runbooks/build-the-backup-guest.md) §4, directly above the same block. `golem` has mounted the share through - it, and `alexander` is refused. + it, and `alexander` is refused. **A tenth is in force, and no document + declared it until the audit of `morpheus` on 2026-11-13 found it:** an + SSH pass on Hicks' interface, `desktop-02` (`10.0.50.90`) → + `10.0.40.30:22`. It is host-scoped, so `make check-firewall`'s wholesale + question cannot see it, and no ADR or issue says why it was made. It is + listed here so this count is true. Removing it, or recording why it stays, + is the operator's decision. - **One more from Hicks is specified and not yet created.** `Allow 5800 to smaug`, Hicks → `10.0.40.30:5800`, is for MakeMKV's web GUI, the disc ripper that runs on `smaug` only while someone is ripping @@ -926,12 +946,13 @@ the least trusted. on ADR-0099's three rows since 2026-10-21. The HomePod rows are in force and reach the devices. Adding the HomePods in Home Assistant is a separate matter, waiting on pyatv. -- **Seven addresses here are reserved, all below the `.100–.200` pool:** +- **Eight addresses here are reserved, all below the `.100–.200` pool:** `bifrost` at `10.0.20.20` since 2026-09-28, the three eeros at `.11`–`.13` since 2026-10-20 - ([#1228](https://github.com/Gerrrt/HomeLab/issues/1228)), and three + ([#1228](https://github.com/Gerrrt/HomeLab/issues/1228)), three HomePods at `.21`–`.23` since 2026-10-21 - ([#1226](https://github.com/Gerrrt/HomeLab/issues/1226)). Every other + ([#1226](https://github.com/Gerrrt/HomeLab/issues/1226)), and the fourth + HomePod's reservation at `.24`, which the audit of 2026-11-13 found. Every other device above sits inside the pool by lease, so its row is what it had when it was read, not what it will have. The build proved why the rule's destination could not be one of those: between 2026-09-09 and 2026-09-28 the bridge moved from `.104` to @@ -941,8 +962,10 @@ the least trusted. Assistant can control the HomePods (play, pause, volume, what's playing) and not stream audio to them. Three are reserved at `.21`–`.23`, beside `bifrost`, since 2026-10-21. They were reset and set up again that day, - and the fourth has not been set up again yet. `.24` is kept for it, and the - rows cover it already. + and the fourth is reserved at `.24`, which the rows cover already. It + held a lease there when `morpheus` was audited on 2026-11-13 and none on + 2026-11-23, so whether it is set up again, and whether discovery from + `trinity` finds it, is not settled. Traffic matching them is translated on its way out of the Skids interface, from `10.0.99.40` to `10.0.20.1`, because the HomePods ignore mDNS queries from another subnet. With that, discovery from `trinity` finds all three. diff --git a/docs/observability.md b/docs/observability.md index 7f227af10..170e852f4 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -352,7 +352,7 @@ separates a quiet stream from a stopped one. ## Alerting -182 rules in total: 161 metric-based in `prometheus/rules/`, and 21 log-based in +186 rules in total: 163 metric-based in `prometheus/rules/`, and 23 log-based in `loki/rules/`. ### Log-based (Loki ruler) @@ -361,7 +361,14 @@ Some conditions only exist in logs. A metric confirms sshd is running; only the log shows it rejecting forty passwords in five minutes. `loki/rules/security.rules.yaml` covers SSH brute force, SSH accepted from outside VLAN 50/99, repeated sudo failures, user/group creation, kernel OOM kills, read-only remounts and disk I/O -errors. +errors. `loki/rules/ups.rules.yaml` reads `upsd` on `morpheus`: the NUT server +the secondaries depend on marks the UPS's data stale for a few seconds 20 to 40 +times a day, a baseline the 2026-11-13 audit found. `NutUpsDataStaleSustained` +fires when a stale period has lasted two minutes, and `NutUpsDataStaleFrequent` +when an hour has more than twenty, twice the worst hour measured. A gap that +lasts days is not theirs to see: syslogd folds a repeated line into one, so +`NutUpsUnreadable`, in `prometheus/rules/ups.rules.yaml`, asks `upsc` on the +firewall every 15 minutes instead (`scripts/collect-nut-state.sh`). **OOM kills have four owners** ([#903](https://github.com/Gerrrt/HomeLab/issues/903), [#1095](https://github.com/Gerrrt/HomeLab/issues/1095)): @@ -513,7 +520,7 @@ argument and for what to do when it exits 1. ### Metric-based (Prometheus) -161 rules across twelve files in `prometheus/rules/`: +163 rules across twelve files in `prometheus/rules/`: | File | Covers | | --- | --- | @@ -549,7 +556,7 @@ as loaded and healthy and could not fire for any input ([#63](https://github.com `prometheus/tests/*.test.yaml` holds `promtool test rules` unit tests, which feed a rule synthetic series and assert it fires — paired with a case asserting it stays quiet, because a test that only ever expects silence would have passed -against the broken rule too. Coverage is 161 rules of 161 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve +against the broken rule too. Coverage is 163 rules of 163 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, `ContainerNearMemoryLimit`, `ContainerRestartLoop`, `ContainerCpuThrottled`, the three container-state rules from diff --git a/docs/runbooks/deploy-stack.md b/docs/runbooks/deploy-stack.md index 9df5cb21f..61a4eef84 100644 --- a/docs/runbooks/deploy-stack.md +++ b/docs/runbooks/deploy-stack.md @@ -151,7 +151,7 @@ Then in the UI: 1. **Prometheus → Status → Targets.** Every job `UP`. The four `snmp` targets take up to 45 seconds on their first scrape. 2. **Prometheus → Status → Rules.** Every rule loaded, none in error. The - page lists 167: the 161 alert rules this repository counts everywhere + page lists 169: the 163 alert rules this repository counts everywhere else, plus the six recording rules: `homelab_suricata_expected_interface`, `homelab_battery_runtime_seconds`, and the two directions each of diff --git a/docs/runbooks/generate-certificates.md b/docs/runbooks/generate-certificates.md index 141a5d448..c32f94b63 100644 --- a/docs/runbooks/generate-certificates.md +++ b/docs/runbooks/generate-certificates.md @@ -244,6 +244,15 @@ is within 15 minutes. For the others it is the next day, or sooner if the collector is run by hand: `systemctl start homelab-cert-expiry` on Saruman, or the cron job's **Run Now** on smaug. +The two syslog TLS leaves are read the same way, from the same job +([#1049](https://github.com/Gerrrt/HomeLab/issues/1049)): `syslog-listener` off +the handshake on `10.0.99.20:6514`, and `syslog-client`, `morpheus`'s client +leaf, from the copy the listener pins in `certificates/`, because a client +certificate has no handshake to read. Both are this CA's, 825 days, due +2029-01-09. They raise `SyslogTlsCertificateExpiringSoon` at 30 days, not the +console pair, and are reissued by +[`ship-firewall-logs.md`](ship-firewall-logs.md) §1 and §3. + A console whose certificate cannot be read raises `ManagementCertificateUnchecked` after six hours rather than going silent. Run the collector with `--print` to see which probe failed. diff --git a/docs/security.md b/docs/security.md index f1bd74bdb..38b2c2e98 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,7 +33,7 @@ What this network is actually built to survive: | A rooted range target reaching `gandalf` itself | **Dropped at `vmbr1`, before the host firewall, once applied.** The host has no address on the range bridge, but Linux answers ARP for its addresses on any interface and accepts a packet for them on any interface. So a target that adds an on-link route to `10.0.30.30` was reaching the host, and only the Proxmox firewall dropped it. Nothing watches that firewall on `gandalf`. A netdev `ingress` table on `vmbr1` now drops every frame the bridge passes up to the host, ARP included, without touching guest-to-guest traffic ([`build-the-playground.md`](runbooks/build-the-playground.md) §2, proved by §8 check four). Behind it, `gandalf` holds no estate credential, no GitHub login, no personal tooling and no third-party apt repository (§4, *Nothing else on `gandalf`*), so the host gives nothing beyond itself. The audits of 2026-11-13 and 2026-11-22 found credentials, then tooling and two third-party repositories. The credentials were gone by 2026-11-22. **The table and the tooling removal are not yet applied** | | Someone on Winterfell or Hicks logging in to `trinity` | **Key-only `sshd` since 2026-11-20; no host firewall by decision.** `trinity` holds the household's data and the sensitive tier's age key, and its `sshd` answers Hicks (by [ADR-0031](adr/0031-narrow-hicks-to-a-named-list-on-winterfell-and-leave-the-lab-open.md)'s list) and every host on VLAN 99, between which pfSense never filters. [`build-the-sensitive-tier-host.md`](runbooks/build-the-sensitive-tier-host.md) §3 now makes `sshd` key-only through a drop-in that outranks cloud-init's, refuses root and X11 forwarding, and keeps `authorized_keys` to `prometheus`'s key and Hicks's. The audit of 2026-11-13 found it taking passwords, with X11 forwarding on and 17 keys imported from GitHub. The step was applied on 2026-11-20: a password-only login is refused with `Permission denied (publickey)`, and three keys remain, `prometheus`'s, Hicks's and the operator's laptop, the last kept by decision. Agent sessions run on `trinity` as the operator, by decision ([ADR-0123](adr/0123-keep-agent-sessions-on-trinity.md)). `ufw` is installed and stays disabled, unlike `phoenix`'s ([ADR-0117](adr/0117-give-phoenix-a-key-only-sshd-and-a-default-deny-inbound-policy.md)): the other two ports `trinity` answers, `443` and `53`, are published by Docker, whose rules run ahead of `ufw`'s, so a policy would govern `22` alone, which the drop-in already closes to anything without a key. Nothing routes through `trinity`, and as the spare firewall a host policy is one more thing to get in the way the day it stands in for `morpheus`. What reaches `443` and `53` is set by pfSense and by the stack's bind addresses | | Someone with the trusted Wi-Fi key quietly joining | Kea's lease log reaches Loki; `UnknownDeviceOnTrustedSegment` fires the first time a MAC appears on VLAN 50 in seven days ([ADR-0019](adr/0019-read-device-joins-from-the-dhcp-server.md)) | -| Losing visibility of a failure | 182 alert rules, 30 days of metrics and logs | +| Losing visibility of a failure | 186 alert rules, 30 days of metrics and logs | | Someone on a reachable VLAN silencing an alert to hide a failure | Alertmanager binds to `127.0.0.1`; silences go through authenticated Grafana | | Mains power loss | **The rack, yes; the monitoring path, yes — on two laptop cells that were measured for the first time on 2026-09-12.** A pack fitted to `mjolnir` on 2026-08-28 passed its self-test; the TP-Link carrying `prometheus` and `oracle` has been on UPS power since 2026-09-08 ([#110](https://github.com/Gerrrt/HomeLab/issues/110)); the laptops ride a cut out on their own batteries, which `HostBatteryHealthLow` in `host.rules.yaml` now reads — `prometheus`'s cell was replaced on 2026-09-18 and reads 101 % of design, `oracle`'s was replaced on 2026-09-29 and reads 100 %, its design figure rather than a learned one ([#531](https://github.com/Gerrrt/HomeLab/issues/531)) — and **each runtime was measured once: `prometheus`'s on 2026-09-19, about 2.5 hours from full at the stack's load, and `oracle`'s on 2026-09-29, about 5.2 hours**; since the same day the projection is recorded on every cut and pages under thirty minutes (`HostBatteryRuntimeLow`, [#532](https://github.com/Gerrrt/HomeLab/issues/532)), but neither pack reports a moving cell temperature, so this row is answered for both hosts' runtime and for neither's cell temperature — see below. **What happens when the cut outlasts the pack is configured and accepted without a live test.** Since 2026-09-23 the firewall's NUT server reads `mjolnir`, and `Saruman` and `smaug` subscribe to it on their own gateway addresses, so a real cut would now try to run the sequence [ADR-0049](adr/0049-shut-down-on-the-ups-from-a-nut-server-on-the-firewall.md) decides: `Saruman` and `smaug` halt first and `morpheus` last. Since the move into the 32U rack on 2026-11-06 the PDU also carries `trinity`, `gandalf` (off until its build) and the console, with `smaug` racked and on the PDU directly rather than by its old long cord to the media room. [ADR-0107](adr/0107-subscribe-trinity-to-the-ups-and-bound-saruman-s-guest-stop.md) makes `trinity` a third subscriber and bounds `Saruman`'s guest stop. `Saruman`'s half was applied on 2026-11-13 (`down=90` on the four ordered guests, and its monitor stays logged in until they are down); `trinity`'s subscription, `HOSTSYNC 600` on `morpheus` and the card's 16-minute threshold followed on 2026-11-20, so all three subscribers would now halt before the pack empties; `gandalf`, the console and `neo` are left to the pack by decision. The pack itself is unmeasured: about 47 minutes at 21 % load is the card's own estimate. Neither the forced-shutdown proof nor a mains pull will be run ([ADR-0121](adr/0121-accept-the-ups-shutdown-without-a-live-test.md)) | | The estate being down while the person who runs it is unavailable | **Documentation, yes; data, no copy outside the house, by decision.** ADR-0011 puts the emergency tier on paper; [ADR-0023](adr/0023-keep-the-household-recovery-path-outside-the-estate.md) extends the same reasoning to the sensitive tier's data. That tier has held real photographs since 2026-09-28. [ADR-0122](adr/0122-drop-the-household-copy.md) dropped their copy outside the estate, so a loss of the house loses them — see below | diff --git a/scripts/README.md b/scripts/README.md index 78ca765fa..9f6da99bb 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -126,7 +126,8 @@ they describe. The rest are installed on the host they describe by | `collect-smart-state.sh`, `render-smart-baselines.sh` | SMART health for disks the iLO cannot see, and the known reallocated-sector baselines ([ADR-0046](../docs/adr/0046-record-a-known-static-smart-count-as-a-baseline-not-a-silence.md)) | | `collect-zpool-state.sh`, `collect-truenas-version.sh` | `smaug`'s pool leaves and TrueNAS version | | `collect-gateway-state.sh` | The firewall's view of its uplinks and its DDNS record | -| `collect-cert-expiry.sh` | When the management consoles' certificates expire, read off a handshake inside each console's segment ([ADR-0084](../docs/adr/0084-read-management-certificate-expiry-from-inside-each-segment.md)) | +| `collect-nut-state.sh` | Whether NUT on the firewall can read the UPS, asked with `upsc` the way a secondary does | +| `collect-cert-expiry.sh` | When the management consoles' certificates expire, read off a handshake inside each console's segment ([ADR-0084](../docs/adr/0084-read-management-certificate-expiry-from-inside-each-segment.md)); and the syslog TLS leaves, the client one from its pinned file with `--file` | | `collect_silences.py` | Alertmanager's silences, one series each, so a silence is watched rather than remembered | | `collect-container-state.sh` | Whether each container of a compose project is running | | `collect-guest-state.sh`, `collect-guest-disk-state.sh`, `collect-thin-pool-state.sh` | `Saruman`'s guests: running, how full, and how full its thin pools are | diff --git a/scripts/collect-cert-expiry.sh b/scripts/collect-cert-expiry.sh index b2c143f14..83649b6af 100755 --- a/scripts/collect-cert-expiry.sh +++ b/scripts/collect-cert-expiry.sh @@ -44,8 +44,16 @@ # expired, and a reader that has quietly stopped working must not look like # good news. # +# A CLIENT CERTIFICATE HAS NO HANDSHAKE TO READ. morpheus's syslog leaf +# (#1049) is presented only when morpheus connects out, and the listener on the +# monitoring host pins that exact certificate. So --file reads a certificate +# file on THIS host, the pinned copy, which is the one that has to match: the +# day it expires, morpheus's logs stop arriving and FirewallLogsStopped is the +# first word. A certificate file holds no key; a key file is refused. +# # Usage: scripts/collect-cert-expiry.sh [--ssh USER@HOST] [--host NAME] [--print] # --probe ENDPOINT=HOST=ADDR:PORT [...] +# --file ENDPOINT=HOST=PATH [...] # scripts/collect-cert-expiry.sh --self-test # # --probe endpoint name, the host label the series carries (`-` for this @@ -53,6 +61,8 @@ # --host names the output file, cert-expiry-.prom; defaults to # this host's hostname # --ssh run the probes on that host instead of here +# --file endpoint name, host label, and a PEM certificate on this host; +# always read here, never over --ssh set -uo pipefail TEXTFILE_DIR="${TEXTFILE_DIR:-/var/lib/node_exporter/textfile_collector}" @@ -60,6 +70,7 @@ PRINT_ONLY=0 SSH_TARGET="" FILE_HOST="" PROBES=() +FILES=() die() { printf '\033[0;31merror:\033[0m %s\n' "$*" >&2; exit 1; } @@ -69,6 +80,11 @@ valid_probe() { [[ "$1" =~ ^[a-z0-9][a-z0-9-]*=([A-Za-z0-9][A-Za-z0-9._-]*|-)=[A-Za-z0-9][A-Za-z0-9.-]*:[0-9]{1,5}$ ]] } +valid_file() { + [[ "$1" =~ ^[a-z0-9][a-z0-9-]*=([A-Za-z0-9][A-Za-z0-9._-]*|-)=[A-Za-z0-9._/][A-Za-z0-9._/-]*$ ]] \ + && [[ "$1" != *key.pem && "$1" != *-key* ]] +} + # The script that does the handshakes. Takes "ENDPOINT ADDR:PORT" pairs and # prints "ENDPOINT notAfter=" or "ENDPOINT -". probe_script() { @@ -131,6 +147,22 @@ if [[ "${1:-}" == "--self-test" ]]; then same "an unread endpoint is checked 0" \ "$(grep '^homelab_cert_checked{endpoint="ilo-ui"' <<<"$out")" 'homelab_cert_checked{endpoint="ilo-ui",host="shiva"} 0' + p='syslog-client=morpheus=certificates/morpheus.matrix.elysium.pem' + if valid_file "$p"; then ok "accepts --file $p"; else bad "accepts --file $p"; fi + # shellcheck disable=SC2016 # the $(id) is the injection being refused + for p in 'k=h=certificates/syslog.matrix.elysium-key.pem' 'a=h=x.pem;id' 'a=h=$(id)' 'a=h=a b.pem'; do + if valid_file "$p"; then bad "rejects --file ${p}"; else ok "rejects --file ${p}"; fi + done + cert_tmp="$(mktemp -d)" + if openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 3 \ + -subj /CN=self-test -keyout "${cert_tmp}/k" -out "${cert_tmp}/c.pem" >/dev/null 2>&1; then + got="$(to_epoch "$(openssl x509 -noout -enddate -in "${cert_tmp}/c.pem")")" + same "a certificate file's date to epoch" "$(( (got - $(date +%s) + 3600) / 86400 ))" 3 + else + bad "openssl could not make a test certificate" + fi + rm -rf "${cert_tmp}" + for p in 'pfsense-ui=morpheus=127.0.0.1:443' 'pve-ui=-=127.0.0.1:8006' 'ilo-ui=shiva=10.0.30.10:443'; do if valid_probe "$p"; then ok "accepts $p"; else bad "accepts $p"; fi done @@ -141,7 +173,7 @@ if [[ "${1:-}" == "--self-test" ]]; then # Arguments, through the real parser. timeout turns the old endless loop on # a trailing flag into 124, which is a FAIL here rather than a hung suite. - for flag in --probe --ssh --host; do + for flag in --probe --ssh --host --file; do timeout 5 "${BASH_SOURCE[0]}" "${flag}" >/dev/null 2>&1; rc=$? if ((rc != 0 && rc != 124)); then ok "a trailing ${flag} with no value is refused" else bad "a trailing ${flag} with no value is refused (exit ${rc})"; fi @@ -173,10 +205,11 @@ while (($#)); do --ssh) need_value "${2:-}" $# "$1"; SSH_TARGET="$2"; shift 2 ;; --host) need_value "${2:-}" $# "$1"; FILE_HOST="$2"; shift 2 ;; --probe) need_value "${2:-}" $# "$1"; PROBES+=("$2"); shift 2 ;; + --file) need_value "${2:-}" $# "$1"; FILES+=("$2"); shift 2 ;; *) die "unknown argument $1" ;; esac done -((${#PROBES[@]})) || die "at least one --probe ENDPOINT=HOST=ADDR:PORT is required" +((${#PROBES[@]} + ${#FILES[@]})) || die "at least one --probe ENDPOINT=HOST=ADDR:PORT or --file ENDPOINT=HOST=PATH is required" [[ -n "$FILE_HOST" ]] || FILE_HOST="$(hostname)" [[ "$FILE_HOST" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "--host ${FILE_HOST@Q} is not a host name" @@ -188,26 +221,38 @@ for p in "${PROBES[@]}"; do pairs+=("${endpoint} ${addr}"); labels+=("${endpoint} ${hostlabel}") done -STDERR_FILE="$(mktemp)"; trap 'rm -f "${STDERR_FILE}"' EXIT -if [[ -n "$SSH_TARGET" ]]; then - raw="$(probe_script "${pairs[@]}" \ - | ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_TARGET" 'sh -s' 2>"${STDERR_FILE}")" -else - raw="$(probe_script "${pairs[@]}" | sh -s 2>"${STDERR_FILE}")" -fi -# No line at all means the probes never ran — ssh failed, or there is no -# openssl. That is the job failing, not every certificate being unreadable, so -# it exits non-zero and leaves the previous file for the staleness rules. -if [[ -z "$raw" ]]; then - detail="$(tr -d '\r' < "${STDERR_FILE}" | grep -v '^$' | tail -2 | paste -sd'; ' -)" - die "the probes did not run${SSH_TARGET:+ on ${SSH_TARGET}}${detail:+ — ${detail}}" +results="" +if ((${#PROBES[@]})); then + STDERR_FILE="$(mktemp)"; trap 'rm -f "${STDERR_FILE}"' EXIT + if [[ -n "$SSH_TARGET" ]]; then + raw="$(probe_script "${pairs[@]}" \ + | ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_TARGET" 'sh -s' 2>"${STDERR_FILE}")" + else + raw="$(probe_script "${pairs[@]}" | sh -s 2>"${STDERR_FILE}")" + fi + # No line at all means the probes never ran — ssh failed, or there is no + # openssl. That is the job failing, not every certificate being unreadable, so + # it exits non-zero and leaves the previous file for the staleness rules. + if [[ -z "$raw" ]]; then + detail="$(tr -d '\r' < "${STDERR_FILE}" | grep -v '^$' | tail -2 | paste -sd'; ' -)" + die "the probes did not run${SSH_TARGET:+ on ${SSH_TARGET}}${detail:+ — ${detail}}" + fi + + for l in "${labels[@]}"; do + endpoint="${l%% *}"; hostlabel="${l#* }" + line="$(grep -m1 "^${endpoint} " <<<"$raw")" + epoch="$(to_epoch "${line#* }")" + results+="${endpoint} ${hostlabel} ${epoch}"$'\n' + done fi -results="" -for l in "${labels[@]}"; do - endpoint="${l%% *}"; hostlabel="${l#* }" - line="$(grep -m1 "^${endpoint} " <<<"$raw")" - epoch="$(to_epoch "${line#* }")" +# Files are read here even with --ssh: they are this host's copies. One that is +# missing or unparseable is checked 0, like a handshake that failed. +for f in "${FILES[@]}"; do + valid_file "$f" || die "--file ${f@Q} is not ENDPOINT=HOST=PATH to a certificate (not a key)" + endpoint="${f%%=*}"; rest="${f#*=}"; hostlabel="${rest%%=*}"; path="${rest#*=}" + [[ "$hostlabel" == - ]] && hostlabel="$(hostname)" + epoch="$(to_epoch "$(openssl x509 -noout -enddate -in "$path" 2>/dev/null)")" results+="${endpoint} ${hostlabel} ${epoch}"$'\n' done diff --git a/scripts/collect-nut-state.sh b/scripts/collect-nut-state.sh new file mode 100755 index 000000000..3cfc6c3bc --- /dev/null +++ b/scripts/collect-nut-state.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# +# Whether the NUT server on the firewall can read the UPS, as a metric. +# +# WHAT NOTHING WAS WATCHING. morpheus runs NUT's primary for `mjolnir`: its +# snmp-ups driver polls the card, and every secondary (Saruman, smaug, trinity) +# learns of a power cut only from it. From 2026-11-05 to 2026-11-07 the driver +# was not connected, upsmon logged it 23,048 times, and nothing raised a word +# (changelog, 2026-11-23). The card-silence alerts are about the card answering +# SNMP; they say nothing about NUT, and a driver that stays down while the card +# answers raises nothing at all. Loki does not fill the gap either: syslogd +# folds a repeated line into "last message repeated", so a driver down for +# days leaves one line, and a log rule's window has moved past it within +# minutes. The two Loki rules in loki/rules/ups.rules.yaml cover the short +# gaps; this covers the long one. +# +# So this asks NUT itself, the way a secondary does: `upsc mjolnir@127.0.0.1 +# ups.status` on the firewall, over the ssh `make gateway-state` already makes. +# A status (OL, OB, LB, ...) is readable; anything else ("Error: Data stale", +# "Error: Driver not connected", no answer) is not. The reason goes to the job's +# output, not to a label, so the series keeps one identity and `for` works. +# +# "Could not ask" is kept apart from "NUT cannot read it": if ssh fails the run +# fails and writes nothing, and the job alerts (ScheduledJobFailed) instead of +# this one. +# +# Usage: scripts/collect-nut-state.sh --ssh USER@HOST --host NAME [--ups NAME] [--print] +# scripts/collect-nut-state.sh --self-test +set -uo pipefail + +TEXTFILE_DIR="${TEXTFILE_DIR:-/var/lib/node_exporter/textfile_collector}" +PRINT_ONLY=0 +SSH_TARGET="" +HOST_LABEL="" +UPS="mjolnir" + +die() { printf '\033[0;31merror:\033[0m %s\n' "$*" >&2; exit 1; } + +# upsc's answer -> "1 " or "0 ". The answer is the remote +# output: the status line, or upsc's error, then "rc=N". +classify() { + local answer="$1" first rc + first="$(printf '%s\n' "$answer" | grep -v '^rc=' | head -1 | tr -d '\r')" + rc="$(printf '%s\n' "$answer" | sed -n 's/^rc=//p' | tail -1)" + if [[ "$rc" == 0 && "$first" =~ ^[A-Z]+( [A-Z]+)*$ ]]; then + printf '1 %s\n' "$first" + else + first="${first#Error: }" + printf '0 %s\n' "${first:-no answer}" + fi +} + +render() { + local readable="$1" + printf '# HELP homelab_nut_ups_readable 1 when the NUT server on this host can read the UPS (upsc returns a status).\n' + printf '# TYPE homelab_nut_ups_readable gauge\n' + printf 'homelab_nut_ups_readable{host="%s",ups="%s"} %s\n' "$HOST_LABEL" "$UPS" "$readable" +} + +if [[ "${1:-}" == "--self-test" ]]; then + fail=0 + ok() { printf '\033[0;32m PASS\033[0m %s\n' "$1"; } + bad() { printf '\033[0;31m FAIL\033[0m %s\n' "$1"; fail=1; } + same() { if [[ "$2" == "$3" ]]; then ok "$1"; else bad "$1"; printf ' got %s\n expected %s\n' "$2" "$3"; fi; } + + same "on line is readable" "$(classify $'OL\nrc=0')" "1 OL" + same "on battery, charging is readable" "$(classify $'OB DISCHRG\nrc=0')" "1 OB DISCHRG" + same "stale data is not" "$(classify $'Error: Data stale\nrc=1')" "0 Data stale" + same "a driver not connected is not" "$(classify $'Error: Driver not connected\nrc=1')" "0 Driver not connected" + same "no answer at all is not" "$(classify 'rc=255')" "0 no answer" + same "a status with a failing rc is not" "$(classify $'OL\nrc=1')" "0 OL" + HOST_LABEL=morpheus + same "the series" "$(render 0 | tail -1)" 'homelab_nut_ups_readable{host="morpheus",ups="mjolnir"} 0' + exit $fail +fi + +need_value() { [[ $2 -ge 2 && -n "$1" ]] || die "$3 needs a value"; } +while (($#)); do + case "$1" in + --print) PRINT_ONLY=1; shift ;; + --ssh) need_value "${2:-}" $# "$1"; SSH_TARGET="$2"; shift 2 ;; + --host) need_value "${2:-}" $# "$1"; HOST_LABEL="$2"; shift 2 ;; + --ups) need_value "${2:-}" $# "$1"; UPS="$2"; shift 2 ;; + *) die "unknown argument $1" ;; + esac +done +[[ -n "$SSH_TARGET" ]] || die "--ssh USER@HOST is required" +[[ "$HOST_LABEL" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "--host NAME is required" +# Interpolated into the command the firewall runs, so checked for shape. +[[ "$UPS" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || die "--ups ${UPS@Q} is not a UPS name" + +answer="$(ssh -o BatchMode=yes -o ConnectTimeout=10 "$SSH_TARGET" \ + "upsc ${UPS}@127.0.0.1 ups.status 2>&1; echo rc=\$?" 2>/dev/null)" +[[ "$answer" == *rc=* ]] || die "could not ask NUT on ${SSH_TARGET}" + +read -r readable detail <<<"$(classify "$answer")" +if ((PRINT_ONLY)); then render "$readable"; exit 0; fi + +[[ -d "${TEXTFILE_DIR}" ]] || die "no ${TEXTFILE_DIR}" +PROM="${TEXTFILE_DIR}/nut-state-${HOST_LABEL}.prom" +tmp="${PROM}.$$" +render "$readable" > "${tmp}" || { rm -f "${tmp}"; die "could not write ${tmp}"; } +{ chmod 0644 "${tmp}" && mv -f "${tmp}" "${PROM}"; } \ + || { rm -f "${tmp}"; die "could not install ${PROM}"; } +printf 'nut-state host=%s ups=%s readable=%s (%s)\n' "$HOST_LABEL" "$UPS" "$readable" "$detail" diff --git a/scripts/self-tests.sh b/scripts/self-tests.sh index 11aa5aee7..1837b2460 100755 --- a/scripts/self-tests.sh +++ b/scripts/self-tests.sh @@ -39,6 +39,8 @@ # agent_control JSON; a removed state file (both # say they will be deprecated) cannot be staged # collect-gateway-state.sh the gateway parse, for morpheus +# collect-nut-state.sh upsc's answer, readable or not; a driver that is +# down cannot be staged on the firewall on demand # collect-smart-state.sh the collector that shipped WITHOUT fixtures and then # produced a real defect (#483); two fixtures are what # was read off smaug at the console on 2026-09-21 diff --git a/stacks/observability/README.md b/stacks/observability/README.md index 40a594e15..0e562e980 100644 --- a/stacks/observability/README.md +++ b/stacks/observability/README.md @@ -53,7 +53,7 @@ prometheus/ targets/snmp.yaml SNMP targets — hot-reloaded, no restart needed targets/node.yaml node_exporter scrapes, for the host that runs no Alloy (smaug) targets/blackbox*.yaml probe targets, http, dns and latency — hot-reloaded, no restart - rules/*.rules.yaml 161 alert rules: host, network, ups, containers, blackbox, + rules/*.rules.yaml 163 alert rules: host, network, ups, containers, blackbox, dns, backup, ids, deploy, stack, internet and watchdog tests/*.test.yaml promtool unit tests — assert the rules can fire blackbox/blackbox.yaml probe modules — reachability, and what a resolver said @@ -61,7 +61,7 @@ alertmanager/ alertmanager.yaml severity + category routing, inhibition loki/ loki-config.yaml single-binary, filesystem, 30-day retention - rules/*.rules.yaml 21 LogQL rules, security and watchdog, evaluated by Loki's ruler + rules/*.rules.yaml 23 LogQL rules, security, NUT and watchdog, evaluated by Loki's ruler alloy/ the agent config — Alloy loads the directory config.alloy every monitored host docker.alloy hosts with a Docker socket diff --git a/stacks/observability/loki/rules/ups.rules.yaml b/stacks/observability/loki/rules/ups.rules.yaml new file mode 100644 index 000000000..7276ee679 --- /dev/null +++ b/stacks/observability/loki/rules/ups.rules.yaml @@ -0,0 +1,80 @@ +--- +# NUT on morpheus losing its UPS data, read from upsd's log. +# +# morpheus runs the NUT server for the UPS card (`mjolnir`): its driver polls +# the card over SNMPv3, and the secondaries (Saruman, smaug, trinity) learn +# about a power cut only from it. When upsd marks the data stale, every +# secondary is blind for that long. The Prometheus side (ups.rules.yaml) polls +# the card directly, so it keeps reporting the UPS while morpheus has lost it; +# only upsd's log shows the gap. +# +# Measured over the fortnight to 2026-11-23, from Loki: 1,363 stale periods, +# none longer than 5.2 seconds, and never more than 9 in an hour. That is the +# baseline the 2026-11-13 audit of morpheus found and could not yet explain. +# These two rules alert when it gets worse, not on the baseline itself. +# +# A gap that lasts days is not theirs: syslogd folds a repeated line into "last +# message repeated", and their windows move past the first line within +# minutes. NutUpsUnreadable in prometheus/rules/ups.rules.yaml asks upsc on the +# firewall every 15 minutes for that case (scripts/collect-nut-state.sh). +groups: + - name: ups-nut + interval: 1m + rules: + - alert: NutUpsDataStaleSustained + # A stale period that has not ended. upsd logs "Data for UPS [...] is + # stale" when it starts and "data is no longer stale" when it ends, so + # more starts than ends in the window means one is still open. The + # `unless` arm covers the case with no end line in the window at all, + # where the subtraction alone returns nothing. Two minutes is more than + # twenty times the longest period measured; a real outage that long + # during a power cut means the secondaries never hear the low-battery + # signal. + expr: | + ( + sum by (host) (count_over_time({app="upsd"} |= "is stale" [15m])) + - + sum by (host) (count_over_time({app="upsd"} |= "no longer stale" [15m])) + ) > 0 + or + ( + sum by (host) (count_over_time({app="upsd"} |= "is stale" [15m])) + unless + sum by (host) (count_over_time({app="upsd"} |= "no longer stale" [15m])) + ) + for: 2m + labels: + component: power + severity: warning + category: power + annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/shut-down-on-the-ups.md" + summary: "NUT on {{ $labels.host }} has had stale UPS data for over 2 minutes" + description: >- + upsd on {{ $labels.host }} marked the UPS's data stale and has not + recovered. Until it does, a power cut reaches none of the NUT + secondaries. Check the card answers SNMP (the Prometheus UPS + panels read it directly), then `upsc mjolnir` and the driver + (`snmp-ups`) on morpheus; restarting the NUT service from + Status -> Services is the usual fix. + + - alert: NutUpsDataStaleFrequent + # The trend, not the event. Short stale periods are the baseline, at up + # to 9 an hour; twenty in an hour is more than twice the worst hour + # measured, so the poll is degrading even if each gap still closes. + expr: | + sum by (host) (count_over_time({app="upsd"} |= "is stale" [1h])) > 20 + for: 0s + labels: + component: power + severity: warning + category: power + annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/shut-down-on-the-ups.md" + summary: "NUT on {{ $labels.host }} lost the UPS data {{ $value }} times in an hour" + description: >- + upsd's data for the UPS went stale more than twice as often as the + worst hour on record. Each gap is a window in which a power cut + reaches no secondary. Look at what else polls the card (Prometheus's + SNMP job, the driver's pollfreq on morpheus) and the card's own + event log before the gaps start lasting. diff --git a/stacks/observability/loki/tests/ups.test.yaml b/stacks/observability/loki/tests/ups.test.yaml new file mode 100644 index 000000000..3ea9a5ef9 --- /dev/null +++ b/stacks/observability/loki/tests/ups.test.yaml @@ -0,0 +1,71 @@ +--- +# Behaviour tests for loki/rules/ups.rules.yaml, run by +# scripts/test_loki_rules.py. The lines are upsd's own wording on morpheus, as +# Loki holds them; Alloy labels them app=upsd, host=morpheus. +tests: + - alert: NutUpsDataStaleSustained + name: a stale period with no end fires + window: 15m + streams: + - labels: {app: upsd, host: morpheus} + entries: + - before: 5m + line: "Data for UPS [mjolnir] is stale - check driver" + expect: + - {host: morpheus} + + - alert: NutUpsDataStaleSustained + name: an open period after closed ones fires + window: 15m + streams: + - labels: {app: upsd, host: morpheus} + entries: + - before: 10m + line: "Data for UPS [mjolnir] is stale - check driver" + - before: 9m + line: "UPS [mjolnir] data is no longer stale" + - before: 4m + line: "Data for UPS [mjolnir] is stale - check driver" + expect: + - {host: morpheus} + + - alert: NutUpsDataStaleSustained + name: short periods that all close stay quiet + window: 15m + streams: + - labels: {app: upsd, host: morpheus} + entries: + - before: 10m + line: "Data for UPS [mjolnir] is stale - check driver" + - before: 9m58s + line: "UPS [mjolnir] data is no longer stale" + - before: 3m + line: "Data for UPS [mjolnir] is stale - check driver" + - before: 2m59s + line: "UPS [mjolnir] data is no longer stale" + expect: [] + + - alert: NutUpsDataStaleFrequent + name: twenty-one stale periods in an hour fire + window: 1h + streams: + - labels: {app: upsd, host: morpheus} + entries: + - before: 50m + count: 21 + every: 2m + line: "Data for UPS [mjolnir] is stale - check driver" + expect: + - {host: morpheus} + + - alert: NutUpsDataStaleFrequent + name: the measured worst hour stays quiet + window: 1h + streams: + - labels: {app: upsd, host: morpheus} + entries: + - before: 50m + count: 9 + every: 5m + line: "Data for UPS [mjolnir] is stale - check driver" + expect: [] diff --git a/stacks/observability/prometheus/rules/host.rules.yaml b/stacks/observability/prometheus/rules/host.rules.yaml index 9305fde7c..768b9fd8e 100644 --- a/stacks/observability/prometheus/rules/host.rules.yaml +++ b/stacks/observability/prometheus/rules/host.rules.yaml @@ -2138,7 +2138,7 @@ groups: - alert: ManagementCertificateExpiringSoon expr: >- min by (endpoint, host) - (homelab_cert_expiry_timestamp_seconds - time()) + (homelab_cert_expiry_timestamp_seconds{endpoint!~"syslog-.*"} - time()) / 86400 < 30 for: 1h labels: @@ -2161,7 +2161,7 @@ groups: - alert: ManagementCertificateExpiryImminent expr: >- min by (endpoint, host) - (homelab_cert_expiry_timestamp_seconds - time()) + (homelab_cert_expiry_timestamp_seconds{endpoint!~"syslog-.*"} - time()) / 86400 < 7 for: 10m labels: @@ -2179,6 +2179,36 @@ groups: is the console someone reaches for when something else is already wrong. Reissue it now from the runbook. + # The two syslog TLS leaves (#1049): the listener's on the monitoring + # host, and morpheus's client leaf, which the listener pins exactly. Both + # come from scripts/gen-certs.sh, which issues 825 days, so they lapse + # together and rarely enough to be forgotten. Not the console rules: + # neither is reissued from a UI, and the day either lapses nothing breaks + # visibly, morpheus's logs just stop (FirewallLogsStopped). One tier, + # because the fix is the same at 30 days as at 7. + - alert: SyslogTlsCertificateExpiringSoon + expr: >- + min by (endpoint, host) + (homelab_cert_expiry_timestamp_seconds{endpoint=~"syslog-.*"} - time()) + / 86400 < 30 + for: 1h + labels: + component: logs + severity: warning + category: availability + annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/ship-firewall-logs.md#1-issue-both-certificates-before-the-receiver-is-deployed" + summary: >- + {{ $labels.endpoint }} ({{ $labels.host }}) has a certificate + with {{ $value | printf "%.0f" }} days left + description: >- + One of the syslog TLS leaves is close to expiry. Reissue both with + scripts/gen-certs.sh on the monitoring host + (ship-firewall-logs.md §1), copy morpheus's new client leaf and key + to pfSense (§3), and restart Alloy, which reads the pinned leaf + only at start. Until then the firewall's logs keep arriving; after + the date, FirewallLogsStopped. + # The reader could not complete a handshake. Kept apart from the expiry # rules on purpose (the homelab_ddns_record_checked pattern): an unread # certificate has no expiry sample, so without this a console that diff --git a/stacks/observability/prometheus/rules/ups.rules.yaml b/stacks/observability/prometheus/rules/ups.rules.yaml index 615ead237..8fd641ace 100644 --- a/stacks/observability/prometheus/rules/ups.rules.yaml +++ b/stacks/observability/prometheus/rules/ups.rules.yaml @@ -170,6 +170,33 @@ groups: annotations: summary: "UPS {{ $labels.device }} battery at {{ $value }}°C" + # NUT on the firewall cannot read the UPS, so no secondary would hear of + # a power cut. Everything else in this group reads the card directly + # over SNMP and stays green while NUT is blind: from 2026-11-05 to + # 2026-11-07 the driver was not connected and nothing said so + # (changelog, 2026-11-23). scripts/collect-nut-state.sh asks `upsc` on + # morpheus from `make gateway-state`, every 15 minutes; 30 minutes is + # three reads. Critical, because while this fires a mains cut halts + # nothing in order. The few-second stale gaps that are the baseline never + # reach it; NutUpsDataStale* in Loki watch those. + - alert: NutUpsUnreadable + expr: homelab_nut_ups_readable == 0 + for: 30m + labels: + component: power + severity: critical + category: power + annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/shut-down-on-the-ups.md" + summary: "NUT on {{ $labels.host }} cannot read UPS {{ $labels.ups }}" + description: >- + For half an hour `upsc {{ $labels.ups }}@127.0.0.1` on + {{ $labels.host }} has returned an error, not a status, so a power + cut would reach none of the NUT secondaries. `make gateway-state`'s + output names the error. If the card answers SNMP (the UPS panels + read it directly), restart NUT from Status -> Services on pfSense + and check the driver's SNMPv3 credentials still match the card. + # The two rules that can actually detect a UPS which cannot carry load. # Everything above this point reads a value the management card is willing # to fabricate; these read the one it is not. diff --git a/stacks/observability/prometheus/tests/cert-expiry.test.yaml b/stacks/observability/prometheus/tests/cert-expiry.test.yaml index 9da34e40d..9b385c81b 100644 --- a/stacks/observability/prometheus/tests/cert-expiry.test.yaml +++ b/stacks/observability/prometheus/tests/cert-expiry.test.yaml @@ -204,3 +204,49 @@ tests: - eval_time: 71h alertname: CertExpiryStateStale exp_alerts: [] + + # --- The syslog TLS leaves: their own rule, not the console ones ---------- + # morpheus's client leaf 20 days out (1735200 = 20 × 86400 + 7200), beside + # the listener's a year away. The console rules must not see either. + - interval: 1m + input_series: + - series: 'homelab_cert_expiry_timestamp_seconds{endpoint="syslog-client", host="morpheus", + instance="prometheus", job="prometheus-metrics"}' + values: "1735200+0x180" + - series: 'homelab_cert_expiry_timestamp_seconds{endpoint="syslog-listener", host="prometheus", + instance="prometheus", job="prometheus-metrics"}' + values: "34567200+0x180" + alert_rule_test: + # Under 30 days from t=0, but `for: 1h`. + - eval_time: 30m + alertname: SyslogTlsCertificateExpiringSoon + exp_alerts: [] + + - eval_time: 2h + alertname: SyslogTlsCertificateExpiringSoon + exp_alerts: + - exp_labels: + alertname: SyslogTlsCertificateExpiringSoon + endpoint: syslog-client + host: morpheus + component: logs + severity: warning + category: availability + exp_annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/ship-firewall-logs.md#1-issue-both-certificates-before-the-receiver-is-deployed" + summary: "syslog-client (morpheus) has a certificate with 20 days left" + description: >- + One of the syslog TLS leaves is close to expiry. Reissue both with + scripts/gen-certs.sh on the monitoring host + (ship-firewall-logs.md §1), copy morpheus's new client leaf and key + to pfSense (§3), and restart Alloy, which reads the pinned leaf + only at start. Until then the firewall's logs keep arriving; after + the date, FirewallLogsStopped. + + - eval_time: 2h + alertname: ManagementCertificateExpiringSoon + exp_alerts: [] + + - eval_time: 2h + alertname: ManagementCertificateExpiryImminent + exp_alerts: [] diff --git a/stacks/observability/prometheus/tests/ups.test.yaml b/stacks/observability/prometheus/tests/ups.test.yaml index c84767b09..46c0f9b50 100644 --- a/stacks/observability/prometheus/tests/ups.test.yaml +++ b/stacks/observability/prometheus/tests/ups.test.yaml @@ -559,3 +559,49 @@ tests: - eval_time: 45m alertname: UpsRideThroughShort exp_alerts: [] + + # --- NutUpsUnreadable: NUT on morpheus cannot read the UPS ---------------- + # The textfile is rewritten every 15 minutes and re-served between, so the + # series is flat; 0 from t=0 crosses `for: 30m` after half an hour. + - interval: 1m + input_series: + - series: 'homelab_nut_ups_readable{host="morpheus", ups="mjolnir", + instance="prometheus", job="prometheus-metrics"}' + values: "0x60" + alert_rule_test: + - eval_time: 25m + alertname: NutUpsUnreadable + exp_alerts: [] + - eval_time: 35m + alertname: NutUpsUnreadable + exp_alerts: + - exp_labels: + alertname: NutUpsUnreadable + host: morpheus + ups: mjolnir + instance: prometheus + job: prometheus-metrics + component: power + severity: critical + category: power + exp_annotations: + runbook_url: "https://github.com/Gerrrt/HomeLab/blob/main/docs/runbooks/shut-down-on-the-ups.md" + summary: "NUT on morpheus cannot read UPS mjolnir" + description: >- + For half an hour `upsc mjolnir@127.0.0.1` on + morpheus has returned an error, not a status, so a power + cut would reach none of the NUT secondaries. `make gateway-state`'s + output names the error. If the card answers SNMP (the UPS panels + read it directly), restart NUT from Status -> Services on pfSense + and check the driver's SNMPv3 credentials still match the card. + + # --- NutUpsUnreadable: quiet while NUT reads a status --------------------- + - interval: 1m + input_series: + - series: 'homelab_nut_ups_readable{host="morpheus", ups="mjolnir", + instance="prometheus", job="prometheus-metrics"}' + values: "1x60" + alert_rule_test: + - eval_time: 45m + alertname: NutUpsUnreadable + exp_alerts: []