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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
{ config, lib, pkgs, ... }:
let
cfg = config.services.vnstati;
in {
options.services.vnstati = with lib; {
enable = mkEnableOption "just some fancy traffic pics";
title = mkOption {
type = types.str;
default = "${if config.networking ? domain then config.networking.hostName else config.networking.fqdn}";
};
domain = mkOption {
type = types.str;
default = "${config.networking.fqdn}";
};
subdirectory = mkOption {
type = types.str;
default = "/traffic/";
};
};
config = lib.mkIf cfg.enable {
assertions = [
({
assertion = config.services.vnstat.enable;
message = "vnstati requires vnstat.enable == true";
})
];
fileSystems."/var/lib/vnstati" = {
device = "tmpfs";
fsType = "tmpfs";
options = [ "rw" "size=30M" ];
};
services.nginx.virtualHosts.${cfg.domain} = {
locations.${cfg.subdirectory} = {
alias = "/var/lib/vnstati/";
index = "index.html";
};
};
systemd.services.vnstati = {
wantedBy = [ "multi-user.target" ];
after = [ "var-lib-vnstati.mount" "vnstat.service" ];
startAt = "*-*-* *:0/10:00";
path = with pkgs; [ vnstat jq nix ];
serviceConfig = {
User = "vnstatd";
Group = "vnstatd";
StateDirectory = "vnstati";
PrivateTmp = true;
ProtectHome = true;
ProtectSystem = "strict";
};
script = ''
set -x
ifaces=$(vnstat --json | jq -r .interfaces[].name | grep -v "^lo$")
echo $ifaces
nix eval -I nixpkgs=${lib.cleanSource pkgs.path} --raw -f ${./vnstati-html.nix} html \
--argstr ifaces "$ifaces" \
--argstr hostname "${cfg.title}" \
> /var/lib/vnstati/index.html
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
'';
};
};
}