summary refs log tree commit diff
path: root/nixos/modules/services/backup/sanoid.nix
blob: 41d0e2e1df686cf86366234fc95a288053555ade (plain) (blame)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.sanoid;

  datasetSettingsType = with types;
    (attrsOf (nullOr (oneOf [ str int bool (listOf str) ]))) // {
      description = "dataset/template options";
    };

  commonOptions = {
    hourly = mkOption {
      description = "Number of hourly snapshots.";
      type = with types; nullOr ints.unsigned;
      default = null;
    };

    daily = mkOption {
      description = "Number of daily snapshots.";
      type = with types; nullOr ints.unsigned;
      default = null;
    };

    monthly = mkOption {
      description = "Number of monthly snapshots.";
      type = with types; nullOr ints.unsigned;
      default = null;
    };

    yearly = mkOption {
      description = "Number of yearly snapshots.";
      type = with types; nullOr ints.unsigned;
      default = null;
    };

    autoprune = mkOption {
      description = "Whether to automatically prune old snapshots.";
      type = with types; nullOr bool;
      default = null;
    };

    autosnap = mkOption {
      description = "Whether to automatically take snapshots.";
      type = with types; nullOr bool;
      default = null;
    };
  };

  datasetOptions = rec {
    use_template = mkOption {
      description = "Names of the templates to use for this dataset.";
      type = types.listOf (types.enum (attrNames cfg.templates));
      default = [ ];
    };
    useTemplate = use_template;

    recursive = mkOption {
      description = "Whether to recursively snapshot dataset children.";
      type = types.bool;
      default = false;
    };

    process_children_only = mkOption {
      description = "Whether to only snapshot child datasets if recursing.";
      type = types.bool;
      default = false;
    };
    processChildrenOnly = process_children_only;
  };

  # Extract unique dataset names
  datasets = unique (attrNames cfg.datasets);

  # Function to build "zfs allow" and "zfs unallow" commands for the
  # filesystems we've delegated permissions to.
  buildAllowCommand = zfsAction: permissions: dataset: lib.escapeShellArgs [
    # Here we explicitly use the booted system to guarantee the stable API needed by ZFS
    "-+/run/booted-system/sw/bin/zfs"
    zfsAction
    "sanoid"
    (concatStringsSep "," permissions)
    dataset
  ];

  configFile =
    let
      mkValueString = v:
        if builtins.isList v then concatStringsSep "," v
        else generators.mkValueStringDefault { } v;

      mkKeyValue = k: v:
        if v == null then ""
        else if k == "processChildrenOnly" then ""
        else if k == "useTemplate" then ""
        else generators.mkKeyValueDefault { inherit mkValueString; } "=" k v;
    in
    generators.toINI { inherit mkKeyValue; } cfg.settings;

in
{

  # Interface

  options.services.sanoid = {
    enable = mkEnableOption "Sanoid ZFS snapshotting service";

    interval = mkOption {
      type = types.str;
      default = "hourly";
      example = "daily";
      description = ''
        Run sanoid at this interval. The default is to run hourly.

        The format is described in
        <citerefentry><refentrytitle>systemd.time</refentrytitle>
        <manvolnum>7</manvolnum></citerefentry>.
      '';
    };

    datasets = mkOption {
      type = types.attrsOf (types.submodule ({ config, options, ... }: {
        freeformType = datasetSettingsType;
        options = commonOptions // datasetOptions;
        config.use_template = mkAliasDefinitions (mkDefault options.useTemplate or { });
        config.process_children_only = mkAliasDefinitions (mkDefault options.processChildrenOnly or { });
      }));
      default = { };
      description = "Datasets to snapshot.";
    };

    templates = mkOption {
      type = types.attrsOf (types.submodule {
        freeformType = datasetSettingsType;
        options = commonOptions;
      });
      default = { };
      description = "Templates for datasets.";
    };

    settings = mkOption {
      type = types.attrsOf datasetSettingsType;
      description = ''
        Free-form settings written directly to the config file. See
        <link xlink:href="https://github.com/jimsalterjrs/sanoid/blob/master/sanoid.defaults.conf"/>
        for allowed values.
      '';
    };

    extraArgs = mkOption {
      type = types.listOf types.str;
      default = [ ];
      example = [ "--verbose" "--readonly" "--debug" ];
      description = ''
        Extra arguments to pass to sanoid. See
        <link xlink:href="https://github.com/jimsalterjrs/sanoid/#sanoid-command-line-options"/>
        for allowed options.
      '';
    };
  };

  # Implementation

  config = mkIf cfg.enable {
    services.sanoid.settings = mkMerge [
      (mapAttrs' (d: v: nameValuePair ("template_" + d) v) cfg.templates)
      (mapAttrs (d: v: v) cfg.datasets)
    ];

    systemd.services.sanoid = {
      description = "Sanoid snapshot service";
      serviceConfig = {
        ExecStartPre = (map (buildAllowCommand "allow" [ "snapshot" "mount" "destroy" ]) datasets);
        ExecStopPost = (map (buildAllowCommand "unallow" [ "snapshot" "mount" "destroy" ]) datasets);
        ExecStart = lib.escapeShellArgs ([
          "${pkgs.sanoid}/bin/sanoid"
          "--cron"
          "--configdir"
          (pkgs.writeTextDir "sanoid.conf" configFile)
        ] ++ cfg.extraArgs);
        User = "sanoid";
        Group = "sanoid";
        DynamicUser = true;
        RuntimeDirectory = "sanoid";
        CacheDirectory = "sanoid";
      };
      # Prevents missing snapshots during DST changes
      environment.TZ = "UTC";
      after = [ "zfs.target" ];
      startAt = cfg.interval;
    };
  };

  meta.maintainers = with maintainers; [ lopsided98 ];
}