ZFS
Notes
- Newest kernels might not be supported by ZFS yet. If you are running an newer kernel which is not yet officially supported by zfs, the zfs module will refuse to evaluate and show up as broken. Use
boot.kernelPackages = config.boot.zfs.package.latestCompatibleLinuxPackages;
- ZFS does not support swap. Hibernation must be either disabled with
boot.kernelParams = [ "nohibernate" ];
, or enabled with a separate, non-ZFS swap partition.
- By default, all ZFS pools available to the system will be forcibly imported during boot. This behaviour can be disabled by setting
boot.zfs.forceImportAll = false;
.
- If you are running within a VM and NixOS fails to import the zpool on reboot, you may need to add
boot.zfs.devNodes = "/dev/disk/by-path";
to your configuration.nix file.
Enable ZFS support
Common ZFS installation guides are now maintained at OpenZFS Documentation website. Visit there for details and if an issue arises, submit an issue or pull request.
Root on ZFS
Root on ZFS guide is now maintained at OpenZFS Documentation website. Visit there for details and if an issue arises, submit an issue or pull request.
Mount datasets at boot
zfs-mount service is enabled by default on NixOS 22.05.
To automatically mount a dataset at boot, you only need to set canmount=on
and mountpoint=/mount/point
on the respective datasets.
Changing the Adaptive Replacement Cache size
To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
Automatic scrubbing
Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
services.zfs.autoScrub.enable = true;
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
Reservations
Since zfs is a copy-on-write filesystem even for deleting files disk space is needed. Therefore it should be avoided to run out of disk space. Luckily it is possible to reserve disk space for datasets to prevent this.
To reserve space create a new unused dataset that gets a guaranteed disk space of 1GB.
# zfs create -o refreservation=1G -o mountpoint=none zroot/reserved
where zroot
should be replaced by a dataset in your pool.
The dataset itself should not be used. In case you would run out of space you can shrink the reservation to reclaim enough disk space to cleanup the other data from the pool:
# zfs set refreservation=none zroot/reserved
Auto ZFS trimming
services.zfs.trim.enable = true;
.
For further information read the man pages.
Take snapshots automatically
To auto-snapshot a ZFS filesystem or a ZVol, set its com.sun:auto-snapshot
property to true
, like this:
# zfs set com.sun:auto-snapshot=true <pool>/<fs>
(Note that by default this property will be inherited by all descendant datasets, but you can set their properties to false if you prefer.)
Then, to enable the auto-snapshot service, add this to your configuration.nix
:
services.zfs.autoSnapshot.enable = true;
And finally, run nixos-rebuild switch
to activate the new configuration!
By default, the auto-snapshot service will keep the latest four 15-minute, 24 hourly, 7 daily, 4 weekly and 12 monthly snapshots.
You can globally override this configuration by setting the desired number of snapshots in your configuration.nix
, like this:
services.zfs.autoSnapshot = {
enable = true;
frequent = 8; # keep the latest eight 15-minute snapshots (instead of four)
monthly = 1; # keep only one monthly snapshot (instead of twelve)
};
You can also disable a given type of snapshots on a per-dataset basis by setting a ZFS property, like this:
# zfs set com.sun:auto-snapshot:weekly=false <pool>/<fs>
This would disable only weekly snapshots on the given filesystem.
Unlock encrypted zfs via ssh on boot
In case you want unlock a machine remotely (after an update), having an ssh service in initrd for the password prompt is handy:
boot = {
initrd.network = {
# This will use udhcp to get an ip address.
# Make sure you have added the kernel module for your network driver to `boot.initrd.availableKernelModules`,
# so your initrd can load it!
# Static ip addresses might be configured using the ip argument in kernel command line:
# https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt
enable = true;
ssh = {
enable = true;
# To prevent ssh clients from freaking out because a different host key is used,
# a different port for ssh is useful (assuming the same host has also a regular sshd running)
port = 2222;
# hostKeys paths must be unquoted strings, otherwise you'll run into issues with boot.initrd.secrets
# the keys are copied to initrd from the path specified; multiple keys can be set
# you can generate any number of host keys using
# `ssh-keygen -t ed25519 -N "" -f /path/to/ssh_host_ed25519_key`
hostKeys = [ /path/to/ssh_host_rsa_key ];
# public ssh key used for login
authorizedKeys = [ "ssh-rsa AAAA..." ];
};
# this will automatically load the zfs password prompt on login
# and kill the other prompt so boot can continue
postCommands = ''
cat <<EOF > /root/.profile
if pgrep -x "zfs" > /dev/null
then
zfs load-key -a
killall zfs
else
echo "zfs not running -- maybe the pool is taking some time to load for some unforseen reason."
fi
EOF
'';
};
};
- In order to use DHCP in the initrd, network manager must not be enabled and
networking.useDHCP = true;
must be set. - If your network card isn't started, you'll need to add the according kernel module to the initrd as well, e.g.
boot.initrd.kernelModules = [ "r8169" ];
Import and unlock multiple encrypted pools/dataset at boot
If you have not only one encrypted pool/dataset but multiple ones and you want to import and unlock them at boot, so that they can be automounted using the hardware-configuration.nix, you could just amend the boot.initrd.network.postCommands
option.
Unfortunately having an unlock key file stored in an encrypted zfs dataset cannot be used directly, so the pool must use keyformat=passphrase
and keylocation=prompt
.
The following example follows the remote unlocking with OpenSSH, but imports another pool also and prompts for unlocking (either when at the machine itself or when logging in remotely:
boot = {
initrd.network = {
enable = true;
ssh = {
enable = true;
port = 2222;
hostKeys = [ /path/to/ssh_host_rsa_key ];
authorizedKeys = [ "ssh-rsa AAAA..." ];
};
postCommands = ''
zpool import tankXXX
echo "zfs load-key -a; killall zfs" >> /root/.profile
'';
};
};
When you login by SSH into the box or when you have physical access to the machine itself, you will be prompted to supply the unlocking password for your zroot and tankXXX pools.
Mail notification for ZFS Event Daemon
ZFS Event Daemon (zed) monitors events generated by the ZFS kernel module and runs configured tasks. It can be configured to send an email when a pool scrub is finished or a disk has failed. zed options
Alternative 1: Rebuild ZFS with Mail Support
The zfs
package can be rebuilt with mail features. However, please note that this will cause Nix to recompile the entire ZFS package on the computer, and on every kernel update, which could be very time-consuming on lower-end NAS systems.
An alternative solution that does not involve recompliation can be found below.
The following override is needed as zfs
is implicitly used in partition mounting:
nixpkgs.config.packageOverrides = pkgs: {
zfsStable = pkgs.zfsStable.override { enableMail = true; };
};
A mail sender like msmtp or postfix is required.
A minimal, testable ZED configuration example:
services.zfs.zed.enableMail = true;
services.zfs.zed.settings = {
ZED_EMAIL_ADDR = [ "root" ];
ZED_NOTIFY_VERBOSE = true;
};
Above, ZED_EMAIL_ADDR
is set to root
, which most people will have an alias for in their mailer. You can change it to directly mail you: ZED_EMAIL_ADDR = [ "you@example.com" ];
ZED pulls in mailutils
and runs mail
by default, but you can override it with ZED_EMAIL_PROG
. If using msmtp, you may need ZED_EMAIL_PROG = "${pkgs.msmtp}/bin/msmtp";
.
You can customize the mail command with ZED_EMAIL_OPTS
. For example, if your upstream mail server requires a certain FROM address: ZED_EMAIL_OPTS = "-r 'noreply@example.com' -s '@SUBJECT@' @ADDRESS@";
Alternative 2: Enable Mail Notification without Re-compliation
First, we need to configure a mail transfer agent, the program that sends email:
{
programs.msmtp = {
enable = true;
setSendmail = true;
defaults = {
aliases = "/etc/aliases";
port = 465;
tls_trust_file = "/etc/ssl/certs/ca-certificates.crt";
tls = "on";
auth = "login";
tls_starttls = "off";
};
accounts = {
default = {
host = "mail.example.com";
passwordeval = "cat /etc/emailpass.txt";
user = "user@example.com";
from = "user@example.com";
};
};
};
}
Then, configure an alias for root account. With this alias configured, all mails sent to root, such as cron job results and failed sudo login events, will be redirected to the configured email account.
tee -a /etc/aliases <<EOF
root: user@example.com
EOF
Finally, override default zed settings with a custom one:
{
services.zfs.zed.settings = {
ZED_DEBUG_LOG = "/tmp/zed.debug.log";
ZED_EMAIL_ADDR = [ "root" ];
ZED_EMAIL_PROG = "${pkgs.msmtp}/bin/msmtp";
ZED_EMAIL_OPTS = "@ADDRESS@";
ZED_NOTIFY_INTERVAL_SECS = 3600;
ZED_NOTIFY_VERBOSE = true;
ZED_USE_ENCLOSURE_LEDS = true;
ZED_SCRUB_AFTER_RESILVER = true;
};
# this option does not work; will return error
services.zfs.zed.enableMail = false;
}
You can now test this by performing a scrub
# zpool scrub $pool
With sharenfs
property, ZFS has build-in support for generating /etc/exports.d/zfs.exports
file, which in turn is processed by NFS service automatically.
To enable NFS share on a dataset, only two steps are needed:
First, enable NFS service:
services.nfs.server.enable = true;
Only this line is needed. Configure firewall if necessary, as described in NFS article.
Then, set sharenfs
property:
# zfs set sharenfs="ro=192.168.1.0/24,all_squash,anonuid=70,anongid=70" rpool/myData
For more options, see man 5 exports
.