summaryrefslogtreecommitdiff
path: root/modules/nixos/personal/monitoring.nix
blob: 8d72c3c9352908a40449973bf2c25d77c635b8b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
{ config, lib, pkgs, ... }:

let cfg = config.personal.monitoring;
in {
  options.personal.monitoring = {
    enable = lib.mkEnableOption "e-mail monitoring";
    services = lib.mkOption {
      type = with lib.types; listOf str;
      default = [ ];
      description = "The list of services whose failure should be notified.";
    };
  };

  config = {
    programs.msmtp = {
      enable = cfg.enable;
      accounts.default = {
        auth = true;
        tls = true;
        tls_starttls = false;
        host = "ssl0.ovh.net";
        port = 465;
        from = "quentin-machines@aristote.fr";
        user = "quentin-machines@aristote.fr";
        passwordeval = "cat /etc/msmtp/secrets";
      };
    };

    systemd.services = lib.mkIf cfg.enable (lib.mkMerge ([{
      "notify@" = {
        enable = true;
        description = "Send the status of the %i service as an e-mail.";
        serviceConfig = {
          Type = "oneshot";
          ExecStart = let
            netCfg = config.networking;
            me = "${netCfg.hostName}.${netCfg.domain}";
            script = pkgs.writeScript "notify" ''
              #!${pkgs.runtimeShell}
              service="$1"
              echo \
              "Subject: ${me}: service $service failed
              Service $service failed on ${me}, with the following status:

              $(systemctl status $service)
              " | ${pkgs.msmtp}/bin/msmtp quentin@aristote.fr
            '';
          in "${script} %i";
        };
      };
    }] ++ builtins.map
      (service: { "${service}".onFailure = [ "notify@%i.service" ]; })
      cfg.services));
  };
}