Jump to content

ZFS: Difference between revisions

3,250 bytes added ,  3 June
Add short command to know the difference between different disk/by-* paths
imported>2r
(zfs root)
(Add short command to know the difference between different disk/by-* paths)
 
(47 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 ==


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


== Root on ZFS ==
==== partial support for SWAP on ZFS ====


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


== Immutable Root on ZFS ==
==== boot.zfs.devNodes ====


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


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


<syntaxhighlight lang="nix">
==== declarative mounting of ZFS datasets ====
## In /etc/nixos/configuration.nix:
 
  systemd.services.zfs-mount.enable = false;
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 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:
 
<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)
 
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


boot.initrd.postDeviceCommands = ''
Command (? for help):
  zpool import -Nf rpool
  zfs rollback -r rpool/nixos/empty@start
  zpool export -a
'';
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang="nix">
'''Make zfs pool with encryption and mount points:'''
## In /etc/nixos/hardware-configuration.nix:
 
'''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=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


## Create new root datasets
mkdir -p /mnt
# zfs create -o canmount=noauto -o mountpoint=/ rpool/nixos/empty
mount -t zfs zpool/root /mnt -o zfsutil
# zfs snapshot rpool/nixos/empty@start
mkdir /mnt/nix /mnt/var /mnt/home


## Replace existing entry for / (root) with
mount -t zfs zpool/nix /mnt/nix -o zfsutil
  fileSystems."/" =
mount -t zfs zpool/var /mnt/var -o zfsutil
    { device = "rpool/nixos/empty";
mount -t zfs zpool/home /mnt/home -o zfsutil
      fsType = "zfs"; options = [ "zfsutil" "noatime" "X-mount.mkdir" ];
</syntaxhighlight>
    };


## Mount old root at /altroot
Output from <syntaxhighlight lang="bash" inline>zpool status</syntaxhighlight>:
## noatime option is used for better performance
<syntaxhighlight >
   fileSystems."/altroot" =
zpool status
    { device = "rpool/nixos/root";
   pool: zpool
      fsType = "zfs"; options = [ "zfsutil" "noatime" "X-mount.mkdir" ];
state: ONLINE
      neededForBoot = true;
...
    };
config:


## /nix/ is needed for the system to boot, so
NAME                              STATE    READ WRITE CKSUM
## bind mount it from old root
zpool                              ONLINE      0     0     0
  fileSystems."/nix" = {
  nvme-eui.0025384b21406566-part2  ONLINE      0    0    0
     device = "/altroot/nix";
     fsType = "none";
    options = [ "bind" "X-mount.mkdir" ];
  };


## /etc/nixos/ stores system configuration
  fileSystems."/etc/nixos" = {
    device = "/altroot/etc/nixos";
    fsType = "none";
    options = [ "bind" "X-mount.mkdir" ];
  };
</syntaxhighlight>
</syntaxhighlight>


'''Optional''': stateless home directory.  This requires you to keep track of your dot files with a version control system.  Git is used here as an example.
'''Make fat filesystem on boot partition'''
<syntaxhighlight lang="bash">
mkfs.fat -F 32 -n boot /dev/nvme0n1p1
</syntaxhighlight>


<syntaxhighlight lang="nix">
## In /etc/nixos/configuration.nix:


## Manage home with home-manager
'''Installation:'''
  environment.systemPackages = with pkgs; [
    home-manager
  ];


## Disable mutable users
Install: [https://nixos.org/manual/nixos/stable/#sec-installation-manual-installing]
  users.mutableUsers = false;


## Password hashes now need to be declared in config
Jump to "2. UEFI systems"
## generate hash with mkpasswd -m SHA-512 -s
    users.users.myUser.initialHashedPassword = "HASH";


## New service to fix home permissions
<syntaxhighlight lang="bash">
  systemd.services.home-perm = {
mkdir -p /mnt/boot
    enable = true;
mount /dev/disk/by-partlabel/boot /mnt/boot
    description = "Fix home dir permission";
    wantedBy = [ "multi-user.target" ];
    path = [ pkgs.coreutils pkgs.git ];
    after = [ "local-fs.target" ];
    serviceConfig = {
      ExecStart = ''/bin/sh -c "git -C /home/myUser reset --hard; chown -R myUser:users /home/myUser; chmod  700 /home/myUser"'';
      User = "root";
      Type = "oneshot";
      PrivateTmp = "true";
      ProtectSystem = "full";
      WorkingDirectory = "/tmp";
    };
  };
</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:
{
   fileSystems."/home/myUser" = {
  # Boot loader config for configuration.nix:
     device = "none";
  boot.loader.systemd-boot.enable = true;
     fsType = "tmpfs";
 
     options = [ "defaults" "size=1G" "mode=755" "X-mount=mkdir" ];
  # 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."/home/myUser/.git" = {
   fileSystems."/var" = {  
     device = "/altroot/home/myUser/.git";
     device = "zpool/var";
     fsType = "none";
     fsType = "zfs";
     options = [ "bind" "X-mount.mkdir" ];
     options = [ "zfsutil" ];
   };
   };


   fileSystems."/home/myUser/Downloads" = {
   fileSystems."/home" = {
     device = "/altroot/home/myUser/Downloads";
     device = "zpool/home";
     fsType = "none";
     fsType = "zfs";
     options = [ "bind" "X-mount.mkdir" ];
     options = [ "zfsutil" ];
   };
   };


   fileSystems."/home/myUser/Documents" = {
   fileSystems."/boot" = {  
    device = "/altroot/home/myUser/Documents";
  device = "/dev/disk/by-partlabel/boot";
    fsType = "none";
  fsType = "vfat";
    options = [ "bind" "X-mount.mkdir" ];
   };
   };
  swapDevices = [{
    device = "/dev/disk/by-partlabel/swap";
    randomEncryption = true;
  }];
}
</syntaxhighlight>
</syntaxhighlight>


== Mount datasets at boot ==
== Importing on boot ==
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.
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>:


== 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:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
## In /etc/nixos/configuration.nix:
boot.zfs.extraPools = [ "zpool_name" ];
</syntaxhighlight>
</syntaxhighlight>


== Automatic scrubbing ==
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:


Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
services.zfs.autoScrub.enable = true;
## In /etc/nixos/configuration.nix:
</syntaxhighlight>
fileSystems."/mount/point" = {
 
  device = "zpool_name";
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
  fsType = "zfs";
 
};
== 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.
 
<syntaxhighlight lang="console">
# zfs create -o refreservation=1G -o mountpoint=none zroot/reserved
</syntaxhighlight>
</syntaxhighlight>


where <code>zroot</code> should be replaced by a dataset in your pool.
=== Zpool created with bus-based disk names ===
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:
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:


<syntaxhighlight lang="console">
<syntaxhighlight>
# zfs set refreservation=none zroot/reserved
# zpool export zpool_name
# zpool import -d /dev/disk/by-id zpool_name
</syntaxhighlight>
</syntaxhighlight>


== Auto ZFS trimming ==
The import setting is reflected in <syntaxhighlight inline="" lang="bash">/etc/zfs/zpool.cache</syntaxhighlight>, so it should persist through subsequent boots.


<syntaxhighlight lang="nix" inline>services.zfs.trim.enable = true;</syntaxhighlight>.
=== 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.


For further information read the man pages.
== Mount datasets at boot ==
zfs-mount service is enabled by default on NixOS 22.05.


== Take snapshots automatically ==
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.


To auto-snapshot a ZFS filesystem or a ZVol, set its <code>com.sun:auto-snapshot</code> property to <code>true</code>, like this:
== Changing the Adaptive Replacement Cache size ==


<syntaxhighlight lang="console">
To change the maximum size of the ARC to (for example) 12 GB, add this to your NixOS configuration:
# zfs set com.sun:auto-snapshot=true <pool>/<fs>
<syntaxhighlight lang="nix">
boot.kernelParams = [ "zfs.zfs_arc_max=12884901888" ];
</syntaxhighlight>
</syntaxhighlight>


(Note that by default this property will be inherited by all descendant datasets, but you can set their properties to false if you prefer.)
== Tuning other parameters ==


Then, to enable the auto-snapshot service, add this to your <code>configuration.nix</code>:
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="nix">
<syntaxhighlight lang="nix">
services.zfs.autoSnapshot.enable = true;
    boot.extraModprobeConfig = ''
      options zfs l2arc_noprefetch=0 l2arc_write_boost=33554432 l2arc_write_max=16777216 zfs_arc_max=2147483648
    '';
</syntaxhighlight>
</syntaxhighlight>


And finally, run <code>nixos-rebuild switch</code> to activate the new configuration!
You can confirm whether any specified configuration/tuning got applied via commands like <code>arc_summary</code> and <code>arcstat -a -s " "</code>.


By default, the auto-snapshot service will keep the latest four 15-minute, 24 hourly, 7 daily, 4 weekly and 12 monthly snapshots.
== Automatic scrubbing ==
You can globally override this configuration by setting the desired number of snapshots in your <code>configuration.nix</code>, like this:


Regular scrubbing of ZFS pools is recommended and can be enabled in your NixOS configuration via:
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
services.zfs.autoSnapshot = {
services.zfs.autoScrub.enable = true;
  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:
You can tweak the interval (defaults to once a week) and which pools should be scrubbed (defaults to all).
 
<syntaxhighlight lang="console">
# zfs set com.sun:auto-snapshot:weekly=false <pool>/<fs>
</syntaxhighlight>


This would disable only weekly snapshots on the given filesystem.


== Unlock encrypted zfs via ssh on boot ==
== 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}}
{{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 240: 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 284: 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:
 
<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>
 
== 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.


Line 305: Line 357:
For more options, see <code>man 5 exports</code>.
For more options, see <code>man 5 exports</code>.


Todo: smbshare property for Samba.
Todo: sharesmb property for Samba.


== Mail notification for ZFS Event Daemon ==
== Mail notification for ZFS Event Daemon ==
Line 311: Line 363:
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]
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 ===
=== Alternative 1: Enable Mail Notification without Re-compliation ===
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:
 
<syntaxhighlight lang="nix">
nixpkgs.config.packageOverrides = pkgs: {
  zfsStable = pkgs.zfsStable.override { enableMail = true; };
};
</syntaxhighlight>
 
A mail sender like [[msmtp]] or [[postfix]] is required.
 
A minimal, testable ZED configuration example:
 
<syntaxhighlight lang="nix">
services.zfs.zed.enableMail = true;
services.zfs.zed.settings = {
  ZED_EMAIL_ADDR = [ "root" ];
  ZED_NOTIFY_VERBOSE = true;
};
</syntaxhighlight>
 
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>
 
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>.
 
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>
 
=== Alternative 2: 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 402: Line 423:
# zpool scrub $pool
# zpool scrub $pool
</syntaxhighlight>
</syntaxhighlight>
=== Alternative 2: 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 above.
The following override is needed as <code>zfs</code> is implicitly used in partition mounting:
<syntaxhighlight lang="nix">
nixpkgs.config.packageOverrides = pkgs: {
  zfsStable = pkgs.zfsStable.override { enableMail = true; };
};
</syntaxhighlight>
A mail sender like [[msmtp]] or [[postfix]] is required.
A minimal, testable ZED configuration example:
<syntaxhighlight lang="nix">
services.zfs.zed.enableMail = true;
services.zfs.zed.settings = {
  ZED_EMAIL_ADDR = [ "root" ];
  ZED_NOTIFY_VERBOSE = true;
};
</syntaxhighlight>
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>
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>.
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>


[[Category:Guide]]
[[Category:Guide]]
17

edits