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
{ config, pkgs, lib, ... }:

# A daily ncdu disk usage index of the whole system, browsable over ssh with
# `ncdu-ui [name]`. rolery runs its own per-user variant, see the ncdu-index
# user service in rolery.nix; the script is shared, see ncdu-index-script.nix.

let
  cfg = config.profpatsch.ncdu;
  cacheDir = "/var/cache/ncdu";

  script = import ./ncdu-index-script.nix { inherit pkgs lib; } {
    inherit cacheDir;
    inherit (cfg) roots threads;
    defaultRoot = "root";
  };
in
{
  options.profpatsch.ncdu = {
    enable = lib.mkEnableOption "a daily ncdu disk usage index (browse with `ncdu-ui [name]`)";
    roots = lib.mkOption {
      type = lib.types.attrsOf lib.types.str;
      default = { root = "/"; };
      description = ''
        Name → directory to index, one export /var/cache/ncdu/<name>.ncdu each.
        ncdu runs with -x, so each root stays on its own filesystem; list every
        data filesystem you want to see.
      '';
    };
    threads = lib.mkOption {
      type = lib.types.int;
      default = 2;
      description = "ncdu scan threads (-t).";
    };
  };

  # The scan re-walks every root, so it runs at idle CPU/IO priority. The
  # servers have 3 GB RAM; MemoryHigh throttles (does not kill) the walk and
  # mostly squeezes reclaimable page cache.
  config = lib.mkIf cfg.enable {
    environment.systemPackages = [ script.ui ];

    systemd.services.ncdu-index = {
      description = "index disk usage with ncdu";
      serviceConfig = {
        Type = "oneshot";
        ExecStart = script.index;
        CacheDirectory = "ncdu";
        Nice = 19;
        CPUSchedulingPolicy = "idle";
        IOSchedulingClass = "idle";
        MemoryHigh = "512M";
      };
    };
    systemd.timers.ncdu-index = {
      description = "index disk usage once per day";
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = "daily";
        Persistent = true;
        RandomizedDelaySec = "1h";
        AccuracySec = "1h";
      };
    };
  };
}