2023-02-26 16:42:49 +01:00
|
|
|
{ pkgs, lib, config, ... }:
|
|
|
|
let
|
|
|
|
fromAddress = config.email.fromAddress;
|
|
|
|
fromIdentity = config.email.fromIdentity;
|
|
|
|
toAddress = config.email.adminEmail;
|
|
|
|
cfg = config.services.statusEmail;
|
|
|
|
in
|
|
|
|
{
|
|
|
|
options.services.statusEmail = {
|
|
|
|
enable = lib.mkEnableOption "Send systemd status e-mails";
|
|
|
|
};
|
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
config = lib.mkIf cfg.enable {
|
|
|
|
email.enable = true;
|
|
|
|
systemd.services."status-email@" = let
|
|
|
|
sendStatusEmail = pkgs.writeScript "send-status-email" ''
|
|
|
|
#!${pkgs.bash}/bin/bash
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
from="${fromIdentity}"
|
|
|
|
to="${toAddress}"
|
|
|
|
service="$1"
|
|
|
|
full_status="$(systemctl status --full --lines 200 "$service")"
|
2024-04-27 14:36:36 +02:00
|
|
|
exit_code="$(echo "$full_status" | head -n5 | tail -1 | sed -e 's/.*ExecStart=.*status=\(.*\))$/\1/g')"
|
2023-03-07 19:35:34 +01:00
|
|
|
# state="$(systemctl is-failed "$service")"
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
fail_priority=1
|
|
|
|
fail_subject="Unit \"$service\" failure report (exit code $exit_code)"
|
|
|
|
success_priority=3
|
|
|
|
success_subject="Unit \"$service\" report (success)"
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
shift
|
|
|
|
while [ $# -gt 0 ] ; do
|
|
|
|
case "$1" in
|
|
|
|
'-s'|'--fail-subject')
|
|
|
|
fail_subject="$2"
|
|
|
|
shift 2
|
|
|
|
;;
|
|
|
|
'-p'|'--fail-priority')
|
|
|
|
fail_priority="$2"
|
|
|
|
shift 2
|
|
|
|
;;
|
|
|
|
*)
|
|
|
|
break
|
|
|
|
;;
|
|
|
|
esac
|
|
|
|
done
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
if [ "$exit_code" != "0/SUCCESS" ] ; then
|
|
|
|
subject="$fail_subject"
|
|
|
|
priority="$fail_priority"
|
|
|
|
else
|
|
|
|
subject="$success_subject"
|
|
|
|
priority="$success_priority"
|
|
|
|
fi
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
echo "Sending e-mail \"$subject\" to \"$to\"."
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
${pkgs.system-sendmail}/bin/sendmail -t -X - <<ERRMAIL
|
|
|
|
To: $to
|
|
|
|
From: $from
|
|
|
|
Subject: $subject
|
|
|
|
Content-Transfer-Encoding: 8bit
|
|
|
|
Content-Type: text/plain; charset=UTF-8
|
|
|
|
X-Priority: $priority
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
$full_status
|
2023-02-26 16:42:49 +01:00
|
|
|
|
2023-03-07 19:35:34 +01:00
|
|
|
ERRMAIL
|
|
|
|
'';
|
|
|
|
in
|
|
|
|
{
|
|
|
|
unitConfig = {
|
|
|
|
Description = "Send a status e-mail for %I";
|
|
|
|
};
|
|
|
|
serviceConfig = {
|
|
|
|
Type = "oneshot";
|
|
|
|
ExecStart = "${sendStatusEmail} %i";
|
|
|
|
};
|
2023-02-26 16:42:49 +01:00
|
|
|
};
|
|
|
|
};
|
|
|
|
}
|