From 6b425fe036ae26421506a2037b01f4a422b102ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?ryan4yin=20=7C=20=E4=BA=8C=E8=8A=B1?= Date: Tue, 17 Nov 2026 21:08:02 +0800 Subject: [PATCH] feat(monitoring): close host and service monitoring gaps (#530) Assisted-by: DeepSeek Harness (claude-opus-5-5) --- .typos.toml | 5 ++ docs/BACKUP.md | 4 +- docs/SECURITY.md | 15 +++- docs/WORKAROUNDS.md | 1 + .../homelab-services/monitoring/README.md | 13 ++++ .../homelab-services/monitoring/alert.nix | 32 ++++++-- .../monitoring/alert_rules/blackbox.yml | 27 +++++++ .../monitoring/alert_rules/flake-inputs.yml | 30 ++++++++ .../monitoring/alert_rules/node-exporter.yml | 39 ++++++++-- .../monitoring/alert_rules/rasdaemon.yml | 27 +++++++ .../monitoring/alert_rules/storage.yml | 16 ++++ .../homelab-services/monitoring/blackbox.nix | 74 ++++++++++++++++++ .../homelab-services/monitoring/default.nix | 1 + .../monitoring/victoriametrics.nix | 32 +++++++- hosts/README.md | 16 ++++ hosts/idols-aquamarine/default.nix | 4 + hosts/idols-aquamarine/secureboot.nix | 2 + lib/genVmHostModule.nix | 29 +++++++ modules/nixos/base/monitoring.nix | 77 ++++++++++++++++++- modules/nixos/base/networking/firewall.nix | 16 +++- modules/nixos/hardware-health.nix | 15 ++++ 21 files changed, 452 insertions(+), 23 deletions(-) create mode 100644 hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/blackbox.yml create mode 100644 hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/flake-inputs.yml create mode 100644 hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/rasdaemon.yml create mode 100644 hosts/12kingdoms-youko/homelab-services/monitoring/blackbox.nix create mode 100644 modules/nixos/hardware-health.nix diff --git a/.typos.toml b/.typos.toml index 1bbce323..85360a5a 100644 --- a/.typos.toml +++ b/.typos.toml @@ -72,4 +72,9 @@ extend-ignore-re = [ # "for"/"far"/"fps". "fpr", "FPR", + + # PCIe Advanced Error Reporting (rasdaemon's `aer` collector and metrics); the + # dictionary wants "are". + "aer", + "AER", ] diff --git a/docs/BACKUP.md b/docs/BACKUP.md index fafc1aee..98d8558e 100644 --- a/docs/BACKUP.md +++ b/docs/BACKUP.md @@ -70,9 +70,11 @@ collisions. | 02:30 + 15m | youko dumps PostgreSQL, then backs itself up | | hourly | youko snapshots the REST store | | 03:45:20 Tue/Sat | btrbk local snapshots | +| 04:00-05:00, 1st | btrfs scrub on the physical servers | | 06:00 (planned) | youko copies homelab repos to cloud | -Set per host via `modules.restic-backup.onCalendar` and `randomizedDelaySec`. +Set per host via `modules.restic-backup.onCalendar` and `randomizedDelaySec`. The scrub row is a +start window: reading youko's HDDs (about 2.7 TiB used) takes hours, past the 06:00 slot. ## What is never backed up diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 2754d088..9f2cdac7 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -45,7 +45,7 @@ small, reversible controls and narrow exceptions; benchmark before adopting expe | Security keys | idols-ai/shoukei use a CanoKey for touch-based sudo (pam_u2f, password fallback; servers via pam_rssh and the forwarded agent), a resident `ed25519-sk` SSH key per CanoKey as the only user SSH keys for GitHub and all hosts, FIDO2 LUKS unlock on shoukei and on-card OpenPGP subkeys; key management happens only in the phone app ([setup](./security-keys.md)) | Touch-only sudo can be triggered by any same-user process, and on a server by root through the forwarded agent; losing both CanoKeys leaves only root logins with the `romantic` recovery key | | Secrets | agenix declarations here, encrypted data in the private nix-secrets repository | Recipients and plaintext file permissions must be reviewed; root on a recipient can read its decrypted secrets | | Supply chain | Locked flake inputs; explicit binary-cache trust keys on NixOS; normal user is not a Nix trusted-user | A trusted cache or imported Nix module can supply code executed as root; a lock file is not a security audit | -| Recovery | NixOS generations, btrbk/restic, hourly read-only snapshots of the REST store, and documented backup procedures | A rollback does not undo compromised data or secrets; backup configuration alone does not prove restore works; the offsite immutable copy is still planned | +| Recovery | NixOS generations with automatic boot fallback on the physical servers, btrbk/restic, hourly read-only snapshots of the REST store, and documented backup procedures | A rollback does not undo compromised data or secrets; backup configuration alone does not prove restore works; the offsite immutable copy is still planned | Sources: [host layout](../hosts/README.md), [k3s deployment](../hosts/k8s/README.md), [firewall](../modules/nixos/base/networking/firewall.nix), [SSH](../modules/nixos/base/ssh.nix), @@ -102,6 +102,12 @@ an advisory and affected kernel versions before adding CVE claims; search snippe key enrollment and actual Secure Boot state with `sbctl status`; do not assume all hosts have it. - Secure Boot, signed boot images, kernel lockdown and module signature enforcement are distinct controls. Test custom kernels and NVIDIA/out-of-tree modules before extending enforcement. +- A failed initrd on the physical servers opens a root shell after the root password + (`boot.initrd.systemd.emergencyAccess`, the public hash in [vars](../vars/default.nix)). It adds + no protection on shoryu, shushou and youko: Secure Boot is off, the systemd-boot editor is on and + TPM2 unlocks LUKS on PCRs 0+7 alone, so console access already grants root through a kernel + command-line edit. aquamarine's Lanzaboote stub ignores command-line edits while Secure Boot is + on. - AppArmor is enabled, but the only explicit policy, sudo's, is in complain mode. Complain mode logs rather than blocks. Existing FHS-oriented abstractions need Nix store path review; this is not broad enforced application confinement. @@ -400,6 +406,11 @@ compatibility, and a generation change that only affects the initrd, modules or kernel path unchanged. Guest profiles and a runner staged only on a MicroVM's physical host require separate verification. +Physical hosts run this comparison for the kernel, initrd and kernel modules every 15 minutes and +export the result as `node_reboot_required` +([monitoring.nix](../modules/nixos/base/monitoring.nix)); `HostRequiresReboot` warns when a reboot +has been pending for a day. + ## Remaining prioritized TODOs | Priority | Work | Acceptance / constraints | @@ -410,7 +421,7 @@ separate verification. | P1 | Review router mappings and tailnet ACLs; narrow service exposure where warranted | Audit was limited to sampled host listeners; test intended and denied access without locking out deployment | | P1 | Review NFS client scope and root identity requirements | Restrict to required VM hosts/CSI nodes where practical; test provisioning, permissions and existing PVCs before changing squash semantics | | P1 | Narrow operator/secret access where justified; finish permission checks | Selected effective probes and ai/youko modes audited; validate broad secret-reader needs, remaining hosts and recipient scope; Darwin per-file ownership is now explicit and needs a runtime check | -| P1 | Adopt the documented cadence and verify the booted kernel after rollouts | Routine documented; compare booted and selected kernel paths and recheck API/workloads after reboot; no automated metric is deployed | +| P1 | Adopt the documented cadence and verify the booted kernel after rollouts | Routine documented; physical hosts export `node_reboot_required` to `HostRequiresReboot`; guests still need the manual check; recheck API/workloads after reboot | | P1 | Exercise backup restore and credential rotation | Use an approved isolated restore target and recovery access; never overwrite live data for a drill | | P2 | Promote selected AppArmor profiles to enforce; harden exposed systemd services | Per-app positive/negative tests, store-path coverage, reviewed capabilities and reversible rollout | | P2 | Maintain ai boot integrity and assess other host roles | Review sbctl configuration migration, recovery boot and signed custom/NVIDIA modules; ai Secure Boot state already verified | diff --git a/docs/WORKAROUNDS.md b/docs/WORKAROUNDS.md index f1edba99..8848d907 100644 --- a/docs/WORKAROUNDS.md +++ b/docs/WORKAROUNDS.md @@ -52,6 +52,7 @@ A setting that works around a bug or a hardware quirk. | WA-049 | none — superseded by pointing `npmRegistryOverrides` at a mirror whose path avoids the join (`outputs/default.nix`) | nixpkgs joins an `npmRegistryOverrides` mirror's path (`/` for a bare host) with the request path, so `fetchNpmDeps` requests `https://registry.npmmirror.com//`, which npmmirror answers with 404 (npmjs tolerates `//`); every npm-deps fetch that misses the binary caches fails. Only `fetchNpmDeps` (fixed-output) gets the patched copy: `npmConfigHook` is a build input of every npm package, so patching the shared `prefetch-npm-deps` would change all their output paths | Drop once nixpkgs' `prefetch-npm-deps/src/util.rs` joins the paths without doubling the slash | 2026-11-03 | on a nixpkgs bump | removed | | WA-050 | polkit agent-helper sandbox opened for pam_u2f — `modules/nixos/desktop/canokey.nix` | nixpkgs relaxes `polkit-agent-helper@`'s `PrivateDevices`/`ProtectHome` for pam_u2f only when the global `security.pam.u2f.enable` is set; this repo enables U2F per service (sudo, polkit-1) so other PAM services keep the password, and without the override pam_u2f cannot reach `/dev/hidraw*` and polkit silently falls back to the password | Drop once nixpkgs' `polkit.nix` also checks per-service `u2f.enable` | 2026-11-09 | on a nixpkgs bump | active | | WA-051 | Steam on the raw session bus, nixpak's D-Bus proxy off — `hardening/nixpaks/steam.nix` | Steam's SteamRT3 client starts pressure-vessel, which wraps any bus path other than `$XDG_RUNTIME_DIR/bus` in a second D-Bus proxy; the launcher-service RPC (`steam-runtime-launch-client --alongside-steam -- lspci`) never crosses that nesting, so the client hangs before its window with no error. On the standard path pressure-vessel binds the bus directly and Steam starts; the cost is that Steam can reach every name on the session bus | Drop once nixpak can expose its proxy at `$XDG_RUNTIME_DIR/bus` (or pressure-vessel stops nesting proxies), so the filtered bus comes back | 2026-11-14 | on a nixpak or Steam client update | active | +| WA-053 | rasdaemon exporter with `enabledCollectors = [ ]` — `modules/nixos/base/monitoring.nix` | nixpkgs' exporter module passes `--collector-` for each listed collector, but the exporter declares its default-on `aer`, `mce` and `mc` collectors with argparse `store_false`, so the module default (all three) turns them off and nothing is exported. Passing no flags keeps them on | Drop once nixpkgs passes no flag for a default-on collector, or the exporter makes the flags enable collectors | 2026-11-17 | on the next nixpkgs bump | active | If the KINGBANK KP260 NVMe freezes on `ai` recur (formerly WA-008, now back at the kernel's APST defaults), restore the parameters commented out in `hosts/idols-ai/hardware-configuration.nix` — diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/README.md b/hosts/12kingdoms-youko/homelab-services/monitoring/README.md index 2bc8c438..f4e31dce 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/README.md +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/README.md @@ -13,6 +13,19 @@ node_exporter's textfile collector after a successful run. `alert_rules/restic-backup.yml` alerts when it is older than two days (the schedule is daily) or absent entirely. +## HTTPS Probes + +`blackbox.nix` probes every named caddy vhost on youko over HTTPS; `alert_rules/blackbox.yml` alerts +on a failing probe and on a certificate that expires within 14 days. + +## Deploy State + +Physical hosts also publish, from `modules/nixos/base/monitoring.nix`: + +- `node_reboot_required`, for `HostRequiresReboot` in `alert_rules/node-exporter.yml`. +- `flake_input_last_modified{input,rev}` of the running generation, for + `alert_rules/flake-inputs.yml`: nixpkgs older than 30 days, or a week behind the newest host. + ## TODO - **Dead-man switch**: `Watchdog` in `alert_rules/general.yml` always fires (`vector(1)`) but is diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert.nix b/hosts/12kingdoms-youko/homelab-services/monitoring/alert.nix index 3f092fcb..2fe7dd92 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/alert.nix +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert.nix @@ -1,4 +1,27 @@ -{ config, mylib, ... }: +{ + config, + lib, + pkgs, + mylib, + ... +}: +let + ruleGlobs = [ + "alert_rules/*.yml" + "alert_rules/*.yaml" + "recording_rules/*.yml" + "recording_rules/*.yaml" + ]; + # A rule vmalert cannot parse fails this build instead of the running service. + checkedRules = + pkgs.runCommand "vmalert-homelab-rules" { nativeBuildInputs = [ config.services.vmalert.package ]; } + '' + mkdir $out + cp -r ${./alert_rules} $out/alert_rules + cp -r ${./recording_rules} $out/recording_rules + vmalert -dryRun ${lib.concatMapStringsSep " " (glob: ''-rule="$out/${glob}"'') ruleGlobs} + ''; +in { # https://docs.victoriametrics.com/victoriametrics/vmalert/ services.vmalert.instances."homelab" = { @@ -18,12 +41,7 @@ # from URLs in log messages or UI and exported metrics. "datasource.showURL" = false; # Path to the files with alerting and/or recording rules. - rule = [ - "${./alert_rules}/*.yml" - "${./alert_rules}/*.yaml" - "${./recording_rules}/*.yml" - "${./recording_rules}/*.yaml" - ]; + rule = map (glob: "${checkedRules}/${glob}") ruleGlobs; # https://docs.victoriametrics.com/victoriametrics/vmalert/#link-to-alert-source # Set this two args to generate the correct `.GeneratorURL` "external.url" = "https://grafana.writefor.fun"; diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/blackbox.yml b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/blackbox.yml new file mode 100644 index 00000000..a7f35100 --- /dev/null +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/blackbox.yml @@ -0,0 +1,27 @@ +groups: + - name: blackbox.rules + rules: + # Probes of every caddy vhost on youko (monitoring/blackbox.nix): the Let's + # Encrypt wildcard that security.acme renews, and the private ecc-ca server + # certificate that is rotated by hand. + - alert: CertificateExpiry + expr: probe_ssl_earliest_cert_expiry - time() < 14 * 86400 + for: 15m + labels: + severity: warning + annotations: + summary: Certificate for {{ $labels.instance }} expires in {{ $value | humanizeDuration }} + description: + "Check `systemctl status acme-writefor.fun.service` on youko for the public wildcard, or + rotate certs/ecc-server.crt for the private one." + + - alert: HttpsEndpointDown + expr: probe_success{job="blackbox-https"} == 0 + for: 15m + labels: + severity: warning + annotations: + summary: "{{ $labels.instance }} is unreachable" + description: + "The HTTPS probe from youko fails (TLS, DNS or an unexpected status). Check caddy and + the backend service there." diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/flake-inputs.yml b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/flake-inputs.yml new file mode 100644 index 00000000..46b8ddb9 --- /dev/null +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/flake-inputs.yml @@ -0,0 +1,30 @@ +groups: + - name: flake-inputs.rules + rules: + # modules/nixos/base/monitoring.nix publishes the commit time and revision + # of the running generation's nixpkgs (physical hosts only). + - alert: NixpkgsOutOfDate + expr: (time() - flake_input_last_modified{input="nixpkgs"}) / 86400 > 30 + for: 1h + labels: + severity: warning + annotations: + summary: nixpkgs on {{ $labels.host }} is {{ $value | humanize }} days old + description: + "{{ $labels.host }} runs nixpkgs {{ $labels.rev }}. Update the flake lock and deploy it + to pick up security fixes." + + # A host that the last deploys skipped. + - alert: NixpkgsBehindFleet + expr: + (scalar(max(flake_input_last_modified{input="nixpkgs"})) - + flake_input_last_modified{input="nixpkgs"}) / 86400 > 7 + for: 1d + labels: + severity: warning + annotations: + summary: + nixpkgs on {{ $labels.host }} is {{ $value | humanize }} days behind the newest host + description: + "{{ $labels.host }} runs nixpkgs {{ $labels.rev }}, older than the newest nixpkgs + deployed to another host. Deploy it." diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/node-exporter.yml b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/node-exporter.yml index ca354f6a..899131f9 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/node-exporter.yml +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/node-exporter.yml @@ -93,18 +93,22 @@ groups: "Disk is probably writing too much data (> 50 MB/s)\n VALUE = {{ $value }}\n LABELS = {{ $labels }}" + # The absolute floor keeps multi-TB disks from alerting with hundreds of GiB + # left; a fast fill is HostDiskWillFillIn24Hours' job. - alert: HostOutOfDiskSpace expr: '((node_filesystem_avail_bytes * 100) / node_filesystem_size_bytes < 10 and ON (instance, - device, mountpoint) node_filesystem_readonly == 0) * on(instance) group_left (nodename) + device, mountpoint) node_filesystem_avail_bytes < 100 * 1024^3 and ON (instance, device, + mountpoint) node_filesystem_readonly == 0) * on(instance) group_left (nodename) node_uname_info{nodename=~".+"}' - for: 2m + for: 30m labels: severity: warning annotations: summary: Host out of disk space (instance {{ $labels.instance }}) description: - "Disk is almost full (< 10% left)\n VALUE = {{ $value }}\n LABELS = {{ $labels }}" + "Disk is almost full (< 10% and < 100 GiB left)\n VALUE = {{ $value }}\n LABELS = {{ + $labels }}" - alert: HostDiskWillFillIn24Hours expr: @@ -288,7 +292,8 @@ groups: expr: '(node_systemd_unit_state{state="failed"} == 1) * on(instance) group_left (nodename) node_uname_info{nodename=~".+"}' - for: 0m + # Skip failures that clear on their own (a retry, the next timer run). + for: 15m labels: severity: warning annotations: @@ -544,15 +549,33 @@ groups: "Clock not synchronising. Ensure NTP is configured on this host.\n VALUE = {{ $value }}\n LABELS = {{ $labels }}" + # Watchdog and panic reboots (modules/nixos/watchdog.nix) recover a host + # without anyone noticing; warning, because info never notifies. Headless + # servers only: desktops boot daily and MicroVM guests restart on deploys. + - alert: HostRebooted + expr: + '(time() - node_boot_time_seconds{host=~"aquamarine|shoryu|shushou|youko"} < 600) * + on(instance) group_left (nodename) node_uname_info{nodename=~".+"}' + labels: + severity: warning + annotations: + summary: Host rebooted (instance {{ $labels.instance }}) + description: + "{{ $labels.instance }} booted {{ $value | humanizeDuration }} ago. If nobody rebooted + it, check `journalctl -b -1` there for a panic or watchdog reset.\n LABELS = {{ $labels + }}" + + # node_reboot_required comes from modules/nixos/base/monitoring.nix + # (physical hosts only). A day leaves room for a planned `boot` deploy. - alert: HostRequiresReboot expr: '(node_reboot_required > 0) * on(instance) group_left (nodename) node_uname_info{nodename=~".+"}' - for: 4h + for: 1d labels: - severity: info + severity: warning annotations: summary: Host requires reboot (instance {{ $labels.instance }}) description: - "{{ $labels.instance }} requires a reboot.\n VALUE = {{ $value }}\n LABELS = {{ - $labels }}" + "{{ $labels.instance }} has a system profile whose kernel, initrd or kernel modules + differ from the booted ones; reboot it to run them.\n LABELS = {{ $labels }}" diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/rasdaemon.yml b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/rasdaemon.yml new file mode 100644 index 00000000..39aab4ed --- /dev/null +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/rasdaemon.yml @@ -0,0 +1,27 @@ +groups: + - name: rasdaemon.rules + rules: + # Counts per message from rasdaemon's database on the physical servers. + # Corrected errors need no action; uncorrected and deferred ones point at + # failing CPU, memory or PCIe hardware. + - alert: MachineCheckError + expr: increase(rasdaemon_mce_records_total{mce_msg!~"Corrected.*"}[1h]) > 0 + labels: + severity: critical + annotations: + summary: Machine check error on {{ $labels.host }} + description: + "{{ $labels.mce_msg }}. Inspect `ras-mc-ctl --errors` and `journalctl -k` on {{ + $labels.host }}." + + - alert: PcieUncorrectedError + expr: increase(rasdaemon_aer_events_total{aer_err_type!="Corrected"}[1h]) > 0 + labels: + severity: critical + annotations: + summary: + "{{ $labels.aer_err_type }} PCIe error on {{ $labels.host }} device {{ + $labels.aer_dev_name }}" + description: + "{{ $labels.aer_err_msg }}. Inspect `ras-mc-ctl --errors` and `journalctl -k` on {{ + $labels.host }}." diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/storage.yml b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/storage.yml index b0b3f3c4..7901cbea 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/storage.yml +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/alert_rules/storage.yml @@ -105,3 +105,19 @@ groups: summary: SATA SSD {{ $labels.device }} on {{ $labels.host }} wear indicator is low ({{ $value }}) description: "Wear_Leveling_Count normalized value below 20 (100 = new)." + + # btrfs keeps these per-device counters on disk across reboots; scrubs + # (services.btrfs.autoScrub) and normal I/O both raise them. The alert + # holds until the counters are reset after the cause is dealt with. + - alert: BtrfsDeviceErrors + expr: node_btrfs_device_errors_total > 0 + for: 5m + labels: + severity: critical + annotations: + summary: + btrfs on {{ $labels.host }} device {{ $labels.device }} has {{ $value }} {{ $labels.type + }} errors + description: + "Run `btrfs device stats` and check `journalctl -k` and the drive's SMART data on {{ + $labels.host }}; after the cause is fixed, reset with `btrfs device stats --reset`." diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/blackbox.nix b/hosts/12kingdoms-youko/homelab-services/monitoring/blackbox.nix new file mode 100644 index 00000000..0de1b7fa --- /dev/null +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/blackbox.nix @@ -0,0 +1,74 @@ +{ + config, + lib, + pkgs, + ... +}: +let + cfg = config.services.prometheus.exporters.blackbox; + + # Every named caddy vhost on this host; the `*.writefor.fun` catch-all only + # answers 404. + httpsTargets = map (name: "https://${name}/") ( + lib.filter (name: !lib.hasPrefix "*." name) (lib.attrNames config.services.caddy.virtualHosts) + ); +in +{ + # https://github.com/prometheus/blackbox_exporter/blob/master/CONFIGURATION.md + services.prometheus.exporters.blackbox = { + enable = true; + listenAddress = "127.0.0.1"; + configFile = (pkgs.formats.yaml { }).generate "blackbox.yml" { + modules.https_up = { + prober = "http"; + timeout = "10s"; + http = { + # The services resolve to this host's LAN IPv4. + preferred_ip_protocol = "ip4"; + ip_protocol_fallback = false; + fail_if_not_ssl = true; + # 401/403 come from the backend's own auth (restic, s3, webdav, + # transmission), so caddy and the service are both up. + valid_status_codes = [ + 200 + 401 + 403 + ]; + }; + }; + }; + }; + + services.victoriametrics.prometheusConfig.scrape_configs = [ + { + job_name = "blackbox-https"; + scrape_interval = "60s"; + metrics_path = "/probe"; + params.module = [ "https_up" ]; + static_configs = [ + { + targets = httpsTargets; + labels.type = "probe"; + labels.app = "caddy"; + labels.host = "youko"; + labels.env = "homelab"; + labels.cluster = "homelab"; + } + ]; + relabel_configs = [ + { + source_labels = [ "__address__" ]; + target_label = "__param_target"; + } + { + source_labels = [ "__param_target" ]; + target_label = "instance"; + } + { + target_label = "__address__"; + replacement = "127.0.0.1:${toString cfg.port}"; + } + ]; + } + ]; +} diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/default.nix b/hosts/12kingdoms-youko/homelab-services/monitoring/default.nix index 4bac8bae..81eb4fa9 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/default.nix +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/default.nix @@ -3,5 +3,6 @@ imports = [ ./victoriametrics.nix ./alert.nix + ./blackbox.nix ]; } diff --git a/hosts/12kingdoms-youko/homelab-services/monitoring/victoriametrics.nix b/hosts/12kingdoms-youko/homelab-services/monitoring/victoriametrics.nix index 65d9e864..1f4859e8 100644 --- a/hosts/12kingdoms-youko/homelab-services/monitoring/victoriametrics.nix +++ b/hosts/12kingdoms-youko/homelab-services/monitoring/victoriametrics.nix @@ -27,6 +27,10 @@ let "shushou" "youko" ]; + + # Physical servers run rasdaemon and its exporter on :10029 (hardware.rasdaemon + # in lib/genVmHostModule.nix and hosts/idols-aquamarine/default.nix). + rasdaemonHosts = lib.remove "ai" physicalHosts; in { # https://victoriametrics.io/docs/victoriametrics/latest/configuration/configuration/ @@ -263,7 +267,33 @@ in ]; } ] - ) [ ] (lib.attrsets.filterAttrs (n: _: builtins.elem n physicalHosts) myvars.networking.hostsAddr)); + ) [ ] (lib.attrsets.filterAttrs (n: _: builtins.elem n physicalHosts) myvars.networking.hostsAddr)) + # --- MCE / PCIe AER / memory errors (physical servers only) --- # + ++ (lib.attrsets.foldlAttrs + ( + acc: hostname: addr: + acc + ++ [ + { + job_name = "rasdaemon-${hostname}"; + scrape_interval = "60s"; + metrics_path = "/metrics"; + static_configs = [ + { + targets = [ "${addr.ipv4}:10029" ]; + labels.type = "rasdaemon"; + labels.app = "rasdaemon"; + labels.host = hostname; + labels.env = "homelab"; + labels.cluster = "homelab"; + } + ]; + } + ] + ) + [ ] + (lib.attrsets.filterAttrs (n: _: builtins.elem n rasdaemonHosts) myvars.networking.hostsAddr) + ); }; }; } diff --git a/hosts/README.md b/hosts/README.md index 946902de..d9cc2e74 100644 --- a/hosts/README.md +++ b/hosts/README.md @@ -180,8 +180,24 @@ qemu-kvm path; there are none right now. settings). Deploy serially (`-p 1`) and re-check VM reachability afterwards. - Use `boot` + a serial reboot for anything that can drop the network mid-flight — `systemd.network` / `br0` changes, nixpkgs updates, or any broad rebuild. +- `switch` enforces this through `system.switch.inhibitors` in + [genVmHostModule.nix](../lib/genVmHostModule.nix): when the kernel, its parameters or modules, the + initrd, systemd, `networkd.conf`, or the `br0` / uplink units change, `switch-to-configuration` + prints `There are changes to critical components of the system` and exits before installing the + boot loader, and Colmena reports the activation as failed. Colmena has already pointed the system + profile at the new generation, so rerun with `just boot` and reboot, or switch anyway on + the host with `NIXOS_NO_CHECK=1 /nix/var/nix/profiles/system/bin/switch-to-configuration switch`. - If a host loses VM networking, check `br0` and the VM taps, or reboot the host. +## Boot Recovery on Physical Servers + +`shoryu`, `shushou`, `youko` (systemd-boot) and `aquamarine` (Lanzaboote) write each new generation +with a boot counter. After 3 boots that never reach `boot-complete.target` (ordered after +`sysinit.target`), the entry is marked bad and the boot loader starts the newest good one. The root +LUKS volume unlocks through TPM2 alone, so retries need no console. Failures later in boot, such as +a broken `br0`, do not count, and a hung boot retries only after a reboot or power cycle. +`bootctl list` shows each entry's remaining tries. + ## Common Build Commands Use the Just recipes for host configuration checks and builds: diff --git a/hosts/idols-aquamarine/default.nix b/hosts/idols-aquamarine/default.nix index ecebf4ed..e261e21c 100644 --- a/hosts/idols-aquamarine/default.nix +++ b/hosts/idols-aquamarine/default.nix @@ -19,6 +19,7 @@ in { imports = [ disko.nixosModules.default + ../../modules/nixos/hardware-health.nix ../../modules/nixos/headless-recovery.nix ../../modules/nixos/power.nix ../../modules/nixos/watchdog.nix @@ -39,6 +40,9 @@ in ./idle-suspend.nix ]; + # A failed initrd drops to a root shell behind the root password (docs/SECURITY.md). + boot.initrd.systemd.emergencyAccess = myvars.initialHashedPassword; + # Bind the board's NCT6798D SuperIO, otherwise fan RPM and board temperatures # are missing. boot.kernelModules = [ "nct6775" ]; diff --git a/hosts/idols-aquamarine/secureboot.nix b/hosts/idols-aquamarine/secureboot.nix index 9547e4e2..abe86d99 100644 --- a/hosts/idols-aquamarine/secureboot.nix +++ b/hosts/idols-aquamarine/secureboot.nix @@ -26,5 +26,7 @@ boot.lanzaboote = { enable = true; pkiBundle = "/etc/secureboot"; + # Retries need no console: root LUKS unlocks through TPM2 alone (hosts/README.md). + bootCounting.initialTries = 3; }; } diff --git a/lib/genVmHostModule.nix b/lib/genVmHostModule.nix index ff75f447..63a93824 100644 --- a/lib/genVmHostModule.nix +++ b/lib/genVmHostModule.nix @@ -9,9 +9,16 @@ let inherit (networking.hostsAddr.${hostName}) iface ipv4; ipv4WithMask = "${ipv4}/24"; in +{ + config, + lib, + myvars, + ... +}: { # CPU policy belongs to physical hosts; guests do not control hardware frequency. imports = [ + ../modules/nixos/hardware-health.nix ../modules/nixos/headless-recovery.nix ../modules/nixos/power.nix ../modules/nixos/watchdog.nix @@ -30,6 +37,12 @@ in "nfs" ]; + # Retries need no console: root LUKS unlocks through TPM2 alone (hosts/README.md). + boot.loader.systemd-boot.bootCounting.enable = true; + + # A failed initrd drops to a root shell behind the root password (docs/SECURITY.md). + boot.initrd.systemd.emergencyAccess = myvars.initialHashedPassword; + # KVM for the microVMs and the libvirt domains. AMD-specific: an Intel VM host # would need kvm-intel instead (see hosts/idols-ai/hardware-intel.nix). boot.kernelModules = [ "kvm-amd" ]; @@ -150,6 +163,22 @@ in }; }; + # `switch` refuses changes that only a reboot applies or that can drop br0 mid-flight; deploy + # those with `boot` (hosts/README.md). Guest tap units are left out so a new guest still switches. + system.switch.inhibitors = { + kernel = toString config.system.build.kernel; + kernel-params = toString config.boot.kernelParams; + kernel-modules = toString config.system.modulesTree; + initrd = toString config.system.build.initialRamdisk; + systemd = toString config.systemd.package; + } + // lib.genAttrs [ + "systemd/networkd.conf" + "systemd/network/10-br0.netdev" + "systemd/network/10-br0.network" + "systemd/network/20-${iface}.network" + ] (name: toString config.environment.etc.${name}.source); + # systemd-journal - cap disk usage, but keep plenty of history on the big # persistent disk (/var/log is preserved to /persistent). # https://www.freedesktop.org/software/systemd/man/latest/journald.conf.html diff --git a/modules/nixos/base/monitoring.nix b/modules/nixos/base/monitoring.nix index 27c61250..6e117d31 100644 --- a/modules/nixos/base/monitoring.nix +++ b/modules/nixos/base/monitoring.nix @@ -1,6 +1,9 @@ { config, lib, + pkgs, + inputs, + mylib, myvars, ... }: @@ -21,6 +24,18 @@ let lanExporters = lib.filterAttrs (_: cfg: cfg.enable) { inherit (config.services.prometheus.exporters) node smartctl nvidia-gpu; }; + + # Deploy-state metrics are published by physical hosts only (hardwareTools is + # off on VM guests). + publishDeployState = + config.services.prometheus.exporters.node.enable && config.modules.hardwareTools.enable; + + # nixpkgs only: any other input would rebuild every host whenever it moves. + flakeInputsProm = pkgs.writeText "flake-inputs.prom" '' + # HELP flake_input_last_modified Commit time of a flake input of the running generation. + # TYPE flake_input_last_modified gauge + flake_input_last_modified{input="nixpkgs",rev="${inputs.nixpkgs.rev}"} ${toString inputs.nixpkgs.lastModified} + ''; in { # node_exporter on every host that has a static LAN IPv4 (see `lanAddr` above) @@ -67,9 +82,43 @@ in # Created here so the textfile collector has somewhere to read from before # the first successful backup writes its metric. - systemd.tmpfiles.rules = lib.mkIf (lanAddr != null) [ - "d ${textfileDir} 0755 root root - -" - ]; + systemd.tmpfiles.rules = lib.mkIf (lanAddr != null) ( + [ "d ${textfileDir} 0755 root root - -" ] + ++ lib.optional publishDeployState "L+ ${textfileDir}/flake-inputs.prom - - - - ${flakeInputsProm}" + ); + + # node_reboot_required for the HostRequiresReboot alert. Compare against the + # system profile, not /run/current-system: a `boot` deploy only moves the + # profile. Same comparison as nixpkgs' system.autoUpgrade.allowReboot. + systemd.services.node-reboot-required = lib.mkIf publishDeployState { + description = "Report whether the next boot changes the kernel, initrd or modules"; + serviceConfig = mylib.systemdHardening.mkDefaults mylib.systemdHardening.service // { + Type = "oneshot"; + ReadWritePaths = [ textfileDir ]; + }; + path = [ pkgs.coreutils ]; + script = '' + booted="$(readlink /run/booted-system/{initrd,kernel,kernel-modules})" + built="$(readlink /nix/var/nix/profiles/system/{initrd,kernel,kernel-modules})" + required=0 + if [ "$booted" != "$built" ]; then + required=1 + fi + { + echo '# HELP node_reboot_required 1 if the system profile boots another kernel, initrd or kernel modules.' + echo '# TYPE node_reboot_required gauge' + echo "node_reboot_required $required" + } > ${textfileDir}/reboot-required.prom.tmp + mv -f ${textfileDir}/reboot-required.prom.tmp ${textfileDir}/reboot-required.prom + ''; + }; + systemd.timers.node-reboot-required = lib.mkIf publishDeployState { + wantedBy = [ "timers.target" ]; + timerConfig = { + OnBootSec = "1min"; + OnUnitActiveSec = "15min"; + }; + }; # Drive SMART health (wear, spare, media errors, temperature, bytes written) # on physical hosts. node_exporter's nvme collector only exposes @@ -86,6 +135,28 @@ in extraFlags = [ "--web.systemd-socket" ]; }; + # MCE, AER and memory-controller error counts from rasdaemon's database, on + # hosts that run rasdaemon. + services.prometheus.exporters.rasdaemon = + lib.mkIf (lanAddr != null && config.hardware.rasdaemon.enable) + { + enable = true; + listenAddress = lanAddr; + port = 10029; + # No flags: each flag turns off one of the default aer/mce/mc collectors + # (WA-053 in docs/WORKAROUNDS.md). + enabledCollectors = [ ]; + }; + # This Python exporter cannot take a systemd socket, so it binds the LAN + # address itself and retries until the address exists and rasdaemon has + # created its database. + systemd.services.prometheus-rasdaemon-exporter = + lib.mkIf config.services.prometheus.exporters.rasdaemon.enable + { + after = [ "rasdaemon.service" ]; + serviceConfig.RestartSec = "5s"; + }; + # Socket activation with FreeBind: the LAN address may not exist yet at boot. systemd.sockets = lib.mkIf (lanAddr != null) ( lib.mapAttrs' ( diff --git a/modules/nixos/base/networking/firewall.nix b/modules/nixos/base/networking/firewall.nix index 9b6affd8..5dc93ab5 100644 --- a/modules/nixos/base/networking/firewall.nix +++ b/modules/nixos/base/networking/firewall.nix @@ -1,8 +1,14 @@ -{ lib, myvars, ... }: +{ + config, + lib, + myvars, + ... +}: let inherit (myvars.networking) lanCidr; # The host that scrapes the exporters (VictoriaMetrics runs on youko). monitoringHost = myvars.networking.hostsAddr.youko.ipv4; + rasdaemonExporter = config.services.prometheus.exporters.rasdaemon; in { # Hosts bring their own firewall as defence in depth behind the router's @@ -32,6 +38,14 @@ in # smartctl_exporter (drive/SSD SMART health) is scraped only by the # monitoring host. ip saddr != ${monitoringHost} tcp dport 9633 drop + '' + + lib.optionalString rasdaemonExporter.enable '' + + # rasdaemon's exporter (physical servers), likewise; it also drops IPv6. + ip saddr != ${monitoringHost} tcp dport ${toString rasdaemonExporter.port} drop + meta nfproto ipv6 tcp dport ${toString rasdaemonExporter.port} drop + '' + + '' # Monitoring uses the stable IPv4 address above. Deny IPv6 exporter # connections before broad LAN/tailnet/container trust can accept them; diff --git a/modules/nixos/hardware-health.nix b/modules/nixos/hardware-health.nix new file mode 100644 index 00000000..1b6e132d --- /dev/null +++ b/modules/nixos/hardware-health.nix @@ -0,0 +1,15 @@ +{ lib, ... }: +{ + # Monthly scrub of every btrfs filesystem; errors show up in node_btrfs_device_errors_total. + # Start between 04:00 and 05:00, after the 01:30-03:45 backup window (docs/BACKUP.md): + # nixpkgs' AccuracySec of 1d could otherwise place it anywhere in the day. + services.btrfs.autoScrub = { + enable = true; + interval = "*-*-01 04:00:00"; + }; + systemd.timers."btrfs-scrub@".timerConfig.AccuracySec = lib.mkForce "1h"; + + # Record machine-check, PCIe AER and memory errors; exported to VictoriaMetrics by + # modules/nixos/base/monitoring.nix. Its database lives in the preserved /var/lib. + hardware.rasdaemon.enable = true; +}