1{ config, pkgs, lib, ... }:
2let
3 inherit (lib)
4 concatLists
5 concatMap
6 concatMapStringsSep
7 concatStringsSep
8 filterAttrs
9 isAttrs
10 literalExpression
11 mapAttrs'
12 mapAttrsToList
13 mkIf
14 mkOption
15 optionalString
16 sort
17 types
18 ;
19
20 # The priority of an option or section.
21 # The configurations format are order-sensitive. Pairs are added as children of
22 # the last sections if possible, otherwise, they start a new section.
23 # We sort them in topological order:
24 # 1. Leaf pairs.
25 # 2. Sections that may contain (1).
26 # 3. Sections that may contain (1) or (2).
27 # 4. Etc.
28 prioOf = { name, value }:
29 if !isAttrs value then 0 # Leaf options.
30 else {
31 target = 1; # Contains: options.
32 subvolume = 2; # Contains: options, target.
33 volume = 3; # Contains: options, target, subvolume.
34 }.${name} or (throw "Unknow section '${name}'");
35
36 genConfig' = set: concatStringsSep "\n" (genConfig set);
37 genConfig = set:
38 let
39 pairs = mapAttrsToList (name: value: { inherit name value; }) set;
40 sortedPairs = sort (a: b: prioOf a < prioOf b) pairs;
41 in
42 concatMap genPair sortedPairs;
43 genSection = sec: secName: value:
44 [ "${sec} ${secName}" ] ++ map (x: " " + x) (genConfig value);
45 genPair = { name, value }:
46 if !isAttrs value
47 then [ "${name} ${value}" ]
48 else concatLists (mapAttrsToList (genSection name) value);
49
50 addDefaults = settings: { backend = "btrfs-progs-sudo"; } // settings;
51
52 mkConfigFile = name: settings: pkgs.writeTextFile {
53 name = "btrbk-${name}.conf";
54 text = genConfig' (addDefaults settings);
55 checkPhase = ''
56 set +e
57 ${pkgs.btrbk}/bin/btrbk -c $out dryrun
58 # According to btrbk(1), exit status 2 means parse error
59 # for CLI options or the config file.
60 if [[ $? == 2 ]]; then
61 echo "Btrbk configuration is invalid:"
62 cat $out
63 exit 1
64 fi
65 set -e
66 '';
67 };
68
69 cfg = config.services.btrbk;
70 sshEnabled = cfg.sshAccess != [ ];
71 serviceEnabled = cfg.instances != { };
72in
73{
74 meta.maintainers = with lib.maintainers; [ oxalica ];
75
76 options = {
77 services.btrbk = {
78 extraPackages = mkOption {
79 description = lib.mdDoc "Extra packages for btrbk, like compression utilities for `stream_compress`";
80 type = types.listOf types.package;
81 default = [ ];
82 example = literalExpression "[ pkgs.xz ]";
83 };
84 niceness = mkOption {
85 description = lib.mdDoc "Niceness for local instances of btrbk. Also applies to remote ones connecting via ssh when positive.";
86 type = types.ints.between (-20) 19;
87 default = 10;
88 };
89 ioSchedulingClass = mkOption {
90 description = lib.mdDoc "IO scheduling class for btrbk (see ionice(1) for a quick description). Applies to local instances, and remote ones connecting by ssh if set to idle.";
91 type = types.enum [ "idle" "best-effort" "realtime" ];
92 default = "best-effort";
93 };
94 instances = mkOption {
95 description = lib.mdDoc "Set of btrbk instances. The instance named `btrbk` is the default one.";
96 type = with types;
97 attrsOf (
98 submodule {
99 options = {
100 onCalendar = mkOption {
101 type = types.nullOr types.str;
102 default = "daily";
103 description = lib.mdDoc ''
104 How often this btrbk instance is started. See systemd.time(7) for more information about the format.
105 Setting it to null disables the timer, thus this instance can only be started manually.
106 '';
107 };
108 settings = mkOption {
109 type = let t = types.attrsOf (types.either types.str (t // { description = "instances of this type recursively"; })); in t;
110 default = { };
111 example = {
112 snapshot_preserve_min = "2d";
113 snapshot_preserve = "14d";
114 volume = {
115 "/mnt/btr_pool" = {
116 target = "/mnt/btr_backup/mylaptop";
117 subvolume = {
118 "rootfs" = { };
119 "home" = { snapshot_create = "always"; };
120 };
121 };
122 };
123 };
124 description = lib.mdDoc "configuration options for btrbk. Nested attrsets translate to subsections.";
125 };
126 };
127 }
128 );
129 default = { };
130 };
131 sshAccess = mkOption {
132 description = lib.mdDoc "SSH keys that should be able to make or push snapshots on this system remotely with btrbk";
133 type = with types; listOf (
134 submodule {
135 options = {
136 key = mkOption {
137 type = str;
138 description = lib.mdDoc "SSH public key allowed to login as user `btrbk` to run remote backups.";
139 };
140 roles = mkOption {
141 type = listOf (enum [ "info" "source" "target" "delete" "snapshot" "send" "receive" ]);
142 example = [ "source" "info" "send" ];
143 description = lib.mdDoc "What actions can be performed with this SSH key. See ssh_filter_btrbk(1) for details";
144 };
145 };
146 }
147 );
148 default = [ ];
149 };
150 };
151
152 };
153 config = mkIf (sshEnabled || serviceEnabled) {
154 environment.systemPackages = [ pkgs.btrbk ] ++ cfg.extraPackages;
155 security.sudo.extraRules = [
156 {
157 users = [ "btrbk" ];
158 commands = [
159 { command = "${pkgs.btrfs-progs}/bin/btrfs"; options = [ "NOPASSWD" ]; }
160 { command = "${pkgs.coreutils}/bin/mkdir"; options = [ "NOPASSWD" ]; }
161 { command = "${pkgs.coreutils}/bin/readlink"; options = [ "NOPASSWD" ]; }
162 # for ssh, they are not the same than the one hard coded in ${pkgs.btrbk}
163 { command = "/run/current-system/bin/btrfs"; options = [ "NOPASSWD" ]; }
164 { command = "/run/current-system/sw/bin/mkdir"; options = [ "NOPASSWD" ]; }
165 { command = "/run/current-system/sw/bin/readlink"; options = [ "NOPASSWD" ]; }
166 ];
167 }
168 ];
169 users.users.btrbk = {
170 isSystemUser = true;
171 # ssh needs a home directory
172 home = "/var/lib/btrbk";
173 createHome = true;
174 shell = "${pkgs.bash}/bin/bash";
175 group = "btrbk";
176 openssh.authorizedKeys.keys = map
177 (
178 v:
179 let
180 options = concatMapStringsSep " " (x: "--" + x) v.roles;
181 ioniceClass = {
182 "idle" = 3;
183 "best-effort" = 2;
184 "realtime" = 1;
185 }.${cfg.ioSchedulingClass};
186 in
187 ''command="${pkgs.util-linux}/bin/ionice -t -c ${toString ioniceClass} ${optionalString (cfg.niceness >= 1) "${pkgs.coreutils}/bin/nice -n ${toString cfg.niceness}"} ${pkgs.btrbk}/share/btrbk/scripts/ssh_filter_btrbk.sh --sudo ${options}" ${v.key}''
188 )
189 cfg.sshAccess;
190 };
191 users.groups.btrbk = { };
192 systemd.tmpfiles.rules = [
193 "d /var/lib/btrbk 0750 btrbk btrbk"
194 "d /var/lib/btrbk/.ssh 0700 btrbk btrbk"
195 "f /var/lib/btrbk/.ssh/config 0700 btrbk btrbk - StrictHostKeyChecking=accept-new"
196 ];
197 environment.etc = mapAttrs'
198 (
199 name: instance: {
200 name = "btrbk/${name}.conf";
201 value.source = mkConfigFile name instance.settings;
202 }
203 )
204 cfg.instances;
205 systemd.services = mapAttrs'
206 (
207 name: _: {
208 name = "btrbk-${name}";
209 value = {
210 description = "Takes BTRFS snapshots and maintains retention policies.";
211 unitConfig.Documentation = "man:btrbk(1)";
212 path = [ "/run/wrappers" ] ++ cfg.extraPackages;
213 serviceConfig = {
214 User = "btrbk";
215 Group = "btrbk";
216 Type = "oneshot";
217 ExecStart = "${pkgs.btrbk}/bin/btrbk -c /etc/btrbk/${name}.conf run";
218 Nice = cfg.niceness;
219 IOSchedulingClass = cfg.ioSchedulingClass;
220 StateDirectory = "btrbk";
221 };
222 };
223 }
224 )
225 cfg.instances;
226
227 systemd.timers = mapAttrs'
228 (
229 name: instance: {
230 name = "btrbk-${name}";
231 value = {
232 description = "Timer to take BTRFS snapshots and maintain retention policies.";
233 wantedBy = [ "timers.target" ];
234 timerConfig = {
235 OnCalendar = instance.onCalendar;
236 AccuracySec = "10min";
237 Persistent = true;
238 };
239 };
240 }
241 )
242 (filterAttrs (name: instance: instance.onCalendar != null)
243 cfg.instances);
244 };
245
246}