Nice to see other attempts than what I usually do:
Instead of device unit files, fstab, crypttab generated stuff, I mainly just use udev rules, a systemd service to track and log execution and a simple script.
Literally looks like:
% cat /etc/udev/rules.d/99-backup-hd.rules
ACTION=="add" \
, SUBSYSTEM=="block" \
, TAG+="systemd" \
, ENV{ID_FS_UUID}=="4a823890-8f07-411e-933e-e73004b02066" \
, ENV{UDISKS_IGNORE}="1" \
, ENV{SYSTEMD_WANTS}+="sys-backup.service
% systemctl cat sys-backup.service
# /etc/systemd/system/sys-backup.service
[Unit]
Description=Do full system backup on harddrive insertion
# I can disable backing up by removing this file
ConditionPathExists=/etc/run-backup
[Service]
User=root
Type=oneshot
ExecStart=/bin/sh /usr/local/sbin/sys-backup.sh
% cat /usr/local/sbin/sys-backup.sh
#!/bin/sh
set -e
disk_uuid=4a823890-8f07-411e-933e-e73004b02066
cryptsetup open \
--key-file /root/storage-keys/usb-"$disk_uuid".key \
/dev/disk/by-uuid/"$disk_uuid" \
luks-backup-"$disk_uuid"
mount -o compress=zstd /dev/mapper/luks-backup-"$disk_uuid" /backup
btrfs-sxbackup run / /home /var
umount /backup
cryptsetup close luks-backup-"$disk_uuid"
udisksctl power-off -b \
/dev/disk/by-uuid/"$disk_uuid"
The tricky thing with udev rules comes down to syntactic mistakes like assignment vs binary operator equality, ordering of rules and what environments they produce.
It took me a nontrivial amount of time to learn that ENV{ID_FS_UUID} is only set in later rules. I wish udev would be updated with explicit “requires/provides” like syntax instead of trying to guess which glob sort order I have to contend with.
That’s a pretty cool solution. One thing I’d add to this service would be a “Nice” option so whatever you’re doing after connecting the drive is not affected too much by the process.
Nice to see other attempts than what I usually do:
Instead of device unit files, fstab, crypttab generated stuff, I mainly just use udev rules, a systemd service to track and log execution and a simple script.
Literally looks like:
The tricky thing with udev rules comes down to syntactic mistakes like assignment vs binary operator equality, ordering of rules and what environments they produce. It took me a nontrivial amount of time to learn that ENV{ID_FS_UUID} is only set in later rules. I wish udev would be updated with explicit “requires/provides” like syntax instead of trying to guess which glob sort order I have to contend with.
That’s…that’s a really smart solution. Nice.
If I ever buy an external harddrive again I’ll probably steal this idea and implement for my FreeBSD storage box.
That’s a pretty cool solution. One thing I’d add to this service would be a “Nice” option so whatever you’re doing after connecting the drive is not affected too much by the process.