@@ -0,0 +1,580 @@
1+{ config, lib, pkgs, ... }:
2+
3+with lib;
4+
5+let
6+
7+ isLocalPath = x:
8+ builtins.substring 0 1 x == "/" # absolute path
9+ || builtins.substring 0 1 x == "." # relative path
10+ || builtins.match "[.*:.*]" == null; # not machine:path
11+
12+ mkExcludeFile = cfg:
13+ # Write each exclude pattern to a new line
14+ pkgs.writeText "excludefile" (concatStringsSep "\n" cfg.exclude);
15+
16+ mkKeepArgs = cfg:
17+ # If cfg.prune.keep e.g. has a yearly attribute,
18+ # its content is passed on as --keep-yearly
19+ concatStringsSep " "
20+ (mapAttrsToList (x: y: "--keep-${x}=${toString y}") cfg.prune.keep);
21+
22+ mkBackupScript = cfg: ''
23+ on_exit()
24+ {
25+ exitStatus=$?
26+ # Reset the EXIT handler, or else we're called again on 'exit' below
27+ trap - EXIT
28+ ${cfg.postHook}
29+ exit $exitStatus
30+ }
31+ trap 'on_exit' INT TERM QUIT EXIT
32+
33+ archiveName="${cfg.archiveBaseName}-$(date ${cfg.dateFormat})"
34+ archiveSuffix="${optionalString cfg.appendFailedSuffix ".failed"}"
35+ ${cfg.preHook}
36+ '' + optionalString cfg.doInit ''
37+ # Run borg init if the repo doesn't exist yet
38+ if ! borg list > /dev/null; then
39+ borg init \
40+ --encryption ${cfg.encryption.mode} \
41+ $extraInitArgs
42+ ${cfg.postInit}
43+ fi
44+ '' + ''
45+ borg create \
46+ --compression ${cfg.compression} \
47+ --exclude-from ${mkExcludeFile cfg} \
48+ $extraCreateArgs \
49+ "::$archiveName$archiveSuffix" \
50+ ${escapeShellArgs cfg.paths}
51+ '' + optionalString cfg.appendFailedSuffix ''
52+ borg rename "::$archiveName$archiveSuffix" "$archiveName"
53+ '' + ''
54+ ${cfg.postCreate}
55+ '' + optionalString (cfg.prune.keep != { }) ''
56+ borg prune \
57+ ${mkKeepArgs cfg} \
58+ --prefix ${escapeShellArg cfg.prune.prefix} \
59+ $extraPruneArgs
60+ ${cfg.postPrune}
61+ '';
62+
63+ mkPassEnv = cfg: with cfg.encryption;
64+ if passCommand != null then
65+ { BORG_PASSCOMMAND = passCommand; }
66+ else if passphrase != null then
67+ { BORG_PASSPHRASE = passphrase; }
68+ else { };
69+
70+ mkBackupService = name: cfg:
71+ let
72+ userHome = config.users.users.${cfg.user}.home;
73+ in nameValuePair "borgbackup-job-${name}" {
74+ description = "BorgBackup job ${name}";
75+ path = with pkgs; [
76+ borgbackup openssh
77+ ];
78+ script = mkBackupScript cfg;
79+ serviceConfig = {
80+ User = cfg.user;
81+ Group = cfg.group;
82+ # Only run when no other process is using CPU or disk
83+ CPUSchedulingPolicy = "idle";
84+ IOSchedulingClass = "idle";
85+ ProtectSystem = "strict";
86+ ReadWritePaths =
87+ [ "${userHome}/.config/borg" "${userHome}/.cache/borg" ]
88+ # Borg needs write access to repo if it is not remote
89+ ++ optional (isLocalPath cfg.repo) cfg.repo;
90+ PrivateTmp = true;
91+ };
92+ environment = {
93+ BORG_REPO = cfg.repo;
94+ inherit (cfg) extraInitArgs extraCreateArgs extraPruneArgs;
95+ } // (mkPassEnv cfg) // cfg.environment;
96+ inherit (cfg) startAt;
97+ };
98+
99+ # Paths listed in ReadWritePaths must exist before service is started
100+ mkActivationScript = name: cfg:
101+ let
102+ install = "install -o ${cfg.user} -g ${cfg.group}";
103+ in
104+ nameValuePair "borgbackup-job-${name}" (stringAfter [ "users" ] (''
105+ # Eensure that the home directory already exists
106+ # We can't assert createHome == true because that's not the case for root
107+ cd "${config.users.users.${cfg.user}.home}"
108+ ${install} -d .config/borg
109+ ${install} -d .cache/borg
110+ '' + optionalString (isLocalPath cfg.repo) ''
111+ ${install} -d ${escapeShellArg cfg.repo}
112+ ''));
113+
114+ mkPassAssertion = name: cfg: {
115+ assertion = with cfg.encryption;
116+ mode != "none" -> passCommand != null || passphrase != null;
117+ message =
118+ "passCommand or passphrase has to be specified because"
119+ + '' borgbackup.jobs.${name}.encryption != "none"'';
120+ };
121+
122+ mkRepoService = name: cfg:
123+ nameValuePair "borgbackup-repo-${name}" {
124+ description = "Create BorgBackup repository ${name} directory";
125+ script = ''
126+ mkdir -p ${escapeShellArg cfg.path}
127+ chown ${cfg.user}:${cfg.group} ${escapeShellArg cfg.path}
128+ '';
129+ serviceConfig = {
130+ # The service's only task is to ensure that the specified path exists
131+ Type = "oneshot";
132+ };
133+ wantedBy = [ "multi-user.target" ];
134+ };
135+
136+ mkAuthorizedKey = cfg: appendOnly: key:
137+ let
138+ # Because of the following line, clients do not need to specify an absolute repo path
139+ cdCommand = "cd ${escapeShellArg cfg.path}";
140+ restrictedArg = "--restrict-to-${if cfg.allowSubRepos then "path" else "repository"} .";
141+ appendOnlyArg = optionalString appendOnly "--append-only";
142+ quotaArg = optionalString (cfg.quota != null) "--storage-quota ${cfg.quota}";
143+ serveCommand = "borg serve ${restrictedArg} ${appendOnlyArg} ${quotaArg}";
144+ in
145+ ''command="${cdCommand} && ${serveCommand}",restrict ${key}'';
146+
147+ mkUsersConfig = name: cfg: {
148+ users.${cfg.user} = {
149+ openssh.authorizedKeys.keys =
150+ (map (mkAuthorizedKey cfg false) cfg.authorizedKeys
151+ ++ map (mkAuthorizedKey cfg true) cfg.authorizedKeysAppendOnly);
152+ useDefaultShell = true;
153+ };
154+ groups.${cfg.group} = { };
155+ };
156+
157+ mkKeysAssertion = name: cfg: {
158+ assertion = cfg.authorizedKeys != [ ] || cfg.authorizedKeysAppendOnly != [ ];
159+ message =
160+ "borgbackup.repos.${name} does not make sense"
161+ + " without at least one public key";
162+ };
163+
164+in {
165+ meta.maintainers = with maintainers; [ dotlambda ];
166+
167+ ###### interface
168+
169+ options.services.borgbackup.jobs = mkOption {
170+ description = "Deduplicating backups using BorgBackup.";
171+ default = { };
172+ example = literalExample ''
173+ {
174+ rootBackup = {
175+ paths = "/";
176+ exclude = [ "/nix" ];
177+ repo = "/path/to/local/repo";
178+ encryption = {
179+ mode = "repokey";
180+ passphrase = "secret";
181+ };
182+ compression = "auto,lzma";
183+ startAt = "weekly";
184+ };
185+ }
186+ '';
187+ type = types.attrsOf (types.submodule (let globalConfig = config; in
188+ { name, config, ... }: {
189+ options = {
190+
191+ paths = mkOption {
192+ type = with types; either path (nonEmptyListOf path);
193+ description = "Path(s) to back up.";
194+ example = "/home/user";
195+ apply = x: if isList x then x else [ x ];
196+ };
197+
198+ repo = mkOption {
199+ type = types.str;
200+ description = "Remote or local repository to back up to.";
201+ example = "user@machine:/path/to/repo";
202+ };
203+
204+ archiveBaseName = mkOption {
205+ type = types.strMatching "[^/{}]+";
206+ default = "${globalConfig.networking.hostName}-${name}";
207+ defaultText = "\${config.networking.hostName}-<name>";
208+ description = ''
209+ How to name the created archives. A timestamp, whose format is
210+ determined by <option>dateFormat</option>, will be appended. The full
211+ name can be modified at runtime (<literal>$archiveName</literal>).
212+ Placeholders like <literal>{hostname}</literal> must not be used.
213+ '';
214+ };
215+
216+ dateFormat = mkOption {
217+ type = types.str;
218+ description = ''
219+ Arguments passed to <command>date</command>
220+ to create a timestamp suffix for the archive name.
221+ '';
222+ default = "+%Y-%m-%dT%H:%M:%S";
223+ example = "-u +%s";
224+ };
225+
226+ startAt = mkOption {
227+ type = with types; either str (listOf str);
228+ default = "daily";
229+ description = ''
230+ When or how often the backup should run.
231+ Must be in the format described in
232+ <citerefentry><refentrytitle>systemd.time</refentrytitle>
233+ <manvolnum>7</manvolnum></citerefentry>.
234+ If you do not want the backup to start
235+ automatically, use <literal>[ ]</literal>.
236+ '';
237+ };
238+
239+ user = mkOption {
240+ type = types.str;
241+ description = ''
242+ The user <command>borg</command> is run as.
243+ User or group need read permission
244+ for the specified <option>paths</option>.
245+ '';
246+ default = "root";
247+ };
248+
249+ group = mkOption {
250+ type = types.str;
251+ description = ''
252+ The group borg is run as. User or group needs read permission
253+ for the specified <option>paths</option>.
254+ '';
255+ default = "root";
256+ };
257+
258+ encryption.mode = mkOption {
259+ type = types.enum [
260+ "repokey" "keyfile"
261+ "repokey-blake2" "keyfile-blake2"
262+ "authenticated" "authenticated-blake2"
263+ "none"
264+ ];
265+ description = ''
266+ Encryption mode to use. Setting a mode
267+ other than <literal>"none"</literal> requires
268+ you to specify a <option>passCommand</option>
269+ or a <option>passphrase</option>.
270+ '';
271+ };
272+
273+ encryption.passCommand = mkOption {
274+ type = with types; nullOr str;
275+ description = ''
276+ A command which prints the passphrase to stdout.
277+ Mutually exclusive with <option>passphrase</option>.
278+ '';
279+ default = null;
280+ example = "cat /path/to/passphrase_file";
281+ };
282+
283+ encryption.passphrase = mkOption {
284+ type = with types; nullOr str;
285+ description = ''
286+ The passphrase the backups are encrypted with.
287+ Mutually exclusive with <option>passCommand</option>.
288+ If you do not want the passphrase to be stored in the
289+ world-readable Nix store, use <option>passCommand</option>.
290+ '';
291+ default = null;
292+ };
293+
294+ compression = mkOption {
295+ # "auto" is optional,
296+ # compression mode must be given,
297+ # compression level is optional
298+ type = types.strMatching "none|(auto,)?(lz4|zstd|zlib|lzma)(,[[:digit:]]{1,2})?";
299+ description = ''
300+ Compression method to use. Refer to
301+ <command>borg help compression</command>
302+ for all available options.
303+ '';
304+ default = "lz4";
305+ example = "auto,lzma";
306+ };
307+
308+ exclude = mkOption {
309+ type = with types; listOf str;
310+ description = ''
311+ Exclude paths matching any of the given patterns. See
312+ <command>borg help patterns</command> for pattern syntax.
313+ '';
314+ default = [ ];
315+ example = [
316+ "/home/*/.cache"
317+ "/nix"
318+ ];
319+ };
320+
321+ doInit = mkOption {
322+ type = types.bool;
323+ description = ''
324+ Run <command>borg init</command> if the
325+ specified <option>repo</option> does not exist.
326+ You should set this to <literal>false</literal>
327+ if the repository is located on an external drive
328+ that might not always be mounted.
329+ '';
330+ default = true;
331+ };
332+
333+ appendFailedSuffix = mkOption {
334+ type = types.bool;
335+ description = ''
336+ Append a <literal>.failed</literal> suffix
337+ to the archive name, which is only removed if
338+ <command>borg create</command> has a zero exit status.
339+ '';
340+ default = true;
341+ };
342+
343+ prune.keep = mkOption {
344+ # Specifying e.g. `prune.keep.yearly = -1`
345+ # means there is no limit of yearly archives to keep
346+ # The regex is for use with e.g. --keep-within 1y
347+ type = with types; attrsOf (either int (strMatching "[[:digit:]]+[Hdwmy]"));
348+ description = ''
349+ Prune a repository by deleting all archives not matching any of the
350+ specified retention options. See <command>borg help prune</command>
351+ for the available options.
352+ '';
353+ default = { };
354+ example = literalExample ''
355+ {
356+ within = "1d"; # Keep all archives from the last day
357+ daily = 7;
358+ weekly = 4;
359+ monthly = -1; # Keep at least one archive for each month
360+ }
361+ '';
362+ };
363+
364+ prune.prefix = mkOption {
365+ type = types.str;
366+ description = ''
367+ Only consider archive names starting with this prefix for pruning.
368+ By default, only archives created by this job are considered.
369+ Use <literal>""</literal> to consider all archives.
370+ '';
371+ default = config.archiveBaseName;
372+ defaultText = "\${archiveBaseName}";
373+ };
374+
375+ environment = mkOption {
376+ type = with types; attrsOf str;
377+ description = ''
378+ Environment variables passed to the backup script.
379+ You can for example specify which SSH key to use.
380+ '';
381+ default = { };
382+ example = { BORG_RSH = "ssh -i /path/to/key"; };
383+ };
384+
385+ preHook = mkOption {
386+ type = types.lines;
387+ description = ''
388+ Shell commands to run before the backup.
389+ This can for example be used to mount file systems.
390+ '';
391+ default = "";
392+ example = ''
393+ # To add excluded paths at runtime
394+ extraCreateArgs="$extraCreateArgs --exclude /some/path"
395+ '';
396+ };
397+
398+ postInit = mkOption {
399+ type = types.lines;
400+ description = ''
401+ Shell commands to run after <command>borg init</command>.
402+ '';
403+ default = "";
404+ };
405+
406+ postCreate = mkOption {
407+ type = types.lines;
408+ description = ''
409+ Shell commands to run after <command>borg create</command>. The name
410+ of the created archive is stored in <literal>$archiveName</literal>.
411+ '';
412+ default = "";
413+ };
414+
415+ postPrune = mkOption {
416+ type = types.lines;
417+ description = ''
418+ Shell commands to run after <command>borg prune</command>.
419+ '';
420+ default = "";
421+ };
422+
423+ postHook = mkOption {
424+ type = types.lines;
425+ description = ''
426+ Shell commands to run just before exit. They are executed
427+ even if a previous command exits with a non-zero exit code.
428+ The latter is available as <literal>$exitStatus</literal>.
429+ '';
430+ default = "";
431+ };
432+
433+ extraInitArgs = mkOption {
434+ type = types.str;
435+ description = ''
436+ Additional arguments for <command>borg init</command>.
437+ Can also be set at runtime using <literal>$extraInitArgs</literal>.
438+ '';
439+ default = "";
440+ example = "--append-only";
441+ };
442+
443+ extraCreateArgs = mkOption {
444+ type = types.str;
445+ description = ''
446+ Additional arguments for <command>borg create</command>.
447+ Can also be set at runtime using <literal>$extraCreateArgs</literal>.
448+ '';
449+ default = "";
450+ example = "--stats --checkpoint-interval 600";
451+ };
452+
453+ extraPruneArgs = mkOption {
454+ type = types.str;
455+ description = ''
456+ Additional arguments for <command>borg prune</command>.
457+ Can also be set at runtime using <literal>$extraPruneArgs</literal>.
458+ '';
459+ default = "";
460+ example = "--save-space";
461+ };
462+
463+ };
464+ }
465+ ));
466+ };
467+
468+ options.services.borgbackup.repos = mkOption {
469+ description = ''
470+ Serve BorgBackup repositories to given public SSH keys,
471+ restricting their access to the repository only.
472+ Also, clients do not need to specify the absolute path when accessing the repository,
473+ i.e. <literal>user@machine:.</literal> is enough. (Note colon and dot.)
474+ '';
475+ default = { };
476+ type = types.attrsOf (types.submodule (
477+ { name, config, ... }: {
478+ options = {
479+
480+ path = mkOption {
481+ type = types.path;
482+ description = ''
483+ Where to store the backups. Note that the directory
484+ is created automatically, with correct permissions.
485+ '';
486+ default = "/var/lib/borgbackup";
487+ };
488+
489+ user = mkOption {
490+ type = types.str;
491+ description = ''
492+ The user <command>borg serve</command> is run as.
493+ User or group needs write permission
494+ for the specified <option>path</option>.
495+ '';
496+ default = "borg";
497+ };
498+
499+ group = mkOption {
500+ type = types.str;
501+ description = ''
502+ The group <command>borg serve</command> is run as.
503+ User or group needs write permission
504+ for the specified <option>path</option>.
505+ '';
506+ default = "borg";
507+ };
508+
509+ authorizedKeys = mkOption {
510+ type = with types; listOf str;
511+ description = ''
512+ Public SSH keys that are given full write access to this repository.
513+ You should use a different SSH key for each repository you write to, because
514+ the specified keys are restricted to running <command>borg serve</command>
515+ and can only access this single repository.
516+ '';
517+ default = [ ];
518+ };
519+
520+ authorizedKeysAppendOnly = mkOption {
521+ type = with types; listOf str;
522+ description = ''
523+ Public SSH keys that can only be used to append new data (archives) to the repository.
524+ Note that archives can still be marked as deleted and are subsequently removed from disk
525+ upon accessing the repo with full write access, e.g. when pruning.
526+ '';
527+ default = [ ];
528+ };
529+
530+ allowSubRepos = mkOption {
531+ type = types.bool;
532+ description = ''
533+ Allow clients to create repositories in subdirectories of the
534+ specified <option>path</option>. These can be accessed using
535+ <literal>user@machine:path/to/subrepo</literal>. Note that a
536+ <option>quota</option> applies to repositories independently.
537+ Therefore, if this is enabled, clients can create multiple
538+ repositories and upload an arbitrary amount of data.
539+ '';
540+ default = false;
541+ };
542+
543+ quota = mkOption {
544+ # See the definition of parse_file_size() in src/borg/helpers/parseformat.py
545+ type = with types; nullOr (strMatching "[[:digit:].]+[KMGTP]?");
546+ description = ''
547+ Storage quota for the repository. This quota is ensured for all
548+ sub-repositories if <option>allowSubRepos</option> is enabled
549+ but not for the overall storage space used.
550+ '';
551+ default = null;
552+ example = "100G";
553+ };
554+
555+ };
556+ }
557+ ));
558+ };
559+
560+ ###### implementation
561+
562+ config = mkIf (with config.services.borgbackup; jobs != { } || repos != { })
563+ (with config.services.borgbackup; {
564+ assertions =
565+ mapAttrsToList mkPassAssertion jobs
566+ ++ mapAttrsToList mkKeysAssertion repos;
567+
568+ system.activationScripts = mapAttrs' mkActivationScript jobs;
569+
570+ systemd.services =
571+ # A job named "foo" is mapped to systemd.services.borgbackup-job-foo
572+ mapAttrs' mkBackupService jobs
573+ # A repo named "foo" is mapped to systemd.services.borgbackup-repo-foo
574+ // mapAttrs' mkRepoService repos;
575+
576+ users = mkMerge (mapAttrsToList mkUsersConfig repos);
577+
578+ environment.systemPackages = with pkgs; [ borgbackup ];
579+ });
580+}