summaryrefslogtreecommitdiff
path: root/modules/nixos/personal/monitoring.nix
blob: e5797fbb463f036c457550689103c8c46f86f9ae (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
56
57
58
59
60
61
62
63
64
65
66
67
68
{
  config,
  lib,
  pkgs,
  ...
}:
let
  cfg = config.personal.monitoring;
in
{
  options = {
    personal.monitoring.enable = lib.mkEnableOption "e-mail monitoring of systemd services";
    systemd.services = lib.mkOption {
      type =
        with lib.types;
        attrsOf (
          submodule (
            {
              name,
              config,
              lib,
              ...
            }:
            {
              options.personal.monitor = lib.mkEnableOption "e-mail monitoring for the ${name} seervice";
              config.onFailure = lib.optional config.personal.monitor "notify@%i.service";
            }
          )
        );
    };
  };

  config = lib.mkIf cfg.enable {
    programs.msmtp = {
      enable = true;
      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."notify@" = lib.mkDefault {
      description = "Send the status of the %i service as an e-mail.";
      serviceConfig.type = "oneshot";
      scriptArgs = "%i";
      script =
        let
          netCfg = config.networking;
          host = "${builtins.toString netCfg.hostName}.${builtins.toString netCfg.domain}";
        in
        ''
             service="$1"
          echo \
          "Subject: ${host}: service $service failed
          Service $soervice failed on ${host}, with the following log:

          $(journalctl --no-pager --unit $service --since -1h)
          " | ${pkgs.msmtp}/bin/msmtp quentin@aristote.fr
        '';
    };
  };
}