refactor(hosts/luna): use btrfs-rollback service for handling rollbacks

This commit is contained in:
Price Hiller 2024-08-25 00:26:25 -05:00
parent aa1ca78c3b
commit 6e0af2ca7a
Signed by: Price
GPG Key ID: C3FADDE7A8534BEB
2 changed files with 10 additions and 53 deletions

View File

@ -258,6 +258,7 @@
};
modules = [
defaults
./modules/btrfs-rollback.nix
inputs.impermanence.nixosModules.impermanence
inputs.agenix.nixosModules.default
inputs.disko.nixosModules.disko

View File

@ -1,8 +1,15 @@
{ modulesPath, pkgs, ... }:
{ modulesPath, ... }:
{
imports = [ (modulesPath + "/installer/scan/not-detected.nix") ];
services.btrfs-rollback = {
enable = true;
diskLabel = "NixOS-Primary";
subvolume = "root";
snapshot = "root-base";
};
boot = {
tmp = {
useTmpfs = true;
@ -24,58 +31,7 @@
"sd_mod"
];
kernelModules = [ ];
systemd = {
enable = true;
initrdBin = [
pkgs.libuuid
pkgs.gawk
];
services.rollback = {
description = "Rollback btrfs root subvolume";
wantedBy = [ "initrd.target" ];
before = [ "sysroot.mount" ];
after = [ "initrd-root-device.target" ];
unitConfig.DefaultDependencies = "no";
serviceConfig.Type = "oneshot";
script = ''
mkdir -p /mnt
DISK_LABEL="NixOS-Primary"
FOUND_DISK=0
ATTEMPTS=50
printf "Attempting to find disk with label '%s'\n" "$DISK_LABEL"
while ((ATTEMPTS > 0)); do
if findfs LABEL="$DISK_LABEL"; then
FOUND_DISK=1
printf "Found disk!\n"
break;
fi
((ATTEMPTS--))
sleep .1
printf "Remaining disk discovery attempts: %s\n" "$ATTEMPTS"
done
if (( FOUND_DISK == 0 )); then
printf "Discovery of disk with label '%s' failed! Cannot rollback!\n" "$DISK_LABEL"
exit 1
fi
mount -t btrfs -o subvol=/ $(findfs LABEL="$DISK_LABEL") /mnt
btrfs subvolume list -to /mnt/root \
| awk 'NR>2 { printf $4"\n" }' \
| while read subvol; do
printf "Removing Subvolume: %s\n" "$subvol";
btrfs subvolume delete "/mnt/$subvol"
done
printf "Removing /root subvolume\n"
btrfs subvolume delete /mnt/root
printf "Restoring base /root subvolume\n"
btrfs subvolume snapshot /mnt/root-base /mnt/root
umount /mnt
'';
};
};
systemd.enable = true;
};
};
}