default.nix 2.31 KB
Newer Older
Matthias Adamczyk's avatar
Matthias Adamczyk committed
1
2
3
{ config, lib, pkgs, ... }:

let
Matthias Adamczyk's avatar
Fix CI    
Matthias Adamczyk committed
4
  cfg = config.finf.vnstat;
Matthias Adamczyk's avatar
Matthias Adamczyk committed
5
6
7
8
9
10

in {
  imports = [
    ./nginx.nix
  ];

Matthias Adamczyk's avatar
Fix CI    
Matthias Adamczyk committed
11
  options.finf.vnstat = with lib; {
Matthias Adamczyk's avatar
Matthias Adamczyk committed
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    enable = mkEnableOption "just some fancy traffic pics";

    generateImages = mkOption {
      type = types.bool;
      default = true;
    };

    title = mkOption {
      type = types.str;
      default = "${config.networking.hostName}${if (config.networking ? domain) then ".${config.networking.domain}" else ""}";
    };
  };

  config = lib.mkIf cfg.enable {
    environment.systemPackages = with pkgs; [ vnstat ];
    services.vnstat.enable = true;

    systemd.services.vnstat-add-interfaces = {
      before = [ "vnstat.service" ];
      wantedBy = [ "multi-user.target" ];
      path = with pkgs; [ vnstat jq iproute gnugrep ];
      serviceConfig.Type = "oneshot";
      script = ''
        for iface in $(ip --json link | jq -r .[].ifname | grep -v "^lo$")
        do
          vnstat --add -i $iface || true
        done
      '';
    };

    systemd.services.vnstati = lib.mkIf cfg.generateImages {
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        User = "vnstatd";
        Group = "vnstatd";
        StateDirectory = "vnstati";
      };
      startAt = "*-*-* *:0/10:00";
      path = with pkgs; [ vnstat jq nix ];
      environment.NIX_PATH = "/etc/src";
      script = ''
        set -x
        ifaces=$(vnstat --json | jq -r .interfaces[].name | grep -v "^lo$")
        echo $ifaces

        nix eval --raw -f ${./vnstati-html.nix} html \
          --argstr ifaces "$ifaces" \
          --argstr hostname "${cfg.title}" \
          > /var/lib/vnstati/index.html

        rm -rf /var/lib/vnstati/static
        cp -r ${./vnstati-static} /var/lib/vnstati/static
        chmod u+rwX -R /var/lib/vnstati/static

        for iface in $ifaces
        do
          vnstati -s -nh -i $iface -o /var/lib/vnstati/$iface-summary.png
          vnstati -h -nh -i $iface -o /var/lib/vnstati/$iface-hourly.png
          vnstati -d -nh -i $iface -o /var/lib/vnstati/$iface-daily.png
          vnstati -m -nh -i $iface -o /var/lib/vnstati/$iface-monthly.png
          vnstati -t -nh -i $iface -o /var/lib/vnstati/$iface-top10.png
        done
      '';
    };

    users = lib.mkIf cfg.generateImages {
      groups.vnstatd = {};
      users.vnstatd.extraGroups = [ "vnstatd" ];
    };
  };
}