{ pkgs, lib, config, hostName, ... }: with builtins; { # Take regular snapshots, and prune old ones services.sanoid = { enable = true; extraArgs = [ "--verbose" ]; datasets = { "${hostName}/home" = { autosnap = true; autoprune = true; hourly = 12; daily = 7; monthly = 0; yearly = 0; recursive = true; }; "${hostName}/var" = { autosnap = true; autoprune = true; hourly = 12; daily = 7; monthly = 0; yearly = 0; recursive = true; }; }; }; # Trigger backups when disks are plugged services.udev.extraRules = '' ACTION=="add", SUBSYSTEM=="block", KERNEL=="sd*", ENV{ID_SERIAL}=="WDC_WD10JPVT-22A1YT0_WD-WX21AC2F3987", ENV{SYSTEMD_WANTS}+="zfs-local-backup-home@WD10JPVT.service", ENV{SYSTEMD_ALIAS}="/sys/subsystem/usb/WD10JPVT" # See https://github.com/systemd/systemd/issues/7587#issuecomment-381428545 ACTION=="remove", SUBSYSTEM=="block", KERNEL=="sd*", ENV{ID_SERIAL}=="WDC_WD10JPVT-22A1YT0_WD-WX21AC2F3987", TAG+="systemd" ''; # Force zpool import, even if the disk has not been exported, or has been imported on another computer systemd.services."zfs-force-import@" = { description = "ZFS force import: %I"; unitConfig.StopWhenUnneeded = true; requires = [ "sys-subsystem-usb-%i.device" ]; serviceConfig = { Type = "oneshot"; RemainAfterExit = true; PrivateTmp = true; ExecStartPre = [ # Scan the zpools, using stable paths "/bin/sh -xc '/run/booted-system/sw/bin/zpool import -d /dev/disk/by-id/ || true'" ]; ExecStart = '' /bin/sh -xc ' \ /run/booted-system/sw/bin/zpool import -lFd /dev/disk/by-id/ %I || \ /run/booted-system/sw/bin/zpool reopen %I || \ /run/booted-system/sw/bin/zpool clear -nFX %I' ''; ExecStartPost = [ # Do not block on unplug/failure "/run/booted-system/sw/bin/zpool set failmode=continue %I" ]; }; }; # Run the backup systemd.services."zfs-local-backup-home@" = { description = "ZFS backup home, on: %I"; after = [ "zfs-force-import@%i.service" ]; requires = [ "zfs-force-import@%i.service" ]; serviceConfig = rec { Type = "oneshot"; RemainAfterExit = true; PrivateTmp = true; CacheDirectory = [ "zfs-usb-backup-%I" ]; RuntimeDirectory = [ "zfs-usb-backup-%I" ]; User = "julm"; Group = "users"; ExecStartPre = [ "+/run/booted-system/sw/bin/zfs allow ${User} bookmark,hold,mount,send ${hostName}/home" "+/run/booted-system/sw/bin/zfs allow ${User} bookmark,create,destroy,load-key,mount,mountpoint,receive,rollback,snapshot %I/${User}" "+/bin/sh -xc '/run/booted-system/sw/bin/zpool scrub -p %I || true'" ]; ExecStart = pkgs.writeShellScript "zfs-local-backup-home" '' set -eu DESTPOOL=$1 install -D -m 400 /dev/stdin /tmp/sanoid/sanoid.conf <