ZFS: Difference between revisions

From NixOS Wiki
imported>2r
(Update to OpenZFS documentation.)
(Add short command to know the difference between different disk/by-* paths)
 
(54 intermediate revisions by 24 users not shown)
Line 1: Line 1:
== Notes ==
[https://zfsonlinux.org/ {{PAGENAME}}] ([[wikipedia:en:{{PAGENAME}}]]) - also known as [https://openzfs.org/ OpenZFS] ([[wikipedia:en:OpenZFS]]) - is a modern filesystem[[category:filesystem]] which is well supported on [[NixOS]].
* 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 <code>boot.kernelPackages = config.boot.zfs.package.latestCompatibleLinuxPackages;</code>


* ZFS does not support swap. Hibernation must be either disabled with <code><nowiki>boot.kernelParams = [ "nohibernate" ];</nowiki></code>, or enabled with a separate, non-ZFS swap partition.
There are a lot of packages for [[{{PAGENAME}}]]. For example there is the ''zfs'' package (''ZFS Filesystem Linux Kernel module'') itself.<ref>https://search.nixos.org/packages?channel=unstable&show=zfs&query=zfs</ref> But there are also a lot of packages of the [[{{PAGENAME}}]] ecosystem available.


* By default, all ZFS pools available to the system will be forcibly imported during boot. This behaviour can be disabled by setting <syntaxhighlight lang="nix" inline>boot.zfs.forceImportAll = false;</syntaxhighlight>.
[[{{PAGENAME}}]] integrates into NixOS via its [[module]] system.  Examples:
* ''boot.zfs''<ref>https://search.nixos.org/options?channel=unstable&query=boot.zfs</ref>
* ''service.zfs''<ref>https://search.nixos.org/options?channel=unstable&query=services.zfs</ref>


* If you are running within a VM and NixOS fails to import the zpool on reboot, you may need to add <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-path";</syntaxhighlight> to your configuration.nix file.
== Limitations ==


==== latestCompatibleLinuxPackages of ZFS for boot.kernelPackages ====


== Enable ZFS support ==
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 <code>boot.kernelPackages = config.boot.zfs.package.latestCompatibleLinuxPackages;</code> to use the latest compatible kernel.


Common ZFS installation guides are now maintained at [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/index.html OpenZFS Documentation] website. Visit there for details and if an issue arises, submit an issue or pull request.
==== partial support for SWAP on ZFS ====


== Root on ZFS ==
ZFS does not support swapfiles. SWAP devices must be used instead. Additionally, hibernation is disabled by default due to a [https://github.com/NixOS/nixpkgs/pull/208037 high risk] of data corruption. Note that even if / after that pull request is merged, it does not fully mitigate the risk. If you wish to enable hibernation regardless, set <code>boot.zfs.allowHibernation = true</code>.


Root on ZFS guide is now maintained at [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/Root%20on%20ZFS.html OpenZFS Documentation] website. Visit there for details and if an issue arises, submit an issue or pull request.
==== boot.zfs.devNodes ====


== Mount datasets at boot ==
If NixOS fails to import the zpool on reboot, you may need to add <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-path";</syntaxhighlight> or <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-partuuid";</syntaxhighlight> to your configuration.nix file.
zfs-mount service is enabled by default on NixOS 22.05.


To automatically mount a dataset at boot, you only need to set <code>canmount=on</code> and <code>mountpoint=/mount/point</code> on the respective datasets.
The differences can be tested by running <code>zpool import -d /dev/disk/by-id</code> when none of the pools are discovered, eg. a live iso.


== Changing the Adaptive Replacement Cache size ==
==== declarative mounting of ZFS datasets ====


To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:
When using legacy mountpoints (created with eg<code>zfs create -o mountpoint=legacy</code>) mountpoints must be specified with <code>fileSystems."/mount/point" = {};</code>. ZFS native mountpoints are not managed as part of the system configuration but better support hibernation with a separate swap partition. This can lead to conflicts if ZFS mount service is also enabled for the same datasets. Disable it with <code>systemd.services.zfs-mount.enable = false;</code>.
<syntaxhighlight lang="nix">
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
</syntaxhighlight>


== Automatic scrubbing ==
== Guides ==


Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
==== '''OpenZFS Documentation for installing''' ====
<syntaxhighlight lang="nix">
services.zfs.autoScrub.enable = true;
</syntaxhighlight>


You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
{{warning|This guide is not endorsed by NixOS and some features like immutable root do not have upstream support and could break on updates. If an issue arises while following this guide, please consult the guides support channels.}}


== Reservations ==
One guide for a NixOS installation with ZFS is maintained at [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/ OpenZFS Documentation (''Getting Started'' for ''NixOS'')]


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.
It is about:
* [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/index.html#installation enabling ZFS on an existing NixOS installation] and
* [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/#root-on-zfs (installing NixOS with) Root on ZFS].


To reserve space create a new unused dataset that gets a guaranteed disk space of 1GB.
It is not about:
* Give understandable, easy to follow and close to the standard installation guide instructions
* integrating ZFS into your existing config


<syntaxhighlight lang="console">
# zfs create -o refreservation=1G -o mountpoint=none zroot/reserved
</syntaxhighlight>


where <code>zroot</code> should be replaced by a dataset in your pool.
==== '''Simple NixOS ZFS installation''' ====
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:


<syntaxhighlight lang="console">
Start from here in the NixOS manual: [https://nixos.org/manual/nixos/stable/#sec-installation-manual].
# zfs set refreservation=none zroot/reserved
Under manual partitioning [https://nixos.org/manual/nixos/stable/#sec-installation-manual-partitioning] do this instead:
</syntaxhighlight>


== How to use the auto-snapshotting service ==
'''Partition your disk with your favorite partition tool.'''


To auto-snapshot a ZFS filesystem or a ZVol, set its <code>com.sun:auto-snapshot</code> property to <code>true</code>, like this:
We need the following partitions:


<syntaxhighlight lang="console">
* 1G for boot partition with "boot" as the partition label (also called name in some tools) and ef00 as partition code
# zfs set com.sun:auto-snapshot=true <pool>/<fs>
* 10G for a swap partition with "swap" as the partition label and 8200 as partition code. We will encrypt this with a random secret on each boot.
</syntaxhighlight>
* The rest of disk space for zfs with "root" as the partition label and 8300 as partition code (default code)


(Note that by default this property will be inherited by all descendent datasets, but you can set their properties to false if you prefer.)
Reason for swap partition: ZFS does use a caching mechanism that is different from the normal Linux cache infrastructure.
In low-memory situations, ZFS therefore might need a bit longer to free up memory from its cache. The swap partition will help with that.


Then, to enable the auto-snapshot service, add this to your <code>configuration.nix</code>:
Example output from fdisk:
<syntaxhighlight lang="nix">
services.zfs.autoSnapshot.enable = true;
</syntaxhighlight>


And finally, run <code>nixos-rebuild switch</code> to activate the new configuration!
<syntaxhighlight lang="bash">
sudo gdisk /dev/nvme0n1
GPT fdisk (gdisk) version 1.0.9.1
...
Command (? for help): p
Disk /dev/nvme0n1: 500118192 sectors, 238.5 GiB
Sector size (logical/physical): 512/512 bytes
Disk identifier (GUID): CA926E8C-47F6-416A-AD1A-C2190CF5D1F8
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 500118158
Partitions will be aligned on 2048-sector boundaries
Total free space is 2669 sectors (1.3 MiB)


By default, the auto-snapshot service will keep the latest four 15-minute, 24 hourly, 7 daily, 4 weekly and 12 monthly snapshots.
Number  Start (sector)    End (sector)  Size      Code  Name
You can globally override this configuration by setting the desired number of snapshots in your <code>configuration.nix</code>, like this:
  1            2048        2099199  1024.0 MiB  EF00  boot
  2        2099200        23070719  10.0 GiB    8200  swap
  3        23070720      500117503  227.5 GiB  8300  root


<syntaxhighlight lang="nix">
Command (? for help):
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)
};
</syntaxhighlight>
</syntaxhighlight>


You can also disable a given type of snapshots on a per-dataset basis by setting a ZFS property, like this:
'''Make zfs pool with encryption and mount points:'''


<syntaxhighlight lang="console">
'''Note:''' zpool config can significantly affect performance (especially the ashift option) so you may want to do some research. The [https://jrs-s.net/2018/08/17/zfs-tuning-cheat-sheet/ ZFS tuning cheatsheet] or [https://wiki.archlinux.org/title/ZFS#Storage_pools ArchWiki] is a good place to start.
# zfs set com.sun:auto-snapshot:weekly=false <pool>/<fs>
<syntaxhighlight lang="bash">
</syntaxhighlight>
zpool create -O encryption=on -O keyformat=passphrase -O keylocation=prompt -O compression=zstd -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool /dev/nvme0n1p2


This would disable only weekly snapshots on the given filesystem.
zfs create zpool/root
zfs create zpool/nix
zfs create zpool/var
zfs create zpool/home


== Installing NixOS on a ZFS root filesystem ==
mkdir -p /mnt
mount -t zfs zpool/root /mnt -o zfsutil
mkdir /mnt/nix /mnt/var /mnt/home


Another guide titled "Encrypted ZFS mirror with mirrored boot on NixOS" is available at https://elis.nu/blog/2019/08/encrypted-zfs-mirror-with-mirrored-boot-on-nixos/.
mount -t zfs zpool/nix /mnt/nix -o zfsutil
mount -t zfs zpool/var /mnt/var -o zfsutil
mount -t zfs zpool/home /mnt/home -o zfsutil
</syntaxhighlight>


OpenZFS document for NixOS Root on ZFS is also available:
Output from <syntaxhighlight lang="bash" inline>zpool status</syntaxhighlight>:
https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/Root%20on%20ZFS.html
<syntaxhighlight >
zpool status
  pool: zpool
state: ONLINE
...
config:


This guide is based on the above OpenZFS guide and the NixOS installation instructions in the [https://nixos.org/manual/nixos/stable/index.html#sec-installation NixOS manual].
NAME                              STATE    READ WRITE CKSUM
zpool                              ONLINE      0    0    0
  nvme-eui.0025384b21406566-part2  ONLINE      0    0    0


=== Pool layout considerations ===
</syntaxhighlight>


it is important to keep <code>/nix</code> and the rest of the filesystem in
'''Make fat filesystem on boot partition'''
different sections of the dataset hierarchy, like this:
<syntaxhighlight lang="bash">
 
mkfs.fat -F 32 -n boot /dev/nvme0n1p1
<syntaxhighlight lang="text">
rpool/
      nixos/
            nix        mounted to /nix
      userdata/
            root        mounted to /
            home        mounted to /home
            ...
</syntaxhighlight>
</syntaxhighlight>


the name of <code>nixos</code> and <code>userdata/</code> can change, but them being peers is important.


ZFS can take consistent and atomic snapshots recursively down a dataset's hierarchy. Since Nix is good at being Nix, most users will want their server's ''data'' backed up, and don't mind reinstalling NixOS and then restoring data. If this is sufficient, only snapshot and back up the <code>userdata</code> hierarchy. Users who want to be able to restore a service with only ZFS snapshots will want to snapshot the entire tree, at the significant expense of snapshotting the Nix store.
'''Installation:'''


=== Dataset properties ===
Install: [https://nixos.org/manual/nixos/stable/#sec-installation-manual-installing]


The following is a list of recommended dataset properties which have no drawbacks under regular uses:
Jump to "2. UEFI systems"


* <code>compression=lz4</code> (<code>zstd</code> for higher-end machines)
<syntaxhighlight lang="bash">
* <code>xattr=sa</code> for Journald
mkdir -p /mnt/boot
* <code>acltype=posixacl</code> also for Journald
mount /dev/disk/by-partlabel/boot /mnt/boot
* <code>relatime=on</code> for reduced stress on SSDs
</syntaxhighlight>


The following is a list of dataset properties which are often useful, but do have drawbacks:
Jump to "4." ... /mnt/etc/nixos/configuration.nix ...


* <code>atime=off</code> disables if a file's access time is updated when the file is read. This can result in significant performance gains, but might confuse some software like mailers.
Continue from here and add this boot loader and filesystems config to your configuration.nix:


==== Journald ====
<syntaxhighlight lang="nix">
{
  # Boot loader config for configuration.nix:
  boot.loader.systemd-boot.enable = true;


Journald requires some properties for <code>journalctl</code> to work for non-root users. The dataset containing <code>/var/log/journal</code> (probably the <code>/</code> dataset for simple configurations) should be created with <code>xattr=sa</code> and <code>acltype=posixacl</code>.
  # for local disks that are not shared over the network, we don't need this to be random
  networking.hostId = "8425e349";
 
  fileSystems."/" = {
    device = "zpool/root";
    fsType = "zfs";
    # the zfsutil option is needed when mounting zfs datasets without "legacy" mountpoints
    options = [ "zfsutil" ];
  };


For example:
  fileSystems."/nix" = {
    device = "zpool/nix";
    fsType = "zfs";
    options = [ "zfsutil" ];
  };


<syntaxhighlight lang="console">
  fileSystems."/var" = {
# zpool create  -O xattr=sa -O acltype=posixacl rpool ...
    device = "zpool/var";
</syntaxhighlight>
    fsType = "zfs";
    options = [ "zfsutil" ];
  };


or:
  fileSystems."/home" = {
<syntaxhighlight lang="console">
    device = "zpool/home";
# zfs create -o xattr=sa -o acltype=posixacl rpool/root
    fsType = "zfs";
</syntaxhighlight>
    options = [ "zfsutil" ];
  };


If you have already created the dataset, these properties can be set later:
  fileSystems."/boot" = {
  device = "/dev/disk/by-partlabel/boot";
  fsType = "vfat";
  };


<syntaxhighlight lang="console">
  swapDevices = [{
# zfs set xattr=sa acltype=posixacl rpool/root
    device = "/dev/disk/by-partlabel/swap";
    randomEncryption = true;
  }];
}
</syntaxhighlight>
</syntaxhighlight>


=== Environment setup ===
== Importing on boot ==
For convenience set a shell variable with the paths to your disk(s):


For multiple disks:
If you create a zpool, it will not be imported on the next boot unless you either add the zpool name to <syntaxhighlight lang="nix" inline>boot.zfs.extraPools</syntaxhighlight>:
<syntaxhighlight lang="console">
$ disk=(/dev/disk/by-id/foo /dev/disk/by-id/bar)
</syntaxhighlight>


For a single disk:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="console">
## In /etc/nixos/configuration.nix:
$ disk=/dev/disk/by-id/foo
boot.zfs.extraPools = [ "zpool_name" ];
</syntaxhighlight>
</syntaxhighlight>


=== Partitioning the disks ===
or if you are using legacy mountpoints, add a <syntaxhighlight lang="nix" inline>fileSystems</syntaxhighlight> entry and NixOS will automatically detect that the pool needs to be imported:
<syntaxhighlight lang="bash">
# Multiple disks
for x in "${disk[@]}"; do
  sudo parted "$x" -- mklabel gpt
  sudo parted "$x" -- mkpart primary 512MiB -8GiB
  sudo parted "$x" -- mkpart primary linux-swap -8GiB 100%
  sudo parted "$x" -- mkpart ESP fat32 1MiB 512MiB
  sudo parted "$x" -- set 3 esp on


   sudo mkswap -L swap "${x}-part2"
<syntaxhighlight lang="nix">
   sudo mkfs.fat -F 32 -n EFI "${x}-part3"
## In /etc/nixos/configuration.nix:
done
fileSystems."/mount/point" = {
   device = "zpool_name";
   fsType = "zfs";
};
</syntaxhighlight>


# Single disk
=== Zpool created with bus-based disk names ===
sudo parted "$disk" -- mklabel gpt
If you used bus-based disk names in the <syntaxhighlight inline>zpool create</syntaxhighlight> command, e.g., <syntaxhighlight inline>/dev/sda</syntaxhighlight>, NixOS may run into issues importing the pool if the names change. Even if the pool is able to be mounted (with <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-partuuid";</syntaxhighlight> set), this may manifest as a <syntaxhighlight inline>FAULTED</syntaxhighlight> disk and a <syntaxhighlight inline>DEGRADED</syntaxhighlight> pool reported by <syntaxhighlight inline>zpool status</syntaxhighlight>. The fix is to re-import the pool using disk IDs:
sudo parted "$disk" -- mkpart primary 512MiB -8GiB
sudo parted "$disk" -- mkpart primary linux-swap -8GiB 100%
sudo parted "$disk" -- mkpart ESP fat32 1MiB 512MiB
sudo parted "$disk" -- set 3 esp on


sudo mkswap -L swap "${disk}-part2"
<syntaxhighlight>
sudo mkfs.fat -F 32 -n EFI "${disk}-part3"
# zpool export zpool_name
# zpool import -d /dev/disk/by-id zpool_name
</syntaxhighlight>
</syntaxhighlight>


=== Laying out the filesystem hierarchy ===
The import setting is reflected in <syntaxhighlight inline="" lang="bash">/etc/zfs/zpool.cache</syntaxhighlight>, so it should persist through subsequent boots.
==== Create the ZFS pool ====
<syntaxhighlight lang="bash">
sudo zpool create \
  -o ashift=12 \
  -o autotrim=on \
  -R /mnt \
  -O canmount=off \
  -O mountpoint=none \
  -O acltype=posixacl \
  -O compression=zstd \
  -O dnodesize=auto \
  -O normalization=formD \
  -O relatime=on \
  -O xattr=sa \
  -O encryption=aes-256-gcm \
  -O keylocation=prompt \
  -O keyformat=passphrase \
  rpool \
  mirror \
  "${disk[@]/%/-part1}"
</syntaxhighlight>


For a single disk, remove <code>mirror</code> and specify just <code>"${disk}-part1"</code> as the device.
=== Zpool created with disk IDs ===
If you used disk IDs to refer to disks in the <code>zpool create</code> command, e.g., <code>/dev/disk/by-id</code>, then NixOS may consistently fail to import the pool unless <code>boot.zfs.devNodes = "/dev/disk/by-id"</code> is also set.


If you do not want the entire pool to be encrypted, remove the options <code>encryption</code> <code>keylocation</code> and <code>keyformat</code>.
== Mount datasets at boot ==
zfs-mount service is enabled by default on NixOS 22.05.


==== Create the ZFS datasets ====
To automatically mount a dataset at boot, you only need to set <code>canmount=on</code> and <code>mountpoint=/mount/point</code> on the respective datasets.
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.
<syntaxhighlight lang="console">
# zfs create -o refreservation=1G -o mountpoint=none rpool/reserved
</syntaxhighlight>


Create the datasets for the operating system.  (Experienced ZFS users may wish to split up the OS datasets further.)
== Changing the Adaptive Replacement Cache size ==
<syntaxhighlight lang="bash">
sudo zfs create -o canmount=on -o mountpoint=/ rpool/nixos
sudo zfs create rpool/nixos/nix
</syntaxhighlight>


Create datasets for user home directories.  If you opted to not encrypt the entire pool, you can encrypt just the userdata by specifying the same ZFS properties when creating rpool/userdata, and the child datasets will also be encrypted.
To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:
<syntaxhighlight lang="bash">
<syntaxhighlight lang="nix">
sudo zfs create -o canmount=off -o mountpoint=/ rpool/userdata
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
sudo zfs create -o canmount=on rpool/userdata/home
sudo zfs create -o canmount=on -o mountpoint=/root rpool/userdata/home/root
# Create child datasets of home for users' home directories.
sudo zfs create -o canmount=on rpool/userdata/home/alice
sudo zfs create -o canmount=on rpool/userdata/home/bob
sudo zfs create -o canmount=on rpool/userdata/home/...
</syntaxhighlight>
</syntaxhighlight>


==== Mount <code>/boot</code> ====
== Tuning other parameters ==
We are going to use the default NixOS bootloader systemd-boot, which can install to only one device.  You will want to periodically rsync <code>/mnt/boot</code> to <code>/mnt/boot2</code> so that you can always boot your system if either disk fails.
<syntaxhighlight lang="bash">
sudo mkdir /mnt/boot /mnt/boot2
sudo mount "${disk[0]}-part3" /mnt/boot
sudo mount "${disk[1]}-part3" /mnt/boot2
</syntaxhighlight>


Or for single-disk systems:
To tune other attributes of ARC, L2ARC or of ZFS itself via runtime modprobe config, add this to your NixOS configuration (keys and values are examples only!):
<syntaxhighlight lang="bash">
<syntaxhighlight lang="nix">
sudo mkdir /mnt/boot
    boot.extraModprobeConfig = ''
sudo mount "${disk}-part3" /mnt/boot
      options zfs l2arc_noprefetch=0 l2arc_write_boost=33554432 l2arc_write_max=16777216 zfs_arc_max=2147483648
    '';
</syntaxhighlight>
</syntaxhighlight>


=== Configure the NixOS system ===
You can confirm whether any specified configuration/tuning got applied via commands like <code>arc_summary</code> and <code>arcstat -a -s " "</code>.
Generate the base NixOS configuration files.
<syntaxhighlight lang="console">
# nixos-generate-config --root /mnt
</syntaxhighlight>


Open <code>/mnt/etc/nixos/configuration.nix</code> in a text editor and change <code>imports</code> to include <code>hardware-configuration-zfs.nix</code> instead of the default <code>hardware-configuration.nix</code>.  We will be editing this file later.
== Automatic scrubbing ==


Now Add the following block of code anywhere (how you organise your <code>configuration.nix</code> is up to you):
Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
# ZFS boot settings.
boot.supportedFilesystems = [ "zfs" ];
boot.zfs.devNodes = "/dev/";
</syntaxhighlight>
Now set <code>networking.hostName</code> and <code>networking.hostId</code>.  The host ID must be an eight digit hexadecimal value.  You can derive it from the <code>/etc/machine-id</code>, taking the first eight characters; from the hostname, by taking the first eight characters of the hostname's md5sum,
<syntaxhighlight lang="console">
$ hostname | md5sum | head -c 8
</syntaxhighlight>
or by taking eight hexadecimal characters from <code>/dev/urandom</code>,
<syntaxhighlight lang="console">
$ tr -dc 0-9a-f < /dev/urandom | head -c 8
</syntaxhighlight>
Now add some ZFS maintenance settings:
<syntaxhighlight lang="nix">
# ZFS maintenance settings.
services.zfs.trim.enable = true;
services.zfs.autoScrub.enable = true;
services.zfs.autoScrub.enable = true;
services.zfs.autoScrub.pools = [ "rpool" ];
</syntaxhighlight>
</syntaxhighlight>


You may wish to also add <syntaxhighlight lang="nix" inline>services.zfs.autoSnapshot.enable = true;</syntaxhighlight> and set the ZFS property <code>com.sun:auto-snapshot</code> to <code>true</code> on <code>rpool/userdata</code> to have automatic snapshots.  (See [[#How to use the auto-snapshotting service]] earlier on this page.)
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).


Now open <code>/mnt/etc/nixos/hardware-configuration-zfs.nix</code>.
* Add <syntaxhighlight lang="nix" inline>options = [ "zfsutil" ];</syntaxhighlight> to every ZFS <code>fileSystems</code> block.
* Add <syntaxhighlight lang="nix" inline>options = [ "X-mount.mkdir" ];</syntaxhighlight> to <syntaxhighlight lang="nix" inline>fileSystems."/boot"</syntaxhighlight> and <syntaxhighlight lang="nix" inline>fileSystems."/boot2"</syntaxhighlight>.
* Replace <code>swapDevices</code> with the following, replacing <code>DISK1</code> and <code>DISK2</code> with the names of your disks.
<syntaxhighlight lang="nix">
swapDevices = [
  { device = "/dev/disk/by-id/DISK1-part2";
    randomEncryption = true;
  }
  { device = "/dev/disk/by-id/DISK2-part2";
    randomEncryption = true;
  }
];
</syntaxhighlight>
For single-disk installs, remove the second entry of this array.


==== Optional additional setup for encrypted ZFS ====
== Remote unlock ==
===== Unlock encrypted zfs via ssh on boot =====
=== Unlock encrypted zfs via ssh on boot ===


{{note|As of 22.05, rebuilding your config with the below directions may result in a situation where, if you want to revert the changes, you may need to do some pretty hairy nix-store manipulation to be able to successfully rebuild, see https://github.com/NixOS/nixpkgs/issues/101462#issuecomment-1172926129}}
{{note|As of 22.05, rebuilding your config with the below directions may result in a situation where, if you want to revert the changes, you may need to do some pretty hairy nix-store manipulation to be able to successfully rebuild, see https://github.com/NixOS/nixpkgs/issues/101462#issuecomment-1172926129}}
Line 336: Line 278:
       authorizedKeys = [ "ssh-rsa AAAA..." ];
       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
    '';
   };
   };
};
};
</syntaxhighlight>
</syntaxhighlight>
* In order to use DHCP in the initrd, network manager must not be enabled and <syntaxhighlight lang="nix" inline>networking.useDHCP = true;</syntaxhighlight> must be set.
* In order to use DHCP in the initrd, network manager must not be enabled and <syntaxhighlight lang="nix" inline>networking.useDHCP = true;</syntaxhighlight> 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. <syntaxhighlight lang="nix" inline>boot.initrd.kernelModules = [ "r8169" ];</syntaxhighlight>
* If your network card isn't started, you'll need to add the according kernel module to the kernel and initrd as well, e.g. <syntaxhighlight lang="nix">
boot.kernelModules = [ "r8169" ];
boot.initrd.kernelModules = [ "r8169" ];</syntaxhighlight>


===== Import and unlock multiple encrypted pools/dataset at boot =====
After that you can unlock your datasets using the following ssh command:
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 <code>boot.initrd.network.postCommands</code> option.


Unfortunately having an unlock key file stored in an encrypted zfs dataset cannot be used directly, so the pool must use <code>keyformat=passphrase</code> and <code>keylocation=prompt</code>.
<syntaxhighlight>
ssh -p 2222 root@host "zpool import -a; zfs load-key -a && killall zfs"
</syntaxhighlight>


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:
Alternatively you could also add the commands as postCommands to your configuration.nix, then you just have to ssh into the initrd:


<syntaxhighlight lang="nix">
<syntaxhighlight>
boot = {
boot = {
   initrd.network = {
   initrd.network = {
    enable = true;
    ssh = {
      enable = true;
      port = 2222;
      hostKeys = [ /path/to/ssh_host_rsa_key ];
      authorizedKeys = [ "ssh-rsa AAAA..." ];
    };
     postCommands = ''
     postCommands = ''
      zpool import tankXXX
    # Import all pools
      echo "zfs load-key -a; killall zfs" >> /root/.profile
    zpool import -a
    # Or import selected pools
    zpool import pool2
    zpool import pool3
    zpool import pool4
    # Add the load-key command to the .profile
    echo "zfs load-key -a; killall zfs" >> /root/.profile
     '';
     '';
   };
   };
Line 380: Line 311:
</syntaxhighlight>
</syntaxhighlight>


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.
After that you can unlock your datasets using the following ssh command:


=== Install NixOS ===
<syntaxhighlight>
<syntaxhighlight lang="console">
ssh -p 2222 root@host
# nixos-install --show-trace --root /mnt
</syntaxhighlight>
</syntaxhighlight>
<code>--show-trace</code> will show you where exactly things went wrong if <code>nixos-install</code> fails.  To take advantage of all cores on your system, also specify <code>--max-jobs n</code> replacing <code>n</code> with the number of cores on your machine.


== ZFS trim support for SSDs ==
== Reservations ==


ZFS 0.8 now also features trim support for SSDs.
On ZFS, the performance will deteriorate significantly when more than 80% of the available space is used. To avoid this, reserve disk space beforehand.  


=== How to use ZFS trimming ===
To reserve space create a new unused dataset that gets a guaranteed disk space of 10GB.


ZFS trimming works on one or more zpools and will trim each ssd inside it. There are two modes of it. One mode will manually trim the specified pool and the other will auto-trim pools. However the main difference is, that auto-trim will skip ranges that it considers too small while manually issued trim will trim all ranges.
<syntaxhighlight lang="console">
# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved
</syntaxhighlight>


To manually start trimming of a zpool run: <code>zpool trim tank</code>.
== Auto ZFS trimming ==
Since [https://github.com/NixOS/nixpkgs/pull/65331 PR-65331] this can be also done periodically (by default once a week) by setting <syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.


To set a pool for auto-trim run: <code>zpool set autotrim=on tank</code>
<syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.


To check the status of the manual trim, you can just run <code>zpool status -t</code>
This will periodically run <code>zpool trim</code>. Note that this is different from the <code>autotrim</code> pool property. For further information, see the <code>zpool-trim</code> and <code>zpoolprops</code> man pages.


To see the effects of trimming, you can run <code>zpool iostat -r</code> and <code>zpool iostat -w</code>
== Take snapshots automatically ==


To see whether auto-trimming works, just run <code>zpool iostat -r</code> note the results and run it later again. The trim entries should change.
See <code>services.sanoid</code> section in <code>man configuration.nix</code>.


For further information read the [https://github.com/zfsonlinux/zfs/pull/8419 PR description].
== NFS share ==


[[Category:Guide]]
With <code>sharenfs</code> property, ZFS has build-in support for generating <code>/etc/exports.d/zfs.exports</code> file, which in turn is processed by NFS service automatically.


{{warning|If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs '''your rule will not correctly apply''', and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - [https://github.com/openzfs/zfs/pull/11939 openzfs/zfs#11939]}}


Following are a few discourse posts on zfs, serving as pointers, form your own opinion
To enable NFS share on a dataset, only two steps are needed:
 
* https://discourse.nixos.org/t/zfs-dedup-on-nix-store-is-it-worth-it/4959
* https://discourse.nixos.org/t/how-to-add-extra-build-input-to-linux-kernel/8208/3
 
== 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. [https://search.nixos.org/options?query=services.zfs.zed zed options]
 
=== Alternative 1: Rebuild ZFS with Mail Support ===
The <code>zfs</code> 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 <code>zfs</code> is implicitly used in partition mounting:


First, enable [[NFS|NFS service]]:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
nixpkgs.config.packageOverrides = pkgs: {
services.nfs.server.enable = true;
  zfsStable = pkgs.zfsStable.override { enableMail = true; };
};
</syntaxhighlight>
</syntaxhighlight>
Only this line is needed. Configure firewall if necessary, as described in [[NFS]] article.


A mail sender like [[msmtp]] or [[postfix]] is required.
Then, set <code>sharenfs</code> property:
 
<syntaxhighlight lang="console">
A minimal, testable ZED configuration example:
# zfs set sharenfs="ro=192.168.1.0/24,all_squash,anonuid=70,anongid=70" rpool/myData
 
<syntaxhighlight lang="nix">
services.zfs.zed.enableMail = true;
services.zfs.zed.settings = {
  ZED_EMAIL_ADDR = [ "root" ];
  ZED_NOTIFY_VERBOSE = true;
};
</syntaxhighlight>
</syntaxhighlight>
For more options, see <code>man 5 exports</code>.


Above, <code>ZED_EMAIL_ADDR</code> is set to <code>root</code>, which most people will have an alias for in their mailer. You can change it to directly mail you: <code>ZED_EMAIL_ADDR = [ "you@example.com" ];</code>
Todo: sharesmb property for Samba.


ZED pulls in <code>mailutils</code> and runs <code>mail</code> by default, but you can override it with <code>ZED_EMAIL_PROG</code>. If using msmtp, you may need <code>ZED_EMAIL_PROG = "${pkgs.msmtp}/bin/msmtp";</code>.
== Mail notification for ZFS Event Daemon ==


You can customize the mail command with <code>ZED_EMAIL_OPTS</code>. For example, if your upstream mail server requires a certain FROM address: <code>ZED_EMAIL_OPTS = "-r 'noreply@example.com' -s '@SUBJECT@' @ADDRESS@";</code>
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. [https://search.nixos.org/options?query=services.zfs.zed zed options]


=== Alternative 2: Enable Mail Notification without Re-compliation ===
=== Alternative 1: Enable Mail Notification without Re-compliation ===


First, we need to configure a mail transfer agent, the program that sends email:
First, we need to configure a mail transfer agent, the program that sends email:
Line 513: Line 424:
</syntaxhighlight>
</syntaxhighlight>


== Mount datasets without legacy mountpoint ==
=== Alternative 2: Rebuild ZFS with Mail Support ===
Contrary to conventional wisdom, <code>mountpoint=legacy</code> is not required for mounting datasets. The trick is to use <code>mount -t zfs -o zfsutil path/to/dataset /path/to/mountpoint</code>.
The <code>zfs</code> 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.


Also, legacy mountpoints are also inconvenient in that the mounts can not be natively handled by <code>zfs mount</code> command, hence <code>legacy</code> in the name.
An alternative solution that does not involve recompliation can be found above.
 
The following override is needed as <code>zfs</code> is implicitly used in partition mounting:


An example configuration of mounting non-legacy dataset is the following:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{
nixpkgs.config.packageOverrides = pkgs: {
   fileSystems."/tank" =
   zfsStable = pkgs.zfsStable.override { enableMail = true; };
    { device = "tank_pool/data";
};
      fsType = "zfs"; options = [ "zfsutil" ];
    };
}
</syntaxhighlight>
</syntaxhighlight>


An alternative is to set <syntaxhighlight lang="nix" inline>boot.zfs.extraPools = [ pool_name ];</syntaxhighlight>, which is recommended by the documentation if you have many zfs filesystems.
A mail sender like [[msmtp]] or [[postfix]] is required.


== NFS share ==
A minimal, testable ZED configuration example:
With <code>sharenfs</code> property, ZFS has build-in support for generating <code>/etc/exports.d/zfs.exports</code> file, which in turn is processed by NFS service automatically.
 
{{warning|If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs '''your rule will not correctly apply''', and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - [https://github.com/openzfs/zfs/pull/11939 openzfs/zfs#11939]}}
 
To enable NFS share on a dataset, only two steps are needed:


First, enable [[NFS|NFS service]]:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
services.nfs.server.enable = true;
services.zfs.zed.enableMail = true;
services.zfs.zed.settings = {
  ZED_EMAIL_ADDR = [ "root" ];
  ZED_NOTIFY_VERBOSE = true;
};
</syntaxhighlight>
</syntaxhighlight>
Only this line is needed. Configure firewall if necessary, as described in [[NFS]] article.


Then, set <code>sharenfs</code> property:
Above, <code>ZED_EMAIL_ADDR</code> is set to <code>root</code>, which most people will have an alias for in their mailer. You can change it to directly mail you: <code>ZED_EMAIL_ADDR = [ "you@example.com" ];</code>
<syntaxhighlight lang="console">
 
# zfs set sharenfs="ro=192.168.1.0/24,all_squash,anonuid=70,anongid=70" rpool/myData
ZED pulls in <code>mailutils</code> and runs <code>mail</code> by default, but you can override it with <code>ZED_EMAIL_PROG</code>. If using msmtp, you may need <code>ZED_EMAIL_PROG = "${pkgs.msmtp}/bin/msmtp";</code>.
</syntaxhighlight>
For more options, see <code>man 5 exports</code>.


== See also ==
You can customize the mail command with <code>ZED_EMAIL_OPTS</code>. For example, if your upstream mail server requires a certain FROM address: <code>ZED_EMAIL_OPTS = "-r 'noreply@example.com' -s '@SUBJECT@' @ADDRESS@";</code>


This article on how to setup encrypted ZFS on Hetzner: <https://mazzo.li/posts/hetzner-zfs.html>.
[[Category:Guide]]

Latest revision as of 23:48, 3 June 2024

ZFS (wikipedia:en:ZFS) - also known as OpenZFS (wikipedia:en:OpenZFS) - is a modern filesystem which is well supported on NixOS.

There are a lot of packages for ZFS. For example there is the zfs package (ZFS Filesystem Linux Kernel module) itself.[1] But there are also a lot of packages of the ZFS ecosystem available.

ZFS integrates into NixOS via its module system. Examples:

Limitations

latestCompatibleLinuxPackages of ZFS for boot.kernelPackages

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; to use the latest compatible kernel.

partial support for SWAP on ZFS

ZFS does not support swapfiles. SWAP devices must be used instead. Additionally, hibernation is disabled by default due to a high risk of data corruption. Note that even if / after that pull request is merged, it does not fully mitigate the risk. If you wish to enable hibernation regardless, set boot.zfs.allowHibernation = true.

boot.zfs.devNodes

If NixOS fails to import the zpool on reboot, you may need to add boot.zfs.devNodes = "/dev/disk/by-path"; or boot.zfs.devNodes = "/dev/disk/by-partuuid"; to your configuration.nix file.

The differences can be tested by running zpool import -d /dev/disk/by-id when none of the pools are discovered, eg. a live iso.

declarative mounting of ZFS datasets

When using legacy mountpoints (created with egzfs create -o mountpoint=legacy) mountpoints must be specified with fileSystems."/mount/point" = {};. ZFS native mountpoints are not managed as part of the system configuration but better support hibernation with a separate swap partition. This can lead to conflicts if ZFS mount service is also enabled for the same datasets. Disable it with systemd.services.zfs-mount.enable = false;.

Guides

OpenZFS Documentation for installing

Warning: This guide is not endorsed by NixOS and some features like immutable root do not have upstream support and could break on updates. If an issue arises while following this guide, please consult the guides support channels.

One guide for a NixOS installation with ZFS is maintained at OpenZFS Documentation (Getting Started for NixOS)

It is about:

It is not about:

  • Give understandable, easy to follow and close to the standard installation guide instructions
  • integrating ZFS into your existing config


Simple NixOS ZFS installation

Start from here in the NixOS manual: [1]. Under manual partitioning [2] do this instead:

Partition your disk with your favorite partition tool.

We need the following partitions:

  • 1G for boot partition with "boot" as the partition label (also called name in some tools) and ef00 as partition code
  • 10G for a swap partition with "swap" as the partition label and 8200 as partition code. We will encrypt this with a random secret on each boot.
  • The rest of disk space for zfs with "root" as the partition label and 8300 as partition code (default code)

Reason for swap partition: ZFS does use a caching mechanism that is different from the normal Linux cache infrastructure. In low-memory situations, ZFS therefore might need a bit longer to free up memory from its cache. The swap partition will help with that.

Example output from fdisk:

sudo gdisk /dev/nvme0n1
GPT fdisk (gdisk) version 1.0.9.1
...
Command (? for help): p
Disk /dev/nvme0n1: 500118192 sectors, 238.5 GiB
Sector size (logical/physical): 512/512 bytes
Disk identifier (GUID): CA926E8C-47F6-416A-AD1A-C2190CF5D1F8
Partition table holds up to 128 entries
Main partition table begins at sector 2 and ends at sector 33
First usable sector is 34, last usable sector is 500118158
Partitions will be aligned on 2048-sector boundaries
Total free space is 2669 sectors (1.3 MiB)

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048         2099199   1024.0 MiB  EF00  boot
   2         2099200        23070719   10.0 GiB    8200  swap
   3        23070720       500117503   227.5 GiB   8300  root

Command (? for help):

Make zfs pool with encryption and mount points:

Note: zpool config can significantly affect performance (especially the ashift option) so you may want to do some research. The ZFS tuning cheatsheet or ArchWiki is a good place to start.

zpool create -O encryption=on -O keyformat=passphrase -O keylocation=prompt -O compression=zstd -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool /dev/nvme0n1p2

zfs create zpool/root
zfs create zpool/nix
zfs create zpool/var
zfs create zpool/home

mkdir -p /mnt
mount -t zfs zpool/root /mnt -o zfsutil
mkdir /mnt/nix /mnt/var /mnt/home

mount -t zfs zpool/nix /mnt/nix -o zfsutil
mount -t zfs zpool/var /mnt/var -o zfsutil
mount -t zfs zpool/home /mnt/home -o zfsutil

Output from zpool status:

zpool status
  pool: zpool
 state: ONLINE
...
config:

	NAME                               STATE     READ WRITE CKSUM
	zpool                              ONLINE       0     0     0
	  nvme-eui.0025384b21406566-part2  ONLINE       0     0     0

Make fat filesystem on boot partition

mkfs.fat -F 32 -n boot /dev/nvme0n1p1


Installation:

Install: [3]

Jump to "2. UEFI systems"

mkdir -p /mnt/boot
mount /dev/disk/by-partlabel/boot /mnt/boot

Jump to "4." ... /mnt/etc/nixos/configuration.nix ...

Continue from here and add this boot loader and filesystems config to your configuration.nix:

{
  # Boot loader config for configuration.nix:
  boot.loader.systemd-boot.enable = true;

  # for local disks that are not shared over the network, we don't need this to be random
  networking.hostId = "8425e349";

  fileSystems."/" = { 
    device = "zpool/root";
    fsType = "zfs";
    # the zfsutil option is needed when mounting zfs datasets without "legacy" mountpoints
    options = [ "zfsutil" ];
  };

  fileSystems."/nix" = { 
    device = "zpool/nix";
    fsType = "zfs";
    options = [ "zfsutil" ];
  };

  fileSystems."/var" = { 
    device = "zpool/var";
    fsType = "zfs";
    options = [ "zfsutil" ];
  };

  fileSystems."/home" = {
    device = "zpool/home";
    fsType = "zfs";
    options = [ "zfsutil" ];
  };

  fileSystems."/boot" = { 
   device = "/dev/disk/by-partlabel/boot";
   fsType = "vfat";
  };

  swapDevices = [{
    device = "/dev/disk/by-partlabel/swap";
    randomEncryption = true;
  }];
}

Importing on boot

If you create a zpool, it will not be imported on the next boot unless you either add the zpool name to boot.zfs.extraPools:

## In /etc/nixos/configuration.nix:
boot.zfs.extraPools = [ "zpool_name" ];

or if you are using legacy mountpoints, add a fileSystems entry and NixOS will automatically detect that the pool needs to be imported:

## In /etc/nixos/configuration.nix:
fileSystems."/mount/point" = {
  device = "zpool_name";
  fsType = "zfs";
};

Zpool created with bus-based disk names

If you used bus-based disk names in the zpool create command, e.g., /dev/sda, NixOS may run into issues importing the pool if the names change. Even if the pool is able to be mounted (with boot.zfs.devNodes = "/dev/disk/by-partuuid"; set), this may manifest as a FAULTED disk and a DEGRADED pool reported by zpool status. The fix is to re-import the pool using disk IDs:

# zpool export zpool_name
# zpool import -d /dev/disk/by-id zpool_name

The import setting is reflected in /etc/zfs/zpool.cache, so it should persist through subsequent boots.

Zpool created with disk IDs

If you used disk IDs to refer to disks in the zpool create command, e.g., /dev/disk/by-id, then NixOS may consistently fail to import the pool unless boot.zfs.devNodes = "/dev/disk/by-id" is also set.

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" ];

Tuning other parameters

To tune other attributes of ARC, L2ARC or of ZFS itself via runtime modprobe config, add this to your NixOS configuration (keys and values are examples only!):

    boot.extraModprobeConfig = ''
      options zfs l2arc_noprefetch=0 l2arc_write_boost=33554432 l2arc_write_max=16777216 zfs_arc_max=2147483648
    '';

You can confirm whether any specified configuration/tuning got applied via commands like arc_summary and arcstat -a -s " ".

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).


Remote unlock

Unlock encrypted zfs via ssh on boot

Note: As of 22.05, rebuilding your config with the below directions may result in a situation where, if you want to revert the changes, you may need to do some pretty hairy nix-store manipulation to be able to successfully rebuild, see https://github.com/NixOS/nixpkgs/issues/101462#issuecomment-1172926129

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..." ];
    };
  };
};
  • 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 kernel and initrd as well, e.g.
    boot.kernelModules = [ "r8169" ];
    boot.initrd.kernelModules = [ "r8169" ];
    

After that you can unlock your datasets using the following ssh command:

ssh -p 2222 root@host "zpool import -a; zfs load-key -a && killall zfs"

Alternatively you could also add the commands as postCommands to your configuration.nix, then you just have to ssh into the initrd:

boot = {
  initrd.network = {
    postCommands = ''
    # Import all pools
    zpool import -a
    # Or import selected pools
    zpool import pool2
    zpool import pool3
    zpool import pool4
    # Add the load-key command to the .profile
    echo "zfs load-key -a; killall zfs" >> /root/.profile
    '';
  };
};

After that you can unlock your datasets using the following ssh command:

ssh -p 2222 root@host

Reservations

On ZFS, the performance will deteriorate significantly when more than 80% of the available space is used. To avoid this, reserve disk space beforehand.

To reserve space create a new unused dataset that gets a guaranteed disk space of 10GB.

# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved

Auto ZFS trimming

services.zfs.trim.enable = true;.

This will periodically run zpool trim. Note that this is different from the autotrim pool property. For further information, see the zpool-trim and zpoolprops man pages.

Take snapshots automatically

See services.sanoid section in man configuration.nix.

NFS share

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.

Warning: If you are intending on defining an IPv6 subnet as part of your sharenfs rule, as of ZFS 2.0.6 (2021-09-23) please note that due to a bug in openzfs your rule will not correctly apply, and may result in a security vulnerability (CVE-2013-20001). A fix has been implemented in the next yet-to-be-released upstream version - openzfs/zfs#11939

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.

Todo: sharesmb property for Samba.

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: 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

Alternative 2: 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 above.

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@";