Difference between pages "Funtoo:Keychain" and "ZFS as Root Filesystem"

From Funtoo
(Difference between pages)
Jump to navigation Jump to search
 
 
Line 1: Line 1:
{{Article
== Introduction ==
|Subtitle=Official Project Page
 
|Summary=Keychain helps you to manage SSH and GPG keys in a convenient and secure manner. Download and learn how to use Keychain on your Linux, Unix or MacOS system.
This tutorial will show you how to install Funtoo on ZFS (rootfs). This tutorial is meant to be an "overlay" over the [[Funtoo_Linux_Installation|Regular Funtoo Installation]]. Follow the normal installation and only use this guide for steps 2, 3, and 8.
|Keywords=keychain,ssh,rsa,dsa,gpg,linux,gentoo,macos,download,source code
 
|Author=Drobbins
=== Introduction to ZFS ===
}}
 
<tt>Keychain</tt> helps you to manage SSH and GPG keys in a convenient and secure manner. It acts as a frontend to <tt>ssh-agent</tt> and <tt>ssh-add</tt>, but allows you to easily have one long running <tt>ssh-agent</tt> process per system, rather than the norm of one <tt>ssh-agent</tt> per login session.
Since ZFS is a new technology for Linux, it can be helpful to understand some of its benefits, particularly in comparison to BTRFS, another popular next-generation Linux filesystem:
 
* On Linux, the ZFS code can be updated independently of the kernel to obtain the latest fixes. btrfs is exclusive to Linux and you need to build the latest kernel sources to get the latest fixes.
 
* ZFS is supported on multiple platforms. The platforms with the best support are Solaris, FreeBSD and Linux. Other platforms with varying degrees of support are NetBSD, Mac OS X and Windows. btrfs is exclusive to Linux.
 
* ZFS has the Adaptive Replacement Cache replacement algorithm while btrfs uses the Linux kernel's Last Recently Used replacement algorithm. The former often has an overwhelmingly superior hit rate, which means fewer disk accesses.
 
* ZFS has the ZFS Intent Log and SLOG devices, which accelerates small synchronous write performance.
 
* ZFS handles internal fragmentation gracefully, such that you can fill it until 100%. Internal fragmentation in btrfs can make btrfs think it is full at 10%. Btrfs has no automatic rebalancing code, so it requires a manual rebalance to correct it.
 
* ZFS has raidz, which is like RAID 5/6 (or a hypothetical RAID 7 that supports 3 parity disks), except it does not suffer from the RAID write hole issue thanks to its use of CoW and a variable stripe size. btrfs gained integrated RAID 5/6 functionality in Linux 3.9. However, its implementation uses a stripe cache that can only partially mitigate the effect of the RAID write hole.
 
* ZFS send/receive implementation supports incremental update when doing backups. btrfs' send/receive implementation requires sending the entire snapshot.
 
* ZFS supports data deduplication, which is a memory hog and only works well for specialized workloads. btrfs has no equivalent.
 
* ZFS datasets have a hierarchical namespace while btrfs subvolumes have a flat namespace.
 
* ZFS has the ability to create virtual block devices called zvols in its namespace. btrfs has no equivalent and must rely on the loop device for this functionality, which is cumbersome.
 
The only area where btrfs is ahead of ZFS is in the area of small file
efficiency. btrfs supports a feature called block suballocation, which
enables it to store small files far more efficiently than ZFS. It is
possible to use another filesystem (e.g. reiserfs) on top of a ZFS zvol
to obtain similar benefits (with arguably better data integrity) when
dealing with many small files (e.g. the portage tree).
 
For a quick tour of ZFS and have a big picture of its common operations you can consult the page [[ZFS Fun]].
 
=== Disclaimers ===
 
{{fancywarning|This guide is a work in progress. Expect some quirks.
 
Today is 2015-05-12. ZFS has undertaken an upgrade - from 0.6.3 to 0.6.4. Please ensure that you use a RescueCD with ZFS 0.6.3. At present date grub 2.02 is not able to deal with those new ZFS parameters. If you want to use ZFS 0.6.4 for pool creation, you should use the compatability mode.
 
You should upgrade an existing pool only when grub is able to deal with - in a future version ... If not, you will not be able to boot into your system, and no rollback will help!
 
Please inform yourself!}}
 
{{fancyimportant|'''Since ZFS was really designed for 64 bit systems, we are only recommending and supporting 64 bit platforms and installations. We will not be supporting 32 bit platforms'''!}}
 
== Downloading the ISO (With ZFS) ==
In order for us to install Funtoo on ZFS, you will need an environment that already provides the ZFS tools. Therefore we will download a customized version of System Rescue CD with ZFS included.
 
<pre>
Name: sysresccd-4.2.0_zfs_0.6.2.iso  (545 MB)
Release Date: 2014-02-25
md5sum 01f4e6929247d54db77ab7be4d156d85
</pre>
 
 
'''[http://ftp.osuosl.org/pub/funtoo/distfiles/sysresccd/ Download System Rescue CD with ZFS]'''<br />
 
== Creating a bootable USB from ISO (From a Linux Environment) ==
After you download the iso, you can do the following steps to create a bootable USB:


This dramatically reduces the number of times you need to enter your passphrase. With <tt>keychain</tt>, you only need to enter a passphrase once every time your local machine is rebooted. <tt>Keychain</tt> also makes it easy for remote cron jobs to securely "hook in" to a long-running <tt>ssh-agent</tt> process, allowing your scripts to take advantage of key-based logins.
<console>
Make a temporary directory
# ##i##mkdir /tmp/loop


Those who are new to OpenSSH and the use of public/private keys for authentication may want to check out the following articles by Daniel Robbins, which will provide a gentle introduction to the concepts used by Keychain:
Mount the iso
* [[OpenSSH Key Management, Part 1]]
# ##i##mount -o ro,loop /root/sysresccd-4.2.0_zfs_0.6.2.iso /tmp/loop
* [[OpenSSH Key Management, Part 2]]
* [[OpenSSH Key Management, Part 3]]


== Download and Resources ==
Run the usb installer
# ##i##/tmp/loop/usb_inst.sh
</console>


The latest release of keychain is version <tt>2.7.2_beta1</tt>, and was released on July 7, 2014. The current version of keychain supports <tt>gpg-agent</tt> as well as <tt>ssh-agent</tt>.
That should be all you need to do to get your flash drive working.


Keychain is compatible with many operating systems, including <tt>AIX</tt>, <tt>*BSD</tt>, <tt>Cygwin</tt>, <tt>MacOS X</tt>, <tt>Linux</tt>, <tt>HP/UX</tt>, <tt>Tru64 UNIX</tt>, <tt>IRIX</tt>, <tt>Solaris</tt> and <tt>GNU Hurd</tt>.
== Booting the ISO ==


=== Download ===
{{fancywarning|'''When booting into the ISO, Make sure that you select the "Alternate 64 bit kernel (altker64)". The ZFS modules have been built specifically for this kernel rather than the standard kernel. If you select a different kernel, you will get a fail to load module stack error message.'''}}


* ''Release Archive''
== Creating partitions ==
** [http://www.funtoo.org/distfiles/keychain/keychain-2.7.2_beta1.tar.bz2 keychain 2.7.2_beta1]
There are two ways to partition your disk: You can use your entire drive and let ZFS automatically partition it for you, or you can do it manually.
** [http://www.funtoo.org/distfiles/keychain/keychain-2.7.1.tar.bz2 keychain 2.7.1]


* ''Apple MacOS X Packages''
We will be showing you how to partition it '''manually''' because if you partition it manually you get to create your own layout, you get to have your own separate /boot partition (Which is nice since not every bootloader supports booting from ZFS pools), and you get to boot into RAID10, RAID5 (RAIDZ) pools and any other layouts due to you having a separate /boot partition.
** [http://www.funtoo.org/distfiles/keychain/keychain-2.7.1-macosx.tar.gz keychain 2.7.1 MacOS X package]


Keychain development sources can be found in the [http://www.github.com/funtoo/keychain keychain git repository]. Please use the [https://bugs.funtoo.org Funtoo Linux bug tracker] and [irc://irc.freenode.net/funtoo #funtoo irc channel] for keychain support questions as well as bug reports.
==== gdisk (GPT Style) ====


=== Project History ===
'''A Fresh Start''':


Daniel Robbins originally wrote <tt>keychain</tt> 1.0 through 2.0.3. 1.0 was written around June 2001, and 2.0.3 was released in late August, 2002.
First lets make sure that the disk is completely wiped from any previous disk labels and partitions.
We will also assume that <tt>/dev/sda</tt> is the target drive.<br />


After 2.0.3, <tt>keychain</tt> was maintained by various Gentoo developers, including Seth Chandler, Mike Frysinger and Robin H. Johnson, through July 3, 2003.
<console>
# ##i##sgdisk -Z /dev/sda
</console>


On April 21, 2004, Aron Griffis committed a major rewrite of <tt>keychain</tt> which was released as 2.2.0. Aron continued to actively maintain and improve <tt>keychain</tt> through October 2006 and the <tt>keychain</tt> 2.6.8 release. He also made a few commits after that date, up through mid-July, 2007. At this point, <tt>keychain</tt> had reached a point of maturity.
{{fancywarning|This is a destructive operation and the program will not ask you for confirmation! Make sure you really don't want anything on this disk.}}


In mid-July, 2009, Daniel Robbins migrated Aron's mercurial repository to git and set up a new project page on funtoo.org, and made a few bug fix commits to the git repo that had been collecting in [http://bugs.gentoo.org bugs.gentoo.org]. Daniel continues to maintain <tt>keychain</tt> and supporting documentation on funtoo.org, and plans to make regular maintenance releases of <tt>keychain</tt> as needed.
Now that we have a clean drive, we will create the new layout.


== Quick Setup ==
First open up the application:


=== Linux ===
<console>
# ##i##gdisk /dev/sda
</console>


To install under Gentoo or Funtoo Linux, type
'''Create Partition 1''' (boot):
<console>
<console>
###i## emerge keychain
Command: ##i##n ↵
Partition Number: ##i##↵
First sector: ##i##↵
Last sector: ##i##+250M ↵
Hex Code: ##i##↵
</console>
 
'''Create Partition 2''' (BIOS Boot Partition):
<console>Command: ##i##n ↵
Partition Number: ##i##↵
First sector: ##i##↵
Last sector: ##i##+32M ↵
Hex Code: ##i##EF02 ↵
</console>
</console>


For other Linux distributions, use your distribution's package manager, or download and install using the source tarball above. Then generate RSA/DSA keys if necessary. The quick install docs assume you have a DSA key pair named <tt>id_dsa</tt> and <tt>id_dsa.pub</tt> in your <tt>~/.ssh/</tt> directory. Add the following to your <tt>~/.bash_profile</tt>:
'''Create Partition 3''' (ZFS):
<console>Command: ##i##n ↵
Partition Number: ##i##↵
First sector: ##i##↵
Last sector: ##i##↵
Hex Code: ##i##bf00 ↵
 
Command: ##i##p ↵
 
Number  Start (sector)    End (sector)  Size      Code  Name
  1            2048          514047  250.0 MiB  8300  Linux filesystem
  2          514048          579583  32.0 MiB    EF02  BIOS boot partition
  3          579584      1953525134  931.2 GiB  BF00  Solaris root


{{file|name=~/.bash_profile|body=
Command: ##i##w ↵
eval `keychain --eval --agents ssh id_rsa`
</console>
}}


If you want to take advantage of GPG functionality, ensure that GNU Privacy Guard is installed and omit the <tt>--agents ssh</tt> option above.


=== Apple MacOS X ===
=== Format your /boot partition ===


To install under MacOS X, install the MacOS X package for keychain. Assuming you have an <tt>id_dsa</tt> and <tt>id_dsa.pub</tt> key pair in your <tt>~/.ssh/</tt> directory, add the following to your <tt>~/.bash_profile</tt>:
<console>
# ##i##mkfs.ext2 -m 1 /dev/sda1
</console>


{{file|name=~/.bash_profile|body=
=== Create the zpool ===
eval `keychain --eval --agents ssh --inherit any id_dsa`
We will first create the pool. The pool will be named  <code>tank</code>. Feel free to name your pool as you want.  We will use <code>ashift=12</code> option  which is used for a hard drives with a 4096 sector size.
}}
<console># ##i##  zpool create -f -o ashift=12 -o cachefile=/tmp/zpool.cache -O normalization=formD -m none -R /mnt/funtoo tank /dev/sda3 </console>
 
=== Create the zfs datasets ===
We will now create some datasets. For this installation, we will create a small but future proof amount of datasets. We will have a dataset for the OS (/), and your swap. We will also show you how to create some optional datasets as examples ones: <code>/home</code>,  <code>/usr/src</code>, and <code>/usr/portage</code>. 


{{Fancynote|The <tt>--inherit any</tt> option above causes keychain to inherit any ssh key passphrases stored in your Apple MacOS Keychain. If you would prefer for this to not happen, then this option can be omitted.}}
<console>
Create some empty containers for organization purposes, and make the dataset that will hold /
# ##i##zfs create -p tank/funtoo
# ##i##zfs create -o mountpoint=/ tank/funtoo/root


=== Fish Shell ===
Optional, but recommended datasets: /home
# ##i##zfs create -o mountpoint=/home tank/funtoo/home


When using the fish shell, the simplest way to call keychain is to source instead of using eval:
Optional datasets: /usr/src, /usr/portage/{distfiles,packages}
# ##i##zfs create -o mountpoint=/usr/src tank/funtoo/src
# ##i##zfs create -o mountpoint=/usr/portage -o compression=off tank/funtoo/portage
# ##i##zfs create -o mountpoint=/usr/portage/distfiles tank/funtoo/portage/distfiles
# ##i##zfs create -o mountpoint=/usr/portage/packages tank/funtoo/portage/packages
</console>


{{file|body=
== Installing Funtoo ==
if status --is-interactive
  keychain --eval --quiet -Q id_rsa | source
end
}}


Alternatively if you wish to still use eval (which really is just a wrapper around piping to source, although it does some job control manipulation that isn't relevant here) you would use
=== Pre-Chroot ===


{{file|body=
<console>
if status --is-interactive
Go into the directory that you will chroot into
  set -l IFS # this temporarily clears IFS, which disables the newline-splitting
# ##i##cd /mnt/funtoo
  eval (keychain --eval --quiet -Q id_rsa)
 
end
Make a boot folder and mount your boot drive
}}
# ##i##mkdir boot
# ##i##mount /dev/sda1 boot
</console>


Thanks to Kevin Ballard for this information (See {{Bug|FL-2006}}).
[[Funtoo_Linux_Installation|Now download and extract the Funtoo stage3 ...]]


== Background ==


You're probably familiar with <tt>ssh</tt>, which has become a secure replacement for the venerable <tt>telnet</tt> and <tt>rsh</tt> commands.
{{fancynote|It is trully recommended to use the current version and generic64. That reduces the risk of a broken build.  


Typically, when one uses <tt>ssh</tt> to connect to a remote system, one supplies a secret passphrase to <tt>ssh</tt>, which is then passed in encrypted form over the network to the remote server. This passphrase is used by the remote <tt>sshd</tt> server to determine if you should be granted access to the system.
After successfull ZFS installation and successfull first boot, the kernel may be changed using the <code> eselect profile set ... </code> command. If you create a snapshot before, you may allways come back to your previous installation, with some simple steps ... (rollback your pool and in the worst case configure and install the bootloader again)}}


However, OpenSSH and nearly all other SSH clients and servers have the ability to perform another type of authentication, called asymmetric public key authentication, using the RSA or DSA authentication algorithms. They are very useful, but can also be complicated to use. <tt>keychain</tt> has been designed to make it easy to take advantage of the benefits of RSA and DSA authentication.


== Generating a Key Pair ==


To use RSA and DSA authentication, first you use a program called <tt>ssh-keygen</tt> (included with OpenSSH) to generate a ''key pair'' -- two small files. One of the files is the ''public key''. The other small file contains the ''private key''. <tt>ssh-keygen</tt> will ask you for a passphrase, and this passphrase will be used to encrypt your private key. You will need to supply this passphrase to use your private key. If you wanted to generate a DSA key pair, you would do this:
Once you've extracted the stage3, do a few more preparations and chroot into your new funtoo environment:


<console># ##i##ssh-keygen -t dsa
<console>
Generating public/private dsa key pair.</console>
Bind the kernel related directories
You would then be prompted for a location to store your key pair. If you do not have one currently stored in <tt>~/.ssh</tt>, it is fine to accept the default location:
# ##i##mount -t proc none proc
# ##i##mount --rbind /dev dev
# ##i##mount --rbind /sys sys


<console>Enter file in which to save the key (/root/.ssh/id_dsa): </console>
Copy network settings
Then, you are prompted for a passphrase. This passphrase is used to encrypt the ''private key'' on disk, so even if it is stolen, it will be difficult for someone else to use it to successfully authenticate as you with any accounts that have been configured to recognize your public key.
# ##i##cp -f /etc/resolv.conf etc


Note that conversely, if you '''do not''' provide a passphrase for your private key file, then your private key file '''will not''' be encrypted. This means that if someone steals your private key file, ''they will have the full ability to authenticate with any remote accounts that are set up with your public key.''
Make the zfs folder in 'etc' and copy your zpool.cache
# ##i##mkdir etc/zfs
# ##i##cp /tmp/zpool.cache etc/zfs


Below, I have supplied a passphrase so that my private key file will be encrypted on disk:
Chroot into Funtoo
# ##i##env -i HOME=/root TERM=$TERM chroot . bash -l
</console>


<console>Enter passphrase (empty for no passphrase): ##i#########
{{fancynote|How to create zpool.cache file?}}
Enter same passphrase again: ##i#########
If no <code>zpool.cache</code> file is available, the following command will create one:
Your identification has been saved in /var/tmp/id_dsa.
<console>
Your public key has been saved in /var/tmp/id_dsa.pub.
# ##i##zpool set cachefile=/etc/zfs/zpool.cache tank
The key fingerprint is:
</console>
5c:13:ff:46:7d:b3:bf:0e:37:1e:5e:8c:7b:a3:88:f4 root@devbox-ve
The key's randomart image is:
+--[ DSA 1024]----+
|          .     |
|          o  . |
|          o . ..o|
|      . . . o  +|
|        S    o. |
|            . o.|
|        .  ..++|
|        . o . =o*|
|        . E .+*.|
+-----------------+</console>


== Setting up Authentication ==
{{:Install/PortageTree}}


Here's how you use these files to authenticate with a remote server. On the remote server, you would append the contents of your ''public key'' to the <tt>~.ssh/authorized_keys</tt> file, if such a file exists. If it doesn't exist, you can simply create a new <tt>authorized_keys</tt> file in the remote account's <tt>~/.ssh</tt> directory that contains the contents of your local <tt>id_dsa.pub</tt> file.
=== Add filesystems to /etc/fstab ===


Then, if you weren't going to use <tt>keychain</tt>, you'd perform the following steps. On your local client, you would start a program called <tt>ssh-agent</tt>, which runs in the background. Then you would use a program called <tt>ssh-add</tt> to tell <tt>ssh-agent</tt> about your secret private key. Then, if you've set up your environment properly, the next time you run <tt>ssh</tt>, it will find <tt>ssh-agent</tt> running, grab the private key that you added to <tt>ssh-agent</tt> using <tt>ssh-add</tt>, and use this key to authenticate with the remote server.
Before we continue to compile and or install our kernel in the next step, we will edit the <code>/etc/fstab</code> file because if we decide to install our kernel through portage, portage will need to know where our <code>/boot</code> is, so that it can place the files in there.  


Again, the steps in the previous paragraph is what you'd do if <tt>keychain</tt> wasn't around to help. If you are using <tt>keychain</tt>, and I hope you are, you would simply add the following line to your <tt>~/.bash_profile</tt> or if a regular user to<tt>~/.bashrc</tt> :
Edit <code>/etc/fstab</code>:


{{file|name=~/.bash_profile|body=
{{file|name=/etc/fstab|desc= |body=
eval `keychain --eval id_dsa`
# <fs>                  <mountpoint>    <type>          <opts>          <dump/pass>
 
/dev/sda1              /boot          ext2            defaults        0 2
}}
}}


The next time you log in or source your <tt>~/.bash_profile</tt> or if you use <tt>~/.bashrc</tt>, <tt>keychain</tt> will start, start <tt>ssh-agent</tt> for you if it has not yet been started, use <tt>ssh-add</tt> to add your <tt>id_dsa</tt> private key file to <tt>ssh-agent</tt>, and set up your shell environment so that <tt>ssh</tt> will be able to find <tt>ssh-agent</tt>. If <tt>ssh-agent</tt> is already running, <tt>keychain</tt> will ensure that your <tt>id_dsa</tt> private key has been added to <tt>ssh-agent</tt> and then set up your environment so that <tt>ssh</tt> can find the already-running <tt>ssh-agent</tt>. It will look something like this:
== Building kernel, initramfs and grub to work with zfs==
=== Install genkernel and initial kernel build ===
 
We need to build a genkernel initially:
<console>
# ##i##emerge genkernel
 
Build initial kernel (required for checks in sys-kernel/spl and sys-fs/zfs):
# ##i##genkernel kernel --no-clean --no-mountboot
 
</console>
 
=== Installing the ZFS userspace tools and kernel modules ===
Emerge {{Package|sys-fs/zfs}}. This package will bring in {{Package|sys-kernel/spl}}, and {{Package|sys-fs/zfs-kmod}} as its dependencies:


Note that when <tt>keychain</tt> runs for the first time after your local system has booted, you will be prompted for a passphrase for your private key file if it is encrypted. But here's the nice thing about using <tt>keychain</tt> -- even if you are using an encrypted private key file, you will only need to enter your passphrase when your system first boots (or in the case of a server, when you first log in.) After that, <tt>ssh-agent</tt> is already running and has your decrypted private key cached in memory. So if you open a new shell, you will see something like this:
<console>
# ##i##emerge zfs
</console>


This means that you can now <tt>ssh</tt> to your heart's content, without supplying a passphrase.
Check to make sure that the zfs tools are working. The <code>zpool.cache</code> file that you copied before should be displayed.


You can also execute batch <tt>cron</tt> jobs and scripts that need to use <tt>ssh</tt> or <tt>scp</tt>, and they can take advantage of passwordless RSA/DSA authentication as well. To do this, you would add the following line to the top of a bash script:
<console>
# ##i##zpool status
# ##i##zfs list
</console>


{{file|name=example-script.sh|body=
Add the zfs tools to openrc.
eval `keychain --noask --eval id_dsa` || exit 1
<console># ##i##rc-update add zfs boot</console>
 
If everything worked, continue.
 
=== Install GRUB 2  ===
 
Install grub2:
<console>
# ##i##echo "sys-boot/grub libzfs -truetype" >> /etc/portage/package.use
# ##i##emerge grub
</console>
 
Now install grub to the drive itself (not a partition):
<console>
# ##i##grub-install /dev/sda
</console>
 
=== Emerge genkernel and initial kernel build ===
Install genkernel using:
<console>
# ##i##echo "sys-kernel/genkernel zfs" >> /etc/portage/package.use
# ##i##emerge genkernel
 
Build now kernel and initramfs with --zfs
# ##i##genkernel all --zfs --no-clean --no-mountboot --callback="emerge @module-rebuild"
</console>
 
 
{{fancynote|During the build, ZFS configurations should be observed.
 
If the build breaks, restart it again.}}
 
=== Configuring the Bootloader ===
 
Using the genkernel you must add 'real_root=ZFS=<root>' and 'dozfs' to your params.
Edit the  entry for <code>/etc/boot.conf</code>:
 
{{file|name=/etc/boot.conf|desc= |body=
"Funtoo ZFS" {
        kernel kernel[-v]
        initrd initramfs-genkernel-x86_64[-v]
        params real_root=ZFS=tank/funtoo/root
        params += dozfs=force
}
}}
}}


The extra <tt>--noask</tt> option tells <tt>keychain</tt> that it should not prompt for a passphrase if one is needed. Since it is not running interactively, it is better for the script to fail if the decrypted private key isn't cached in memory via <tt>ssh-agent</tt>.
The command <code>boot-update</code> should take care of grub configuration:


== Keychain Options ==
<console>
Install boot-update (if it is missing):
###i##emerge boot-update


=== Specifying Agents ===
Run boot-update to update grub.cfg
###i##boot-update
</console>


In the images above, you will note that <tt>keychain</tt> starts <tt>ssh-agent</tt>, but also starts <tt>gpg-agent</tt>. Modern versions of <tt>keychain</tt> also support caching decrypted GPG keys via use of <tt>gpg-agent</tt>, and will start <tt>gpg-agent</tt> by default if it is available on your system. To avoid this behavior and only start <tt>ssh-agent</tt>, modify your <tt>~/.bash_profile</tt> as follows:
{{fancynote|If <code>boot-update</code>fails, try this:
<console>
# ##i##grub-mkconfig -o /boot/grub/grub.cfg
</console>
}}
Now you should have a new installation of the kernel, initramfs and grub which are zfs capable. The configurtion files should be updated, and the system should come up during the next reboot.  


{{file|name=~/.bash_profile|body=
{{fancynote|If The <code>luks</code> integration works basically the same way.}}
eval `keychain --agents ssh --eval id_dsa` || exit 1
 
}}
== Final configuration ==
=== Clean up and reboot ===
We are almost done, we are just going to clean up, '''set our root password''', and unmount whatever we mounted and get out.


The additional <tt>--agents ssh</tt> option tells <tt>keychain</tt> just to manage <tt>ssh-agent</tt>, and ignore <tt>gpg-agent</tt> even if it is available.
<console>
Delete the stage3 tarball that you downloaded earlier so it doesn't take up space.
# ##i##cd /
# ##i##rm stage3-latest.tar.xz


=== Clearing Keys ===
Set your root password
# ##i##passwd
>> Enter your password, you won't see what you are writing (for security reasons), but it is there!


Sometimes, it might be necessary to flush all cached keys in memory. To do this, type:
Get out of the chroot environment
# ##i##exit


<console># ##i##keychain --clear</console>
Unmount all the kernel filesystem stuff and boot (if you have a separate /boot)
Any agent(s) will continue to run.
# ##i##umount -l proc dev sys boot


=== Improving Security ===
Turn off the swap
# ##i##swapoff /dev/zvol/tank/swap


To improve the security of <tt>keychain</tt>, some people add the <tt>--clear</tt> option to their <tt>~/.bash_profile</tt> <tt>keychain</tt> invocation. The rationale behind this is that any user logging in should be assumed to be an intruder until proven otherwise. This means that you will need to re-enter any passphrases when you log in, but cron jobs will still be able to run when you log out.
Export the zpool
# ##i##cd /
# ##i##zpool export tank


=== Stopping Agents ===
Reboot
# ##i##reboot
</console>


If you want to stop all agents, which will also of course cause your keys/identities to be flushed from memory, you can do this as follows:
{{fancyimportant|'''Don't forget to set your root password as stated above before exiting chroot and rebooting. If you don't set the root password, you won't be able to log into your new system.'''}}


<console># ##i##keychain -k all</console>
and that should be enough to get your system to boot on ZFS.
If you have other agents running under your user account, you can also tell <tt>keychain</tt> to just stop only the agents that <tt>keychain</tt> started:


<console># ##i##keychain -k mine</console>
== After reboot ==


=== GPG ===
=== Forgot to reset password? ===
==== System Rescue CD ====
If you aren't using bliss-initramfs, then you can reboot back into your sysresccd and reset through there by mounting your drive, chrooting, and then typing passwd.


Keychain can ask you for your GPG passphrase if you provide it the GPG key ID. To find it out:
Example:
<console>
<console>
$##i## gpg -k
# ##i##zpool import -f -R /mnt/funtoo tank
pub  2048R/DEADBEEF 2012-08-16
# ##i##chroot /mnt/funtoo bash -l
uid                  Name (Comment) <email@host.tld>
# ##i##passwd
sub  2048R/86D2FAC6 2012-08-16
# ##i##exit
# ##i##zpool export -f tank
# ##i##reboot
</console>
</console>


Note the '''DEADBEEF''' above is the ID. Then, in your login script, do your usual
=== Create initial ZFS Snapshot ===
Continue to set up anything you need in terms of /etc configurations. Once you have everything the way you like it, take a snapshot of your system. You will be using this snapshot to revert back to this state if anything ever happens to your system down the road. The snapshots are cheap, and almost instant.
 
To take the snapshot of your system, type the following:
<console># ##i##zfs snapshot -r tank@install</console>
 
To see if your snapshot was taken, type:
<console># ##i##zfs list -t snapshot</console>
 
If your machine ever fails and you need to get back to this state, just type (This will only revert your / dataset while keeping the rest of your data intact):
<console># ##i##zfs rollback tank/funtoo/root@install</console>
 
{{fancyimportant|'''For a detailed overview, presentation of ZFS' capabilities, as well as usage examples, please refer to the [[ZFS_Fun|ZFS Fun]] page.'''}}
 
== Troubleshooting ==
 
=== Starting from scratch ===
If your installation has gotten screwed up for whatever reason and you need a fresh restart, you can do the following from sysresccd to start fresh:


<console>
<console>
$##i## keychain --dir ~/.ssh/.keychain ~/.ssh/id_rsa DEADBEEF
Destroy the pool and any snapshots and datasets it has
$##i## source ~/.ssh/.keychain/$HOST-sh
# ##i##zpool destroy -R -f tank
$##i## source ~/.ssh/.keychain/$HOST-sh-gpg
 
This deletes the files from /dev/sda1 so that even after we zap, recreating the drive in the exact sector
position and size will not give us access to the old files in this partition.
# ##i##mkfs.ext2 /dev/sda1
# ##i##sgdisk -Z /dev/sda
</console>
</console>


=== Learning More ===
Now start the guide again :).


The instructions above will work on any system that uses <tt>bash</tt> as its default shell, such as most Linux systems and Mac OS X.


To learn more about the many things that <tt>keychain</tt> can do, including alternate shell support, consult the keychain man page, or type <tt>keychain --help | less</tt> for a full list of command options.
=== Starting again reusing the same disk partitions and the same pool ===


I also recommend you read my original series of articles about [http://www.openssh.com OpenSSH] that I wrote for IBM developerWorks, called <tt>OpenSSH Key Management</tt>. Please note that <tt>keychain</tt> 1.0 was released along with Part 2 of this article, which was written in 2001. <tt>keychain</tt> has changed quite a bit since then. In other words, read these articles for the conceptual and [http://www.openssh.com OpenSSH] information, but consult the <tt>keychain</tt> man page for command-line options and usage instructions :)
If your installation has gotten screwed up for whatever reason and you want to keep your pole named tank than you should boou into the Rescue CD / USB as done before.


* [http://www.ibm.com/developerworks/library/l-keyc.html Common Threads: OpenSSH key management, Part 1] - Understanding RSA/DSA Authentication
<console>import the pool reusing all existing datasets:
* [http://www.ibm.com/developerworks/library/l-keyc2/ Common Threads: OpenSSH key management, Part 2] - Introducing <tt>ssh-agent</tt> and <tt>keychain</tt>
# ##i##zpool import -f -R /mnt/funtoo tank
* [http://www.ibm.com/developerworks/library/l-keyc3/ Common Threads: OpenSSH key management, Part 3] - Agent forwarding and <tt>keychain</tt> improvements
</console>
 
Now you should wipe the previous installation off:
 
<console>
let's go to our base installation directory:
# ##i##cd /mnt/funtoo
 
and delete the old installation:  
# ##i##rm -rf *
</console>
 
Now start the guide again, at "Pre-Chroot"


As mentioned at the top of the page, <tt>keychain</tt> development sources can be found in the [http://www.github.com/funtoo/keychain keychain git repository]. Please use the [http://groups.google.com/group/funtoo-dev funtoo-dev mailing list] and [irc://irc.freenode.net/funtoo #funtoo irc channel] for keychain support questions as well as bug reports.


[[Category:HOWTO]]
[[Category:HOWTO]]
[[Category:Projects]]
[[Category:Filesystems]]
[[Category:First Steps]]
[[Category:Featured]]
[[Category:Articles]]
[[Category:Install]]
{{ArticleFooter}}
 
__NOTITLE__

Revision as of 15:57, May 13, 2015

Introduction

This tutorial will show you how to install Funtoo on ZFS (rootfs). This tutorial is meant to be an "overlay" over the Regular Funtoo Installation. Follow the normal installation and only use this guide for steps 2, 3, and 8.

Introduction to ZFS

Since ZFS is a new technology for Linux, it can be helpful to understand some of its benefits, particularly in comparison to BTRFS, another popular next-generation Linux filesystem:

  • On Linux, the ZFS code can be updated independently of the kernel to obtain the latest fixes. btrfs is exclusive to Linux and you need to build the latest kernel sources to get the latest fixes.
  • ZFS is supported on multiple platforms. The platforms with the best support are Solaris, FreeBSD and Linux. Other platforms with varying degrees of support are NetBSD, Mac OS X and Windows. btrfs is exclusive to Linux.
  • ZFS has the Adaptive Replacement Cache replacement algorithm while btrfs uses the Linux kernel's Last Recently Used replacement algorithm. The former often has an overwhelmingly superior hit rate, which means fewer disk accesses.
  • ZFS has the ZFS Intent Log and SLOG devices, which accelerates small synchronous write performance.
  • ZFS handles internal fragmentation gracefully, such that you can fill it until 100%. Internal fragmentation in btrfs can make btrfs think it is full at 10%. Btrfs has no automatic rebalancing code, so it requires a manual rebalance to correct it.
  • ZFS has raidz, which is like RAID 5/6 (or a hypothetical RAID 7 that supports 3 parity disks), except it does not suffer from the RAID write hole issue thanks to its use of CoW and a variable stripe size. btrfs gained integrated RAID 5/6 functionality in Linux 3.9. However, its implementation uses a stripe cache that can only partially mitigate the effect of the RAID write hole.
  • ZFS send/receive implementation supports incremental update when doing backups. btrfs' send/receive implementation requires sending the entire snapshot.
  • ZFS supports data deduplication, which is a memory hog and only works well for specialized workloads. btrfs has no equivalent.
  • ZFS datasets have a hierarchical namespace while btrfs subvolumes have a flat namespace.
  • ZFS has the ability to create virtual block devices called zvols in its namespace. btrfs has no equivalent and must rely on the loop device for this functionality, which is cumbersome.

The only area where btrfs is ahead of ZFS is in the area of small file efficiency. btrfs supports a feature called block suballocation, which enables it to store small files far more efficiently than ZFS. It is possible to use another filesystem (e.g. reiserfs) on top of a ZFS zvol to obtain similar benefits (with arguably better data integrity) when dealing with many small files (e.g. the portage tree).

For a quick tour of ZFS and have a big picture of its common operations you can consult the page ZFS Fun.

Disclaimers

   Warning

This guide is a work in progress. Expect some quirks.

Today is 2015-05-12. ZFS has undertaken an upgrade - from 0.6.3 to 0.6.4. Please ensure that you use a RescueCD with ZFS 0.6.3. At present date grub 2.02 is not able to deal with those new ZFS parameters. If you want to use ZFS 0.6.4 for pool creation, you should use the compatability mode.

You should upgrade an existing pool only when grub is able to deal with - in a future version ... If not, you will not be able to boot into your system, and no rollback will help!

Please inform yourself!

   Important

Since ZFS was really designed for 64 bit systems, we are only recommending and supporting 64 bit platforms and installations. We will not be supporting 32 bit platforms!

Downloading the ISO (With ZFS)

In order for us to install Funtoo on ZFS, you will need an environment that already provides the ZFS tools. Therefore we will download a customized version of System Rescue CD with ZFS included.

Name: sysresccd-4.2.0_zfs_0.6.2.iso  (545 MB)
Release Date: 2014-02-25
md5sum 01f4e6929247d54db77ab7be4d156d85


Download System Rescue CD with ZFS

Creating a bootable USB from ISO (From a Linux Environment)

After you download the iso, you can do the following steps to create a bootable USB:

Make a temporary directory
root # mkdir /tmp/loop

Mount the iso
root # mount -o ro,loop /root/sysresccd-4.2.0_zfs_0.6.2.iso /tmp/loop

Run the usb installer
root # /tmp/loop/usb_inst.sh

That should be all you need to do to get your flash drive working.

Booting the ISO

   Warning

When booting into the ISO, Make sure that you select the "Alternate 64 bit kernel (altker64)". The ZFS modules have been built specifically for this kernel rather than the standard kernel. If you select a different kernel, you will get a fail to load module stack error message.

Creating partitions

There are two ways to partition your disk: You can use your entire drive and let ZFS automatically partition it for you, or you can do it manually.

We will be showing you how to partition it manually because if you partition it manually you get to create your own layout, you get to have your own separate /boot partition (Which is nice since not every bootloader supports booting from ZFS pools), and you get to boot into RAID10, RAID5 (RAIDZ) pools and any other layouts due to you having a separate /boot partition.

gdisk (GPT Style)

A Fresh Start:

First lets make sure that the disk is completely wiped from any previous disk labels and partitions. We will also assume that /dev/sda is the target drive.

root # sgdisk -Z /dev/sda
   Warning

This is a destructive operation and the program will not ask you for confirmation! Make sure you really don't want anything on this disk.

Now that we have a clean drive, we will create the new layout.

First open up the application:

root # gdisk /dev/sda

Create Partition 1 (boot):

Command: n ↵
Partition Number: 
First sector: 
Last sector: +250M ↵
Hex Code: 

Create Partition 2 (BIOS Boot Partition):

Command: n ↵
Partition Number: 
First sector: 
Last sector: +32M ↵
Hex Code: EF02 ↵

Create Partition 3 (ZFS):

Command: n ↵
Partition Number: 
First sector: 
Last sector: 
Hex Code: bf00 ↵

Command: p ↵

Number  Start (sector)    End (sector)  Size       Code  Name
   1            2048          514047   250.0 MiB   8300  Linux filesystem
   2          514048          579583   32.0 MiB    EF02  BIOS boot partition
   3          579584      1953525134   931.2 GiB   BF00  Solaris root

Command: w ↵


Format your /boot partition

root # mkfs.ext2 -m 1 /dev/sda1

Create the zpool

We will first create the pool. The pool will be named tank. Feel free to name your pool as you want. We will use ashift=12 option which is used for a hard drives with a 4096 sector size.

root #   zpool create -f -o ashift=12 -o cachefile=/tmp/zpool.cache -O normalization=formD -m none -R /mnt/funtoo tank /dev/sda3 

Create the zfs datasets

We will now create some datasets. For this installation, we will create a small but future proof amount of datasets. We will have a dataset for the OS (/), and your swap. We will also show you how to create some optional datasets as examples ones: /home, /usr/src, and /usr/portage.

Create some empty containers for organization purposes, and make the dataset that will hold /
root # zfs create -p tank/funtoo
root # zfs create -o mountpoint=/ tank/funtoo/root

Optional, but recommended datasets: /home
root # zfs create -o mountpoint=/home tank/funtoo/home

Optional datasets: /usr/src, /usr/portage/{distfiles,packages}
root # zfs create -o mountpoint=/usr/src tank/funtoo/src
root # zfs create -o mountpoint=/usr/portage -o compression=off tank/funtoo/portage
root # zfs create -o mountpoint=/usr/portage/distfiles tank/funtoo/portage/distfiles
root # zfs create -o mountpoint=/usr/portage/packages tank/funtoo/portage/packages

Installing Funtoo

Pre-Chroot

Go into the directory that you will chroot into
root # cd /mnt/funtoo

Make a boot folder and mount your boot drive
root # mkdir boot
root # mount /dev/sda1 boot

Now download and extract the Funtoo stage3 ...


   Note

It is trully recommended to use the current version and generic64. That reduces the risk of a broken build.

After successfull ZFS installation and successfull first boot, the kernel may be changed using the eselect profile set ... command. If you create a snapshot before, you may allways come back to your previous installation, with some simple steps ... (rollback your pool and in the worst case configure and install the bootloader again)


Once you've extracted the stage3, do a few more preparations and chroot into your new funtoo environment:

Bind the kernel related directories
root # mount -t proc none proc
root # mount --rbind /dev dev
root # mount --rbind /sys sys

Copy network settings
root # cp -f /etc/resolv.conf etc

Make the zfs folder in 'etc' and copy your zpool.cache
root # mkdir etc/zfs
root # cp /tmp/zpool.cache etc/zfs

Chroot into Funtoo
root # env -i HOME=/root TERM=$TERM chroot . bash -l
   Note

How to create zpool.cache file?

If no zpool.cache file is available, the following command will create one:

root # zpool set cachefile=/etc/zfs/zpool.cache tank

Install/PortageTree

Add filesystems to /etc/fstab

Before we continue to compile and or install our kernel in the next step, we will edit the /etc/fstab file because if we decide to install our kernel through portage, portage will need to know where our /boot is, so that it can place the files in there.

Edit /etc/fstab:

   /etc/fstab
# <fs>                  <mountpoint>    <type>          <opts>          <dump/pass>

/dev/sda1               /boot           ext2            defaults        0 2

Building kernel, initramfs and grub to work with zfs

Install genkernel and initial kernel build

We need to build a genkernel initially:

root # emerge genkernel

Build initial kernel (required for checks in sys-kernel/spl and sys-fs/zfs):
root # genkernel kernel --no-clean --no-mountboot 

Installing the ZFS userspace tools and kernel modules

Emerge No results. This package will bring in No results, and No results as its dependencies:

root # emerge zfs

Check to make sure that the zfs tools are working. The zpool.cache file that you copied before should be displayed.

root # zpool status
root # zfs list

Add the zfs tools to openrc.

root # rc-update add zfs boot

If everything worked, continue.

Install GRUB 2

Install grub2:

root # echo "sys-boot/grub libzfs -truetype" >> /etc/portage/package.use
root # emerge grub

Now install grub to the drive itself (not a partition):

root # grub-install /dev/sda

Emerge genkernel and initial kernel build

Install genkernel using:

root # echo "sys-kernel/genkernel zfs" >> /etc/portage/package.use
root # emerge genkernel

Build now kernel and initramfs with --zfs
root # genkernel all --zfs --no-clean --no-mountboot --callback="emerge @module-rebuild"


   Note

During the build, ZFS configurations should be observed.

If the build breaks, restart it again.

Configuring the Bootloader

Using the genkernel you must add 'real_root=ZFS=<root>' and 'dozfs' to your params. Edit the entry for /etc/boot.conf:

   /etc/boot.conf
"Funtoo ZFS" {
        kernel kernel[-v]
        initrd initramfs-genkernel-x86_64[-v]
        params real_root=ZFS=tank/funtoo/root
        params += dozfs=force
}

The command boot-update should take care of grub configuration:

Install boot-update (if it is missing):
root #emerge boot-update

Run boot-update to update grub.cfg
root #boot-update
   Note

If boot-updatefails, try this:

root # grub-mkconfig -o /boot/grub/grub.cfg

Now you should have a new installation of the kernel, initramfs and grub which are zfs capable. The configurtion files should be updated, and the system should come up during the next reboot.

   Note

If The luks integration works basically the same way.

Final configuration

Clean up and reboot

We are almost done, we are just going to clean up, set our root password, and unmount whatever we mounted and get out.

Delete the stage3 tarball that you downloaded earlier so it doesn't take up space.
root # cd /
root # rm stage3-latest.tar.xz

Set your root password
root # passwd
>> Enter your password, you won't see what you are writing (for security reasons), but it is there!

Get out of the chroot environment
root # exit

Unmount all the kernel filesystem stuff and boot (if you have a separate /boot)
root # umount -l proc dev sys boot

Turn off the swap
root # swapoff /dev/zvol/tank/swap

Export the zpool
root # cd /
root # zpool export tank

Reboot
root # reboot
   Important

Don't forget to set your root password as stated above before exiting chroot and rebooting. If you don't set the root password, you won't be able to log into your new system.

and that should be enough to get your system to boot on ZFS.

After reboot

Forgot to reset password?

System Rescue CD

If you aren't using bliss-initramfs, then you can reboot back into your sysresccd and reset through there by mounting your drive, chrooting, and then typing passwd.

Example:

root # zpool import -f -R /mnt/funtoo tank
root # chroot /mnt/funtoo bash -l
root # passwd
root # exit
root # zpool export -f tank
root # reboot

Create initial ZFS Snapshot

Continue to set up anything you need in terms of /etc configurations. Once you have everything the way you like it, take a snapshot of your system. You will be using this snapshot to revert back to this state if anything ever happens to your system down the road. The snapshots are cheap, and almost instant.

To take the snapshot of your system, type the following:

root # zfs snapshot -r tank@install

To see if your snapshot was taken, type:

root # zfs list -t snapshot

If your machine ever fails and you need to get back to this state, just type (This will only revert your / dataset while keeping the rest of your data intact):

root # zfs rollback tank/funtoo/root@install
   Important

For a detailed overview, presentation of ZFS' capabilities, as well as usage examples, please refer to the ZFS Fun page.

Troubleshooting

Starting from scratch

If your installation has gotten screwed up for whatever reason and you need a fresh restart, you can do the following from sysresccd to start fresh:

Destroy the pool and any snapshots and datasets it has
root # zpool destroy -R -f tank

This deletes the files from /dev/sda1 so that even after we zap, recreating the drive in the exact sector
position and size will not give us access to the old files in this partition.
root # mkfs.ext2 /dev/sda1
root # sgdisk -Z /dev/sda

Now start the guide again :).


Starting again reusing the same disk partitions and the same pool

If your installation has gotten screwed up for whatever reason and you want to keep your pole named tank than you should boou into the Rescue CD / USB as done before.

import the pool reusing all existing datasets:
root # zpool import -f -R /mnt/funtoo tank

Now you should wipe the previous installation off:

let's go to our base installation directory:
root # cd /mnt/funtoo

and delete the old installation: 
root # rm -rf *

Now start the guide again, at "Pre-Chroot"