feat(monitoring): close host and service monitoring gaps (#530)

Assisted-by: DeepSeek Harness (claude-opus-5-5)
This commit is contained in:
ryan4yin | 二花 authored and GitHub committed 2026-11-17 21:08:02 +08:00
1 parent 667fd76cac
commit 6b425fe036
21 files changed
+452 -23

No files matched your search

+5
View File
@@ -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",
]
+3 -1
View File
@@ -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
+13 -2
View File
@@ -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 |
+1
View File
@@ -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//<pkg>`, 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-<name>` 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` —
@@ -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
@@ -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";
@@ -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."
@@ -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."
@@ -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 }}"
@@ -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 }}."
@@ -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`."
@@ -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}";
}
];
}
];
}
@@ -3,5 +3,6 @@
imports = [
./victoriametrics.nix
./alert.nix
./blackbox.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)
);
};
};
}
+16
View File
@@ -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 <host> 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:
+4
View File
@@ -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" ];
+2
View File
@@ -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;
};
}
+29
View File
@@ -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
+74 -3
View File
@@ -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' (
+15 -1
View File
@@ -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;
+15
View File
@@ -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;
}