Difference between revisions of "ZFS"

From NixOS Wiki
Jump to: navigation, search
m (typo: smbshare -> sharesmb)
m (category (to classify the purpose of the software) added)
 
(21 intermediate revisions by 12 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 ==
  
== Enable ZFS support ==
+
==== latestCompatibleLinuxPackages of ZFS for boot.kernelPackages ====
  
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.
+
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.
  
==Importing on boot==
+
==== missing support for SWAP on ZFS ====
  
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>:
+
ZFS does not support swapfiles. Hibernation must be either disabled with <code><nowiki>boot.kernelParams = [ "nohibernate" ];</nowiki></code>, or be enabled with a separate, non-ZFS swap partition.
 +
 
 +
==== boot.zfs.devNodes in virtual machines ====
 +
 
 +
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> or <syntaxhighlight lang="nix" inline>boot.zfs.devNodes = "/dev/disk/by-partuuid";</syntaxhighlight> to your configuration.nix file.
 +
 
 +
==== declarative mounting of ZFS datasets ====
 +
 
 +
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>.
 +
 
 +
== 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 [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/ OpenZFS Documentation (''Getting Started'' for ''NixOS'')]
 +
 
 +
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].
 +
 
 +
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: [https://nixos.org/manual/nixos/stable/#sec-installation-manual].
 +
Under manual partitioning [https://nixos.org/manual/nixos/stable/#sec-installation-manual-partitioning] do this instead:
 +
 
 +
'''Partition your disk with an boot and an zfs partition with your favorite partition tool.'''
 +
 
 +
Eg. 1G for boot partion, rest for zfs.
 +
 
 +
Example output from fdisk:
 +
 
 +
<syntaxhighlight lang="bash">
 +
 
 +
fdisk /dev/nvme0n1
 +
Command (m for help): p
  
<syntaxhighlight lang="nix">
+
Disk /dev/nvme0n1: 931.51 GiB, 1000204886016 bytes, 1953525168 sectors
## In /etc/nixos/configuration.nix:
+
...
boot.zfs.extraPools = [ "zpool_name" ];
+
Device          Start        End    Sectors  Size Type
 +
/dev/nvme0n1p1    2048    2099199    2097152    1G EFI System
 +
/dev/nvme0n1p2 2099200 1953523711 1951424512 930.5G Linux filesystem
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
'''Note:''' Remember to set boot partition (first partition) to "EFI System" type
  
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:
+
'''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 [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.
 +
<syntaxhighlight lang="bash">
 +
zpool create -O encryption=on -O keyformat=passphrase -O keylocation=prompt -O compression=on -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool /dev/nvme0n1p2
 +
 
 +
zfs create -o mountpoint=legacy zpool/root
 +
zfs create -o mountpoint=legacy zpool/nix
 +
zfs create -o mountpoint=legacy zpool/var
 +
zfs create -o mountpoint=legacy zpool/home
 +
 
 +
mkdir /mnt/root
 +
mount -t zfs zpool/root /mnt
 +
mkdir /mnt/nix /mnt/var /mnt/home
  
<syntaxhighlight lang="nix">
+
mount -t zfs zpool/nix /mnt/nix
## In /etc/nixos/configuration.nix:
+
mount -t zfs zpool/var /mnt/var
fileSystems."/mount/point" = {
+
mount -t zfs zpool/home /mnt/home
  device = "zpool_name";
 
  fsType = "zfs";
 
};
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== Root on ZFS ==
+
Output from <syntaxhighlight lang="bash" inline>zpool status</syntaxhighlight>:
 +
<syntaxhighlight >
 +
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
  
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.
+
</syntaxhighlight>
  
== Immutable Root on ZFS ==
+
'''Make fat filesystem on boot partition'''
 +
<syntaxhighlight lang="bash">
 +
mkfs.fat -F 32 -n boot /dev/nvme0n1p1
 +
</syntaxhighlight>
  
After following the [https://openzfs.github.io/openzfs-docs/Getting%20Started/NixOS/Root%20on%20ZFS.html OpenZFS Documentation], immutable root can be optionally enabled to clean up root filesystem at boot.
+
'''Installation:'''
  
This involves mounting the existing root at a different location and bind mount necessary configuration files from the new mount point. We will use <code>/altroot</code> here.
+
Install: [https://nixos.org/manual/nixos/stable/#sec-installation-manual-installing]
  
<syntaxhighlight lang="nix">
+
Jump to "2. UEFI systems"
## In /etc/nixos/configuration.nix:
 
  systemd.services.zfs-mount.enable = false;
 
  
boot.initrd.postDeviceCommands = ''
+
<syntaxhighlight lang="bash">
  zpool import -Nf rpool
+
mkdir -p /mnt/boot
  zfs rollback -r rpool/nixos/empty@start
+
mount /dev/disk/by-label/boot /mnt/boot
  zpool export -a
 
'';
 
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Jump to "4." ... /mnt/etc/nixos/configuration.nix ...
 +
 +
Continue from here and add this boot loader and filesystems config to your configuration.nix:
  
 
<syntaxhighlight lang="nix">
 
<syntaxhighlight lang="nix">
## In /etc/nixos/hardware-configuration.nix:
+
Boot loader config for configuration.nix:
 +
  boot.loader.grub = {
 +
    enable = true;
 +
    zfsSupport = true;
 +
    efiSupport = true;
 +
    efiInstallAsRemovable = true;
 +
    mirroredBoots = [
 +
      { devices = [ "nodev"]; path = "/boot"; }
 +
    ];
 +
  };
 +
 
 +
  fileSystems."/" =
 +
    { device = "zpool/root";
 +
      fsType = "zfs";
 +
    };
 +
 
 +
  fileSystems."/nix" =
 +
    { device = "zpool/nix";
 +
      fsType = "zfs";
 +
    };
  
## Create new root datasets
+
  fileSystems."/var" =
# zfs create -o canmount=noauto -o mountpoint=/ rpool/nixos/empty
+
    { device = "zpool/var";
# zfs snapshot rpool/nixos/empty@start
+
      fsType = "zfs";
 +
    };
  
## Replace existing entry for / (root) with
+
   fileSystems."/home" =
   fileSystems."/" =
+
     { device = "zpool/home";
     { device = "rpool/nixos/empty";
+
       fsType = "zfs";
       fsType = "zfs"; options = [ "zfsutil" "noatime" "X-mount.mkdir" ];
 
 
     };
 
     };
  
## Mount old root at /altroot
+
   fileSystems."/boot" =
## noatime option is used for better performance
+
     { device = "/dev/disk/by-uuid/2A11-F4EF";
   fileSystems."/altroot" =
+
       fsType = "vfat";
     { device = "rpool/nixos/root";
 
       fsType = "zfs"; options = [ "zfsutil" "noatime" "X-mount.mkdir" ];
 
      neededForBoot = true;
 
 
     };
 
     };
  
## /nix/ is needed for the system to boot, so
+
  swapDevices = [ ];
## bind mount it from old root
+
</syntaxhighlight>
  fileSystems."/nix" = {
+
 
    device = "/altroot/nix";
+
'''Note:''' Remove / comment out <syntaxhighlight lang="nix" inline>boot.loader.systemd-boot.enable = true;</syntaxhighlight> config if added by<syntaxhighlight lang="nix" inline>nixos-generate-config</syntaxhighlight>
    fsType = "none";
+
 
    options = [ "bind" "X-mount.mkdir" ];
+
== 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 <syntaxhighlight lang="nix" inline>boot.zfs.extraPools</syntaxhighlight>:
 +
 
 +
<syntaxhighlight lang="nix">
 +
## In /etc/nixos/configuration.nix:
 +
boot.zfs.extraPools = [ "zpool_name" ];
 +
</syntaxhighlight>
 +
 
 +
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:
  
## /etc/nixos/ stores system configuration
+
<syntaxhighlight lang="nix">
  fileSystems."/etc/nixos" = {
+
## In /etc/nixos/configuration.nix:
    device = "/altroot/etc/nixos";
+
fileSystems."/mount/point" = {
    fsType = "none";
+
  device = "zpool_name";
    options = [ "bind" "X-mount.mkdir" ];
+
  fsType = "zfs";
  };
+
};
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 121: Line 213:
 
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
 
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
  
== 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.
 
 
<syntaxhighlight lang="console">
 
# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved
 
</syntaxhighlight>
 
 
== Auto ZFS trimming ==
 
 
<syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.
 
 
For further information read the man pages.
 
 
== Take snapshots automatically ==
 
 
See <code>services.sanoid</code> section in <code>man configuration.nix</code>.
 
  
 
== Remote unlock ==
 
== Remote unlock ==
Line 181: Line 254:
  
 
<syntaxhighlight>
 
<syntaxhighlight>
ssh root@host -p 2222 "zpool import -a; zfs load-key -a && killall zfs"
+
ssh -p 2222 root@host "zpool import -a; zfs load-key -a && killall zfs"
 +
</syntaxhighlight>
 +
 
 +
Alternatively you could also add the commands as postCommands to your configuration.nix, then you just have to ssh into the initrd:
 +
 
 +
<syntaxhighlight>
 +
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
 +
    '';
 +
  };
 +
};
 +
</syntaxhighlight>
 +
 
 +
After that you can unlock your datasets using the following ssh command:
 +
 
 +
<syntaxhighlight>
 +
ssh -p 2222 root@host
 +
</syntaxhighlight>
 +
 
 +
== 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.
 +
 
 +
<syntaxhighlight lang="console">
 +
# zfs create -o refreservation=10G -o mountpoint=none zroot/reserved
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
== Auto ZFS trimming ==
 +
 +
<syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.
 +
 +
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.
 +
 +
== Take snapshots automatically ==
 +
 +
See <code>services.sanoid</code> section in <code>man configuration.nix</code>.
  
 
== NFS share ==
 
== NFS share ==
 +
 
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.
 
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.
  

Latest revision as of 12:07, 15 February 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.

missing support for SWAP on ZFS

ZFS does not support swapfiles. Hibernation must be either disabled with boot.kernelParams = [ "nohibernate" ];, or be enabled with a separate, non-ZFS swap partition.

boot.zfs.devNodes in virtual machines

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"; or boot.zfs.devNodes = "/dev/disk/by-partuuid"; to your configuration.nix file.

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 an boot and an zfs partition with your favorite partition tool.

Eg. 1G for boot partion, rest for zfs.

Example output from fdisk:

fdisk /dev/nvme0n1
Command (m for help): p

Disk /dev/nvme0n1: 931.51 GiB, 1000204886016 bytes, 1953525168 sectors
...
Device           Start        End    Sectors   Size Type
/dev/nvme0n1p1    2048    2099199    2097152     1G EFI System
/dev/nvme0n1p2 2099200 1953523711 1951424512 930.5G Linux filesystem

Note: Remember to set boot partition (first partition) to "EFI System" type

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=on -O mountpoint=none -O xattr=sa -O acltype=posixacl -o ashift=12 zpool /dev/nvme0n1p2

zfs create -o mountpoint=legacy zpool/root
zfs create -o mountpoint=legacy zpool/nix
zfs create -o mountpoint=legacy zpool/var
zfs create -o mountpoint=legacy zpool/home

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

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

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-label/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.grub = {
    enable = true;
    zfsSupport = true;
    efiSupport = true;
    efiInstallAsRemovable = true;
    mirroredBoots = [
      { devices = [ "nodev"]; path = "/boot"; }
    ];
  };

  fileSystems."/" =
    { device = "zpool/root";
      fsType = "zfs";
    };

  fileSystems."/nix" =
    { device = "zpool/nix";
      fsType = "zfs";
    };

  fileSystems."/var" =
    { device = "zpool/var";
      fsType = "zfs";
    };

  fileSystems."/home" =
    { device = "zpool/home";
      fsType = "zfs";
    };

  fileSystems."/boot" =
    { device = "/dev/disk/by-uuid/2A11-F4EF";
      fsType = "vfat";
    };

  swapDevices = [ ];

Note: Remove / comment out boot.loader.systemd-boot.enable = true; config if added bynixos-generate-config

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

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