Files
alo-cluster/common/impermanence.nix

74 lines
1.8 KiB
Nix

{
pkgs,
lib,
config,
...
}:
let
cfg = config.custom.impermanence;
in
{
# Import common impermanence configuration
imports = [ ./impermanence-common.nix ];
options.custom.impermanence = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Enable impermanent root fs with btrfs subvolume rollback";
};
};
config = lib.mkIf cfg.enable {
# Use /persist for btrfs-based impermanence
custom.impermanence.persistPath = "/persist";
# Btrfs-specific filesystem options
fileSystems."/".options = [
"compress=zstd"
"noatime"
];
fileSystems."/nix".options = [
"compress=zstd"
"noatime"
];
fileSystems."/persist".options = [
"compress=zstd"
"noatime"
];
fileSystems."/persist".neededForBoot = true;
fileSystems."/var/log".options = [
"compress=zstd"
"noatime"
];
fileSystems."/var/log".neededForBoot = true;
# Btrfs subvolume rollback at each boot
# Note `lib.mkBefore` is used instead of `lib.mkAfter` here.
boot.initrd.postDeviceCommands = pkgs.lib.mkBefore ''
mkdir /mnt
mount ${config.fileSystems."/".device} /mnt
if [[ -e /mnt/root ]]; then
mkdir -p /mnt/old_roots
timestamp=$(date --date="@$(stat -c %Y /mnt/root)" "+%Y-%m-%-d_%H:%M:%S")
mv /mnt/root "/mnt/old_roots/$timestamp"
fi
delete_subvolume_recursively() {
IFS=$'\n'
for i in $(btrfs subvolume list -o "$1" | cut -f 9- -d ' '); do
delete_subvolume_recursively "/mnt/$i"
done
btrfs subvolume delete "$1"
}
for i in $(find /mnt/old_roots/ -maxdepth 1 -mtime +30); do
delete_subvolume_recursively "$i"
done
btrfs subvolume create /mnt/root
umount /mnt
'';
};
}