config/modules/base/unitstatus/default.nix

61 lines
1.6 KiB
Nix
Raw Permalink Normal View History

2023-07-20 06:58:47 +03:00
{
config,
lib,
pkgs,
...
2024-07-29 15:39:54 +03:00
}:
{
2023-07-20 06:58:47 +03:00
# TODO:
# - assert postfix is configured
options.mj.base.unitstatus = with lib.types; {
enable = lib.mkEnableOption "alert by email on unit failure";
2024-07-29 15:39:54 +03:00
email = lib.mkOption { type = str; };
2023-08-15 07:09:11 +03:00
units = lib.mkOption {
type = listOf str;
2024-07-29 15:39:54 +03:00
default = [ ];
2023-08-15 07:09:11 +03:00
};
2023-07-20 06:58:47 +03:00
};
config = lib.mkIf config.mj.base.unitstatus.enable {
systemd.services =
{
2024-07-29 15:39:54 +03:00
"unit-status-mail@" =
let
# https://northernlightlabs.se/2014-07-05/systemd-status-mail-on-unit-failure.html
script = pkgs.writeShellScript "unit-status-mail" ''
set -e
MAILTO="${config.mj.base.unitstatus.email}"
UNIT=$1
EXTRA=""
for e in "''${@:2}"; do
EXTRA+="$e"$'\n'
done
2024-09-17 11:47:47 +03:00
UNITSTATUS=$(${pkgs.systemd}/bin/systemctl status -l -n 1000 "$UNIT" || :)
2024-07-29 15:39:54 +03:00
${pkgs.postfix}/bin/sendmail $MAILTO <<EOF
Subject:Status mail for unit: $UNIT
2023-07-20 06:58:47 +03:00
2024-07-29 15:39:54 +03:00
Status report for unit: $UNIT
$EXTRA
2023-07-20 06:58:47 +03:00
2024-07-29 15:39:54 +03:00
$UNITSTATUS
EOF
2023-07-20 06:58:47 +03:00
2024-07-29 15:39:54 +03:00
echo -e "Status mail sent to: $MAILTO for unit: $UNIT"
'';
in
{
description = "Send an email on unit failure";
serviceConfig = {
Type = "simple";
ExecStart = ''${script} "%i" "Hostname: %H" "Machine ID: %m" "Boot ID: %b" '';
};
};
}
2024-07-29 15:39:54 +03:00
// lib.genAttrs config.mj.base.unitstatus.units (unit: {
unitConfig = {
OnFailure = "unit-status-mail@${unit}.service";
};
});
};
2023-07-20 06:58:47 +03:00
}