nixcfg/modules/nixos/services/systemd-email-notify/default.nix
Harald Hoyer 5b0cab98d5 feat(systems): enable email notifications on failure
- Added `emailOnFailure.enable` option to metacfg with a default of `false`.
- Enabled email notifications on failure for SGX and MX systems.
- Enhanced `systemd-email-notify` module to support the new configuration.
2025-11-14 07:42:28 +01:00

78 lines
1.8 KiB
Nix

{
config,
lib,
pkgs,
...
}:
with lib;
with lib.metacfg;
let
cfg = config.metacfg.emailOnFailure;
checkConditions = pkgs.writeScript "checkConditions" ''
#!/bin/sh
STATUS=$(systemctl status --full "$1")
case "$STATUS" in
*"activating (auto-restart) (Result: timeout)"*) exit 1 ;;
*) exit 0 ;;
esac
'';
sendmail = pkgs.writeScript "sendmail" ''
#!/bin/sh
${pkgs.system-sendmail}/bin/sendmail -t <<ERRMAIL
To: $1
From: ${config.systemd.email-notify.mailFrom}
Subject: Status of service $2
Content-Transfer-Encoding: 8bit
Content-Type: text/plain; charset=UTF-8
$(systemctl status --full "$2")
ERRMAIL
'';
in
{
options = {
metacfg.emailOnFailure = with types; {
enable = mkBoolOpt false "Whether or not to send mails on failure.";
};
systemd.email-notify.mailTo = mkOption {
type = types.str;
default = "admin";
description = "Email address to which the service status will be mailed.";
};
systemd.email-notify.mailFrom = mkOption {
type = types.str;
default = "admin";
description = "Email address from which the service status will be mailed.";
};
systemd.services = mkOption {
type =
with types;
attrsOf (submodule {
config.onFailure = [ "email@%n.service" ];
});
};
};
config = mkIf cfg.enable {
systemd.services."email@" = {
description = "Sends a status mail via sendmail on service failures.";
onFailure = mkForce [ ];
unitConfig = {
StartLimitIntervalSec = "5m";
StartLimitBurst = 1;
};
serviceConfig = {
ExecCondition = "${checkConditions} %i";
ExecStart = "${sendmail} ${config.systemd.email-notify.mailTo} %i";
Type = "oneshot";
};
};
};
}