Zfs on linux install

Install Arch Linux on ZFS

This article details the steps required to install Arch Linux onto a ZFS root filesystem.

Contents

Installation

To install Archlinux on ZFS, you need to boot archiso system with ZFS module.

Get ZFS module on archiso system

A script to easily install and load the ZFS module on running archiso system. It should work on any archiso version.

Embedding ZFS module into custom archiso

To build a custom archiso, see ZFS article.

An unofficial weekly build is available here.

Partition the destination drive

Review Partitioning for information on determining the partition table type to use for ZFS. ZFS supports GPT and MBR partition tables.

ZFS manages its own partitions, so only a basic partition table scheme is required. The partition that will contain the ZFS filesystem should be of the type bf00 , or «Solaris Root».

Drives larger than 2TB require a GPT partition table. GRUB on BIOS/GPT configurations require a small (1

2MiB) BIOS boot partition to embed its image of boot code.

Depending upon your machine’s firmware or your choice of boot mode, booting may or may not require an EFI partition. On a BIOS machine (or a UEFI machine booting in legacy mode) EFI partition is not required. Consult Arch boot process#Boot loader for more information.

Partition scheme

Here is an example of a basic partition scheme that could be employed for your ZFS root install on a BIOS/MBR installation using GRUB:

Using GRUB on a BIOS (or UEFI machine in legacy boot mode) machine but using a GPT partition table:

Another example, this time using a UEFI-specific bootloader (such as rEFInd) with an GPT partition table:

ZFS does not support swap files. If you require a swap partition, see ZFS#Swap volume for creating a swap ZVOL.

Example parted commands

Here are some example commands to partition a drive for the second scenario above ie using BIOS/legacy boot mode with a GPT partition table and a (slighty more than) 1MB BIOS boot partition for GRUB:

You can achieve the above in a single command like so:

If you are creating an EFI partition then that should have the boot flag set instead of the root partition.

Format the destination disk

If you have opted for a boot partition as well as any other non-ZFS system partitions then format them. Do not do anything to the Solaris partition nor to the BIOS boot partition. ZFS will manage the first, and your bootloader the second.

Setup the ZFS filesystem

First, make sure the ZFS modules are loaded,

Create the root zpool

Create your pool and set all default dataset options. All dataset created on the zpool will inherit of each -O set at the zpool creation. Default options are detailed in Debian Buster Root on ZFS. Step 2: Disk Formatting.

Compression and native encryption

This will enable compression and native encryption by default on all datasets:

Create your datasets

Instead of using conventional disk partitions, ZFS has the concept of datasets to manage your storage. Unlike disk partitions, datasets have no fixed size and allow for different attributes, such as compression, to be applied per dataset. Normal ZFS datasets are mounted automatically by ZFS whilst legacy datasets are required to be mounted using fstab or with the traditional mount command.

One of the most useful features of ZFS is boot environments. Boot environments allow you to create a bootable snapshot of your system that you can revert to at any time instantly by simply rebooting and booting from that boot environment. This can make doing system updates much safer and is also incredibly useful for developing and testing software. In order to be able to use a boot environment manager such as beadm, zectl AUR (systemd-boot), or zedenv AUR (GRUB) to manage boot environments, your datasets must be configured properly. Key to this are that you split your data directories (such as /home ) into datasets that are distinct from your system datasets and that you do not place data in the root of the pool as this cannot be moved afterwards.

Читайте также:  Mac os как открыть два окна рядом

You should always create a dataset for at least your root filesystem and in nearly all cases you will also want /home to be in a separate dataset. You may decide you want your logs to persist over boot environments. If you are a running any software that stores data outside of /home (such as is the case for database servers) you should structure your datasets so that the data directories of the software you want to run are separated out from the root dataset.

With these example commands, we will create a basic boot environment compatible configuration comprising of just root and /home datasets. It inherits default options from zpool creation.

You can also create your ROOT dataset without having to specify mountpoint to / since GRUB will mount it to / anyway. That gives you possibility to boot into some old versions of root just by cloning it and putting as menuentry of GRUB. In such, you can create ROOT with the following command:

You can store /root in your zroot/data/home dataset.

You will need to enable some options for datasets which hold specific directories:

Options required by specific directories

Directory Dataset option Details
/ canmount=noauto
/var/log/journal acltype=posixacl Systemd#systemd-tmpfiles-setup.service fails to start at boot

System datasets

To create datasets for system directories, use canmount=off .

Export/Import your datasets

To validate your configurations, export then reimport all your zpools.

If this command fails and you are asked to import your pool via its numeric ID, run zpool import to find out the ID of your pool then use a command such as:

If you used native encryption, load zfs key.

Manually mount your rootfs dataset because it uses canmount=noauto , then mount all others datasets.

The ZFS filesystem is now ready to use.

Configure the root filesystem

If you used legacy datasets, it must be listed in /etc/fstab .

Set the bootfs property on the descendant root filesystem so the boot loader knows where to find the operating system.

Be sure to bring the zpool.cache file into your new system. This is required later for the ZFS daemon to start.

if you do not have /etc/zfs/zpool.cache , create it:

Install and configure Arch Linux

Follow the following steps using the Installation guide. It will be noted where special consideration must be taken for ZFSonLinux.

  • First mount any legacy or non-ZFS boot or system partitions using the mount command.
  • Install the base system.
  • The procedure described in Installation guide#Fstab is usually overkill for ZFS. ZFS usually auto mounts its own partitions, so we do not need ZFS partitions in fstab file, unless the user made legacy datasets of system directories. To generate the fstab for filesystems, use:
  • Change root into the new system, per Installation guide#Chroot:
  • Edit the /etc/fstab :
  • You need to add the Arch ZFS repository to /etc/pacman.conf , sign its key and installzfs-linux (or zfs-linux-lts if you are running the LTS kernel) within the arch-chroot before you can update the ramdisk with ZFS support.
  • When creating the initial ramdisk, first edit /etc/mkinitcpio.conf and add zfs before filesystems. Also, move keyboard hook before zfs so you can type in console if something goes wrong. You may also remove fsck (if you are not using Ext3 or Ext4). Your HOOKS line should look something like this:

When using systemd in the initrd, you need to install mkinitcpio-sd-zfs AUR and add the sd-zfs hook after the systemd hook instead of the zfs hook. Keep in mind that this hook uses different kernel parameters than the default zfs hook, more information can be found at the project page.

Install and configure the bootloader

Using GRUB for EFI/BIOS

If you use GRUB, you can store your /boot on a zpool. Please read Debian-Buster-Root-on-ZFS#step-3-system-installation.

Install GRUB onto your disk as instructed here: GRUB#BIOS systems or GRUB#UEFI systems. The GRUB manual provides detailed information on manually configuring the software which you can supplement with GRUB and GRUB/Tips and tricks.

bug: broken root pool detection

Because of a known bug, grub-mkconfig will fail to detect the root pool and omit in /boot/grub/grub.cfg . Until this is fixed, there are two possible workarounds:

  • Workaround A: Modify code for rpool detection in /etc/grub.d/10_linux . Replace

with This will detect the correct root pool name and write working path to /boot/grub/grub.cfg any time grub-mkconfig is used.

  • Workaround B: Hardcoded path to root dataset in the kernel command line via /etc/default/grub :

Because GRUB_CMDLINE_LINUX is added at the end of the kernel command line, this path will overwrite the wrong, auto-generated one. Even though this is the less intrusive option to fix the issue, you will have to make sure the path is correct yourself.

Читайте также:  Самый стабильный пакет windows 10

error: failed to get canonical path of

grub-mkconfig fails to properly generate entries for systems hosted on ZFS.

To work around this you must set this environment variable: ZPOOL_VDEV_NAME_PATH=1 . For example:

error: unknown filesystem

GRUB tools like grub-probe or grub-install may fail with the error unknown filesystem when filesystem detection fails. This may happen due to the filesystem not being supported by GRUB, or in the case of ZFS, unsupported features may be present (refer to ZFS#GRUB-compatible pool creation for appropriate features to include in a boot zpool.)

In order to troubleshoot the error, understand which filesystem it is failing to identify (e.g. run grub-probe on the suspects, like grub-probe / or grub-probe /boot ). An example interaction follows:

After identifying the problem filesystem, run grub-probe -vvvv / and scan the output for the filesystem it was expected to identify. In this case, ZFS was expected, but the following output was generated:

This shows that ZFS detection went well until the com.datto:encryption feature was detected. Since ZFS Native Encryption is not supported by GRUB (as of August 2021), detection of ZFS failed. A second, GRUB-compatible zpool may be appropriate to boot into an encrypted system — as of August 2021, this is the recommended approach (refer to the relevant OpenZFS project page).

A successful execution of grub-probe on a GRUB-compatible zpool looks like this:

Booting your kernel and initrd from ZFS

You may skip this section if you have your kernel and initrd on a separate /boot partition using something like ext4 or vfat.

Otherwise grub needs to load your kernel and initrd are from a ZFS dataset the kernel and initrd paths have to be in the following format:

Example with Arch installed on the root dataset:

Example with Arch installed on a nested dataset:

Booting your kernel and initrd from separate boot partition

Example with a separate non-ZFS /boot partition and Arch installed on a nested dataset:

Using systemd-boot for EFI only

Systemd-boot cannot open ZFS zpools, you must store your /boot on a separated VFAT or ext4 partition.

Create a boot entry:

Using rEFInd for UEFI

Use EFISTUB and rEFInd for the UEFI boot loader. The kernel parameters in refind_linux.conf for ZFS should include zfs=bootfs or zfs=zroot so the system can boot from ZFS. The root and rootfstype parameters are not needed.

Configure systemd ZFS mounts

For your system to be able to reboot without issues, you need to enable the zfs.target to auto mount the pools and set the hostid.

For each pool you want automatically mounted execute:

Enable the target with systemd:

In order to mount zfs pools automatically on boot you need to enable the following services and targets:

When running ZFS on root, the machine’s hostid will not be available at the time of mounting the root filesystem. There are two solutions to this. You can either place your spl hostid in the kernel parameters in your boot loader. For example, adding spl.spl_hostid=0x00bab10c , to get your number use the hostid command.

The other, and suggested, solution is to make sure that there is a hostid in /etc/hostid , and then regenerate the initramfs image which will copy the hostid into the initramfs image. To write the hostid file safely you need to use the zgenhostid command.

To use the libc-generated hostid (recommended):

To use a custom hostid (must be hexadecimal and 8 characters long):

To let the tool generate a hostid:

Do not forget to regenerate your image using mkinitcpio.

Unmount and restart

We are almost done!

Loading password from USB-Stick

It is possible to store password on usb-stick and load it when booting:

Save password on first bytes of usb-stick:

To create partition zfs partition you can either use previous described method with password prompt or pipe with dd:

Next step is modyfing zfs hook. By default zfs prompts for password. You have to change it to have it piped with dd from your pendrive. In order to do so modify /usr/lib/initcpio/hooks/zfs and change line:

You are modifying your zfs hook so do not forget to regenerate your image using mkinitcpio. Now zfs should load password from your usb-stick on boot.

Troubleshooting

System fails to boot due to: cannot import zroot: no such pool available

You can try the following steps and see if they can help.

Источник

Установка и конфигурирование ZFS on Linux в Debian Jessie 8.1

Ramadoni: оригинал
Перевод: Алексей Федорчук

ZFS — это комбинация файловой системы и системы управления логическими томами. Среди её функций — защита от повреждения данных, поддержка больших хранилищ данных, эффективное их сжатие, интеграция файловой системы и управления томами, снапшоты и клоны с «копированием при записи», непрерывная проверка целостности файловой системы и автоматическое восстановление, RAID-Z и «родные» ACL в NFSv4.

ZFS создавалась как открытый софт, распространяемый под Common Development and Distribution License (CDDL).

Читайте также:  Qfile для windows 10

При рассмотрении ZFS выделяются следующие ключевые моменты:

простое управление хранилищами с помощью всего двух команд — zpool и zfs ;

возможность выполнения любых действий online (то есть без перезагрузки системы).

Полное описание всех доступных функций ZFS можно увидеть в подробной статье на Wikipedia (англ., русская версия здесь).

В этом руковостве дана пошаговая инструкция по установке файловой системы ZFS в Debian 8.1 (Jessie). Будут описаны создание и настройка пулов типа RAID0 (stripe — «с расщеплением»), RAID1 (Mirror — с зеркалированием) и RAID-Z (parity — с контролем чётности), а также настройка файловых систем с ZFS.

Согласно сведениям официального сайта проекта ZFS on Linux, ZFS поддерживается только для 64-разрядных процессоров AMD и Intel. Начнём с установки.

Требования

Debian 8.1 с 64-разрядным ядром;

Шаг 1: апдейт репозиториев и системы Debian Linux

Для установки ZFS нужно скачать и установить пакет zfsonlinux . Это добавит в систему файлы /etc/apt/sources.list.d/zfsonlinux.list и /etc/apt/trusted.gpg.d/zfsonlinux.gpg . После этого zfs устанавливается как любой другой пакет командой apt-get (или apt ). Преимущество использования официального репозитория — в возможности автоматического обновления с помощью apt-get update && apt-get upgrade .

Авторизуйте на машине Debian, получите права администратора и выполните следующие команды:

Шаг 2: установка zfsonlinux

Zfsonlinux имеет много зависимостей, которые будут автоматически разрешаться с помощью apt , что займёт некоторое время. Когда установка будет завершена, потребуется перезагрузить машину.

Шаг 3: создание и настройка пула

После перезагрузки убедитесь, что zfsonlinux установлен и работает правильно:

Данный вывод показывает, что zfsonlinux установлен нормально, и можно создавать первый пул.

Далее в пул добавляется 5 дисков, по 2 ГБ каждый. Сначала — проверка их доступности:

Мы видим диски с /dev/sda по , однако /dev/sda используется самим Debian’ом. Так что в пул ZFS будут включены диски с /dev/sdb по .

Теперь создаём пул, для первого раза — типа RAID0 (stripe).

Сначала у нас ничего нет:

Команда zpool list показывает, что пул типа RAID0, с именем pool0 , объёмом 2 ГБ, создан успешно.

Затем из оставшихся дисков создаётся пул типа RAID1 (mirror):

Теперь можно видеть два пула, pool0 типа raid0 и pool1 типа raid1 .

Для проверки статуса пулов используется следующая команда:

В выводе команды zpool status видно различие между pool0 и pool1 : pool0 имеет только один диск, а pool1 имеет два диска типа зеркало.

Затем мы создадим пул с RAID-Z — это схема распределения данных с контролем чётности, подобно RAID 5, но использующая динамическое «расщепление»: каждый блок имеет свою собственную «полосу пропускания», независимо от его размера. В результате каждая запись в RAID-Z выглядит как запись с полным «расщеплением».

RAID-Z требует минимум три жёстких диска, и представляет собой компромисс между RAID 0 и RAID 1. Если если один диск в пуле RAID-Z умирает, просто замените его, и ZFS автоматически перестроит данные на основе информации о чётности с других дисков. Потеря всей информации в пуле RAID-Z происходит только при смерти двух дисков хранения, два диска должны были бы умереть. Для ещё большей избыточности можно использовать RAID 6 (RAID-Z2 в случае ZFS), обеспечивающий двойной контроль чётности.

Однако давайте создадим пул RAID-Z с одинарным паритетом:

И поглядим на размер пула:

Из чего видно, что при суммарном объёме дисков в 6 ГБ объём пула составляет 4 ГЮ, а 2ГБ используется для хранения контрольных сумм.

Теперь создадим RAID-Z2 (aka RAID 6). Дл я этого потребуется удалить существующие пулы, потому что доступных дисков больше нет:

Для удаления пула используется команда zpool destroy :

По удалении бывших пулдов можно создать новый пул RAID-Z2:

Можно видеть, что при суммарном объёме дисков в 8 ГБ пул занимает 4 ГБ, а 4 ГБ используются для хранения удвоенного количества контрольных сумм.

Шаг 4: моделирование дисковых сбоев

Здесь мы воспроизведём ситуацию с фатальным отказом одного из дисков в пуле poolz2 . Для чего создаём в нём файл:

Перед моделированием отказа следует проверить статус пула poolz2 и всех входящих в него дисков, всё это должно быть в статусе Online.

Сам отказ моделируется записью случайных данных на устройство /dev/sdb командой dd :

Как можно видеть, на одном или нескольких дисках произошла неустранимая ошибка. В данном случае диск /dev/sdb заменяется на диск /dev/sdr :

После замены дисков сообщение об ошибке исчезло, и созданный ранее тестовый файл опять доступен:

Так что теперь мы знаем, как создавать и настраивать пулы ZFS.

Шаг 5: создание и настройка файловых систем ZFS

Теперь узнаем, как создавать и настраивать файловые системы ZFS.

То есть одна файловая систему уже есть, она была создана автоматически при создании пула ZFS. Теперь создадим другие файловые системы:

Просто, не так ли? Была создана новая файловая система ZFS с именем tank, автоматически смонтированная в /poolz2/tank . Для определения более иной точки монтирования ту же команду надо дать в таком виде:

Если требуется изменить указанную ранее точку монтирования, используется такая команда:

Дляьщтеирования и отмонтирования файловых систем используются такие команды:

Удаление файловых систем делается очень просто:

Файловая система /data удалена.

Заключение

ZFS — революционная файловая система, которая принципиально меняет способы управления файловыми системами в Unix-подобных операционках. ZFS мощная, масштабируема и проста в управлении.

Оставьте комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Источник

Оцените статью