aboutsummaryrefslogtreecommitdiff
path: root/modules/scripts/zquota/default.nix
blob: cc0f08fc4dbaabf09570d9f652531eefbcfbc61e (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.services.zquota;

  zquota = let hostname = config.networking.hostName; in
    pkgs.writeShellScriptBin "zquota" ''
      #!/usr/bin/env bash

      set -eu

      if [ "$#" -ne 2 ]; then
        echo "failed to provide both a dataset and quota" >&2
        exit 1
      fi

      DATASET="$1"
      QUOTA="$2"

      if [ -n "$(echo "$QUOTA" | tr -d 0-9.)" ]; then
        echo "failed to provide a valid quota" >&2
        exit 1
      fi

      USED=$(${getExe pkgs.zfs} list -Hpo used "$DATASET" 2>/dev/null) || {
        echo "failed to provide a valid dataset" >&2
        exit 1
      }

      USAGE=$(${getExe pkgs.bc} <<< "scale=2; $USED / 1024^3")

      DIFF=$(${getExe pkgs.bc} <<< "scale=2; $USAGE - $QUOTA")

      (( $(awk '{ print ($1 > $2) }' <<< "$USAGE $QUOTA") )) &&
        /run/current-system/sw/bin/pushover -t "${hostname} quota exceeded" \
        "dataset $DATASET on ${hostname} has exceeded quota by ''${DIFF}GB"
    '';
in
{
  options = {
    services.zquota = {
      enable = mkEnableOption "zquota";
      quotas = mkOption {
        default = { };
        type = types.attrsOf types.int;
        description = "Attribute set of ZFS dataset and disk quota (in GB).";
      };
      dates = mkOption {
        default = "daily";
        type = types.str;
        description = ''
          How often quota checks are performed.

          This value must be a calendar event specified by
          {manpage}`systemd.time(7)`.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    environment.systemPackages = [ zquota ];

    systemd.services."zquota" = {
      description = "Perform and report scheduled quota checks on ZFS datasets.";
      serviceConfig.Type = "oneshot";
      script =
        strings.concatStringsSep "\n" (
          mapAttrsToList (
            dataset: quota: "/run/current-system/sw/bin/zquota ${dataset} ${builtins.toString quota}"
          ) cfg.quotas
        );
    };
    systemd.timers."zquota" = {
      wantedBy = [ "timers.target" ];
      timerConfig = {
        OnCalendar = cfg.dates;
        Persistent = true;
      };
    };
  };
}