iac/nixos/modules/monitoring-agent.nix
Sergei Poljanski 368393eaca
All checks were successful
nixos / nixos (push) Successful in 21s
until comin status --json | jq -e '.deployer.deployment.generation.selected_commit_id == "$H" and (.deployer.deployment.status == "done" or .deployer.deployment.status == "failed")' >/dev/null; do sleep 10; done
comin status --json | jq -r '.deployer.deployment.status'
loginctl list-users --no-legend | awk '{print \$2, \$3}' | tr '\n' ' '; echo
ls /var/lib/systemd/linger
EOF
git log --oneline -1
nixos: keep the login users' systemd managers running (linger)

Every SSH login starts a user's systemd manager and the logout stops it:
a git push as git, a CI deploy, an admin session. A switch that reloads
user units while one is starting or stopping fails with status 4
although the system did switch, and comin reports the deployment as
failed; at 08:50 a push as git did this on ops and the "Deploy failing"
alert mailed. With linger the managers run permanently.

Assisted-by: Claude:opus-5-5
2026-11-17 13:11:13 +04:00

289 lines
9 KiB
Nix

# What every host reports: node metrics, container metrics, its logs to
# Loki on asxpio-ops, and its security state (peers, devices on the
# private network, accounts, listening ports, privileged containers).
# Everything listens on the private address only; Prometheus on ops
# scrapes it.
{
config,
lib,
pkgs,
...
}:
let
ip = config.asxpio.privateIPv4;
sec = config.asxpio.security;
textfile = "/var/lib/node_exporter/textfile";
securityConfig = pkgs.writeText "security-metrics.json" (
builtins.toJSON {
textfile = "${textfile}/security.prom";
vpc_network = "10.10.0.0/20";
vpc_hosts = [
"10.10.0.1"
"10.10.0.10"
"10.10.0.20"
];
wg_peer_keys = lib.listToAttrs (
map (p: lib.nameValuePair p.publicKey p.name) config.asxpio.wireguard.peers
);
login_users = sec.loginUsers;
groups = {
wheel = sec.adminUsers;
podman = sec.adminUsers ++ sec.podmanUsers;
};
ports = sec.ports;
containers = sec.containers;
# Files a deploy does not rewrite; the rest of /etc is the Nix store
filesets = {
accounts = [
"/etc/passwd"
"/etc/shadow"
"/etc/group"
];
authorized_keys = [ "/etc/ssh/authorized_keys.d/*" ];
host_keys = [ "/etc/ssh/ssh_host_*" ];
};
forgejo_db = sec.forgejoDb;
}
);
alloyConfig = pkgs.writeText "config.alloy" ''
// Logs of this host to Loki.
discovery.docker "containers" {
host = "unix:///run/podman/podman.sock"
}
discovery.relabel "containers" {
targets = discovery.docker.containers.targets
rule {
source_labels = ["__meta_docker_container_name"]
regex = "/(.*)"
target_label = "container"
}
rule {
source_labels = ["__meta_docker_container_label_com_docker_compose_project"]
target_label = "compose_project"
}
rule {
source_labels = ["__meta_docker_container_label_com_docker_compose_service"]
target_label = "compose_service"
}
}
loki.source.docker "containers" {
host = "unix:///run/podman/podman.sock"
targets = discovery.docker.containers.targets
relabel_rules = discovery.relabel.containers.rules
labels = { job = "docker" }
forward_to = [loki.process.containers.receiver]
}
loki.process "containers" {
// CI job containers are many, short-lived and noisy: the runner logs suffice
stage.match {
selector = "{container=~\"FORGEJO-ACTIONS-TASK-.*\"}"
action = "drop"
}
forward_to = [loki.write.default.receiver]
}
loki.relabel "journal" {
forward_to = []
rule {
source_labels = ["__journal__systemd_unit"]
target_label = "unit"
}
// Every SSH login (CI deploys) gets its own session-N.scope: one
// stream each blew Loki's active stream limit.
rule {
source_labels = ["unit"]
regex = "session-\\d+\\.scope"
target_label = "unit"
replacement = "session.scope"
}
rule {
source_labels = ["__journal_priority_keyword"]
target_label = "level"
}
}
loki.source.journal "journal" {
max_age = "12h"
relabel_rules = loki.relabel.journal.rules
labels = { job = "journal" }
forward_to = [loki.write.default.receiver]
}
${lib.optionalString config.services.traefik.enable ''
local.file_match "traefik" {
path_targets = [{ "__path__" = "/var/log/traefik/access.log", job = "traefik-access" }]
}
loki.source.file "traefik" {
targets = local.file_match.traefik.targets
forward_to = [loki.write.default.receiver]
}
''}
loki.write "default" {
endpoint {
url = "http://10.10.0.10:3100/loki/api/v1/push"
}
external_labels = { host = "${config.asxpio.backup.hostName}" }
}
'';
in
{
options.asxpio.privateIPv4 = lib.mkOption {
type = lib.types.str;
description = "This host's address on the private network.";
};
options.asxpio.security = {
loginUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Accounts that may have a login shell.";
};
adminUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"asxpi"
"deploy"
"zerrtika"
];
};
podmanUsers = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Service users allowed on the container socket.";
};
ports = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Expected listening sockets outside loopback: proto/port/process.";
};
containers = lib.mkOption {
type = lib.types.attrsOf (lib.types.listOf lib.types.str);
default = { };
description = "Containers allowed host-level access: name pattern to flags.";
};
forgejoDb = lib.mkOption {
type = lib.types.str;
default = "";
};
};
config = {
# Their systemd user managers run permanently. Otherwise each SSH
# login (a git push as git, a CI deploy, an admin session) starts
# and stops one, and a switch that reloads user units at that moment
# fails with status 4 although the system switched; comin then
# reports the deployment as failed.
users.users = lib.genAttrs config.asxpio.security.loginUsers (_: {
linger = true;
});
asxpio.security.loginUsers = [
"root"
"asxpi"
"deploy"
"zerrtika"
];
asxpio.security.ports = [
"tcp/22/sshd"
"udp/${toString config.asxpio.wireguard.listenPort}/"
"tcp/12345/alloy"
"tcp/9100/node_exporter"
"tcp/9180/cadvisor"
"udp/68/systemd-network" # DHCP
];
systemd.tmpfiles.rules = [ "d ${textfile} 0755 root root -" ];
# When this host last activated a NixOS configuration (deploy or
# boot). Activations rewrite accounts and authorized_keys by design;
# the "Access files changed" alert stays quiet around them and still
# fires for a change outside a deploy, which here means a hand edit.
system.activationScripts.activationMetric = {
deps = [ ];
text = ''
mkdir -p ${textfile}
printf '# HELP nixos_activation_timestamp_seconds Last NixOS activation (deploy or boot).\n# TYPE nixos_activation_timestamp_seconds gauge\nnixos_activation_timestamp_seconds %s\n' "$(${pkgs.coreutils}/bin/date +%s)" > ${textfile}/nixos.prom.tmp
mv ${textfile}/nixos.prom.tmp ${textfile}/nixos.prom
'';
};
services.prometheus.exporters.node = {
enable = true;
listenAddress = ip;
port = 9100;
enabledCollectors = [ "textfile" ];
extraFlags = [
"--collector.textfile.directory=${textfile}"
"--collector.filesystem.mount-points-exclude=^/(dev|proc|run|sys|var/lib/containers/.+)($|/)"
];
};
services.cadvisor = {
enable = true;
listenAddress = ip;
port = 9180;
extraOptions = [
"--podman=unix:///run/podman/podman.sock"
"--docker_only=true"
"--housekeeping_interval=30s"
"--store_container_labels=false"
"--whitelisted_container_labels=com.docker.compose.project,com.docker.compose.service"
"--disable_metrics=percpu,sched,tcp,udp,hugetlb,referenced_memory,cpu_topology,resctrl,advtcp,process"
];
};
services.alloy = {
enable = true;
configPath = alloyConfig;
extraFlags = [ "--server.http.listen-addr=${ip}:12345" ];
};
# They bind the private address: wait for it, and retry
systemd.services = lib.mkMerge [
(lib.genAttrs [ "prometheus-node-exporter" "cadvisor" "alloy" ] (_: {
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Restart = lib.mkForce "always";
RestartSec = lib.mkForce 5;
};
}))
{
alloy.serviceConfig.SupplementaryGroups = [
"podman"
"systemd-journal"
]
++ lib.optional config.services.traefik.enable "traefik";
}
{
security-metrics = {
description = "Security state for Prometheus (node_exporter textfile)";
path = [
pkgs.wireguard-tools
pkgs.iproute2
pkgs.coreutils
pkgs.docker-client # `docker ps` / `docker inspect`, against Podman
];
environment.DOCKER_HOST = "unix:///run/podman/podman.sock";
serviceConfig = {
Type = "oneshot";
ExecStart = "${pkgs.python3}/bin/python3 ${./security-metrics.py} ${securityConfig}";
# Runs every minute: keep "Starting/Finished" out of the journal
LogLevelMax = "notice";
};
};
}
];
systemd.timers.security-metrics = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "minutely";
AccuracySec = "5s";
};
};
};
}