about summary refs log tree commit diff
path: root/nixos/modules/services/misc/snapper.nix
blob: 33207ac2b5bd5a448fdb893fee97e766b25568ea (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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
{ config, pkgs, lib, ... }:

with lib;

let
  cfg = config.services.snapper;

  mkValue = v:
    if isList v then "\"${concatMapStringsSep " " (escape [ "\\" " " ]) v}\""
    else if v == true then "yes"
    else if v == false then "no"
    else if isString v then "\"${v}\""
    else builtins.toJSON v;

  mkKeyValue = k: v: "${k}=${mkValue v}";

  # "it's recommended to always specify the filesystem type"  -- man snapper-configs
  defaultOf = k: if k == "FSTYPE" then null else configOptions.${k}.default or null;

  safeStr = types.strMatching "[^\n\"]*" // {
    description = "string without line breaks or quotes";
    descriptionClass = "conjunction";
  };

  configOptions = {
    SUBVOLUME = mkOption {
      type = types.path;
      description = ''
        Path of the subvolume or mount point.
        This path is a subvolume and has to contain a subvolume named
        .snapshots.
        See also man:snapper(8) section PERMISSIONS.
      '';
    };

    FSTYPE = mkOption {
      type = types.enum [ "btrfs" ];
      default = "btrfs";
      description = ''
        Filesystem type. Only btrfs is stable and tested.
      '';
    };

    ALLOW_GROUPS = mkOption {
      type = types.listOf safeStr;
      default = [];
      description = ''
        List of groups allowed to operate with the config.

        Also see the PERMISSIONS section in man:snapper(8).
      '';
    };

    ALLOW_USERS = mkOption {
      type = types.listOf safeStr;
      default = [];
      example = [ "alice" ];
      description = ''
        List of users allowed to operate with the config. "root" is always
        implicitly included.

        Also see the PERMISSIONS section in man:snapper(8).
      '';
    };

    TIMELINE_CLEANUP = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Defines whether the timeline cleanup algorithm should be run for the config.
      '';
    };

    TIMELINE_CREATE = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Defines whether hourly snapshots should be created.
      '';
    };
  };
in

{
  options.services.snapper = {

    snapshotRootOnBoot = mkOption {
      type = types.bool;
      default = false;
      description = ''
        Whether to snapshot root on boot
      '';
    };

    snapshotInterval = mkOption {
      type = types.str;
      default = "hourly";
      description = ''
        Snapshot interval.

        The format is described in
        {manpage}`systemd.time(7)`.
      '';
    };

    persistentTimer = mkOption {
      default = false;
      type = types.bool;
      example = true;
      description = ''
        Set the `persistentTimer` option for the
        {manpage}`systemd.timer(5)`
        which triggers the snapshot immediately if the last trigger
        was missed (e.g. if the system was powered down).
      '';
    };

    cleanupInterval = mkOption {
      type = types.str;
      default = "1d";
      description = ''
        Cleanup interval.

        The format is described in
        {manpage}`systemd.time(7)`.
      '';
    };

    filters = mkOption {
      type = types.nullOr types.lines;
      default = null;
      description = ''
        Global display difference filter. See man:snapper(8) for more details.
      '';
    };

    configs = mkOption {
      default = { };
      example = literalExpression ''
        {
          home = {
            SUBVOLUME = "/home";
            ALLOW_USERS = [ "alice" ];
            TIMELINE_CREATE = true;
            TIMELINE_CLEANUP = true;
          };
        }
      '';

      description = ''
        Subvolume configuration. Any option mentioned in man:snapper-configs(5)
        is valid here, even if NixOS doesn't document it.
      '';

      type = types.attrsOf (types.submodule {
        freeformType = types.attrsOf (types.oneOf [ (types.listOf safeStr) types.bool safeStr types.number ]);

        options = configOptions;
      });
    };
  };

  config = mkIf (cfg.configs != {}) (let
    documentation = [ "man:snapper(8)" "man:snapper-configs(5)" ];
  in {

    environment = {

      systemPackages = [ pkgs.snapper ];

      # Note: snapper/config-templates/default is only needed for create-config
      #       which is not the NixOS way to configure.
      etc = {

        "sysconfig/snapper".text = ''
          SNAPPER_CONFIGS="${lib.concatStringsSep " " (builtins.attrNames cfg.configs)}"
        '';

      }
      // (mapAttrs' (name: subvolume: nameValuePair "snapper/configs/${name}" ({
        text = lib.generators.toKeyValue { inherit mkKeyValue; } (filterAttrs (k: v: v != defaultOf k) subvolume);
      })) cfg.configs)
      // (lib.optionalAttrs (cfg.filters != null) {
        "snapper/filters/default.txt".text = cfg.filters;
      });

    };

    services.dbus.packages = [ pkgs.snapper ];

    systemd.services.snapperd = {
      description = "DBus interface for snapper";
      inherit documentation;
      serviceConfig = {
        Type = "dbus";
        BusName = "org.opensuse.Snapper";
        ExecStart = "${pkgs.snapper}/bin/snapperd";
        CapabilityBoundingSet = "CAP_DAC_OVERRIDE CAP_FOWNER CAP_CHOWN CAP_FSETID CAP_SETFCAP CAP_SYS_ADMIN CAP_SYS_MODULE CAP_IPC_LOCK CAP_SYS_NICE";
        LockPersonality = true;
        NoNewPrivileges = false;
        PrivateNetwork = true;
        ProtectHostname = true;
        RestrictAddressFamilies = "AF_UNIX";
        RestrictRealtime = true;
      };
    };

    systemd.services.snapper-timeline = {
      description = "Timeline of Snapper Snapshots";
      inherit documentation;
      requires = [ "local-fs.target" ];
      serviceConfig.ExecStart = "${pkgs.snapper}/lib/snapper/systemd-helper --timeline";
    };

    systemd.timers.snapper-timeline = {
      wantedBy = [ "timers.target" ];
      timerConfig = {
        Persistent = cfg.persistentTimer;
        OnCalendar = cfg.snapshotInterval;
      };
    };

    systemd.services.snapper-cleanup = {
      description = "Cleanup of Snapper Snapshots";
      inherit documentation;
      serviceConfig.ExecStart = "${pkgs.snapper}/lib/snapper/systemd-helper --cleanup";
    };

    systemd.timers.snapper-cleanup = {
      description = "Cleanup of Snapper Snapshots";
      inherit documentation;
      wantedBy = [ "timers.target" ];
      requires = [ "local-fs.target" ];
      timerConfig.OnBootSec = "10m";
      timerConfig.OnUnitActiveSec = cfg.cleanupInterval;
    };

    systemd.services.snapper-boot = lib.optionalAttrs cfg.snapshotRootOnBoot {
      description = "Take snapper snapshot of root on boot";
      inherit documentation;
      serviceConfig.ExecStart = "${pkgs.snapper}/bin/snapper --config root create --cleanup-algorithm number --description boot";
      serviceConfig.Type = "oneshot";
      requires = [ "local-fs.target" ];
      wantedBy = [ "multi-user.target" ];
      unitConfig.ConditionPathExists = "/etc/snapper/configs/root";
    };

    assertions =
      concatMap
        (name:
          let
            sub = cfg.configs.${name};
          in
          [ { assertion = !(sub ? extraConfig);
              message = ''
                The option definition `services.snapper.configs.${name}.extraConfig' no longer has any effect; please remove it.
                The contents of this option should be migrated to attributes on `services.snapper.configs.${name}'.
              '';
            }
          ] ++
          map
            (attr: {
              assertion = !(hasAttr attr sub);
              message = ''
                The option definition `services.snapper.configs.${name}.${attr}' has been renamed to `services.snapper.configs.${name}.${toUpper attr}'.
              '';
            })
            [ "fstype" "subvolume" ]
        )
        (attrNames cfg.configs);
  });
}