# ZFS home datasets for Virtualmin and Webmin

Webmin and Virtualmin don't know about ZFS. These scripts give every home on
the server its own ZFS dataset, so each domain, sub-server and mailbox gets a
real quota, its own snapshots, and one-step renames.

| File | What it is |
|---|---|
| `zfs-home-lib.pl` | Settings and shared code. The other scripts need it in the same directory. |
| `zfs-before` | Hook: creates and renames datasets. |
| `zfs-after` | Hook: sets quotas and destroys deleted homes' datasets. |
| `zfs-home-convert` | Converts existing plain-directory homes to datasets, and checks the layout (`--check`). |

Everything is plain Perl 5 with core modules only.

## How the layout works

Dataset names follow paths. `rpool/home` is the dataset for `/home`, and every
other dataset inherits its mountpoint from it:

```
dataset                                   mounted at                     canmount
rpool/home                                /home                          off
rpool/home/example                        /home/example                  on
rpool/home/example/domains                (container, not mounted)       off
rpool/home/example/domains/shop.example   /home/example/domains/shop.example  on
rpool/home/example/homes                  (container, not mounted)       off
rpool/home/example/homes/bob              /home/example/homes/bob        on
```

- **Every home is a dataset.** Owners, sub-servers and mailboxes each have their
  own mounted dataset.
- **`domains` and `homes` are containers.** They exist so that names and
  mountpoints line up. They have `canmount=off`, so they never mount and hold no
  files. On disk, `/home/example/homes` is an ordinary folder in the owner's
  dataset, with each mailbox's dataset mounted inside it.
- **`rpool/home` is `canmount=off` too,** unless it was already mounted at
  `/home` (common on root-on-ZFS installs), in which case it stays mounted.
  Either works.

Because mountpoints are inherited, renaming a domain is one `zfs rename` and
everything under it follows. Because names follow paths,
`/home/example/domains/foo` and `/home/example/homes/foo` can never clash.

**What you see in `ls` is not the whole story.** A dataset that exists but isn't
mounted looks exactly like a normal folder, and a quota on it does nothing.
This command shows what is really there:

```sh
zfs list -r -o name,canmount,mounted,mountpoint,quota,used rpool/home
```

Every home should be `mounted yes`. Only containers and `rpool/home` itself
should be `canmount off`. `zfs-home-convert --check` does this comparison for
you (see [Checking the layout](#checking-the-layout)).

## Settings

Edit the top of `zfs-home-lib.pl`:

| Setting | Default | Meaning |
|---|---|---|
| `$pool` | `rpool` | Pool name. |
| `$base` | `"$pool/home"` | The dataset that maps to `/home`. |
| `$zfs` | `/usr/sbin/zfs` | Path to the `zfs` command. |
| `$qtype` | `quota` | `quota` counts snapshots and child datasets; `refquota` doesn't. |
| `$verbose` | `1` | Print each step in Virtualmin's output. |
| `$logfile` | `''` (off) | Set to e.g. `/var/log/zfs-home-hooks.log` to log every hook run. Useful for debugging. |
| `$default_user_quota` | `0` (none) | Quota in KB for new users. Webmin can't read quotas on ZFS, so it never passes one, and with `0` mailboxes are limited only by their domain's quota. Set this if you add users in Webmin without Virtualmin. |

## Installing the hooks

1. Put all the files in one directory, e.g. `/root/zscripts/`, and make the
   scripts executable: `chmod 700 /root/zscripts/zfs-before /root/zscripts/zfs-after /root/zscripts/zfs-home-convert`.
2. If the server already has homes, convert them first (see
   [Converting an existing server](#converting-an-existing-server)). At minimum,
   `rpool/home` must have `mountpoint=/home`. The before-hook refuses to create
   anything until it does, and running the converter sets that up.
3. In **Virtualmin → System Settings → Virtualmin Configuration → Actions upon
   server and user creation**, set:
   - *Command to run before making changes to a server*: `/root/zscripts/zfs-before`
   - *Command to run after making changes to a server*: `/root/zscripts/zfs-after`
4. In **Webmin → System → Users and Groups → Module Config**, set the commands
   to run before and after making changes to the same two scripts. Virtualmin
   creates mailbox users through this module, so this is what gives mailboxes
   their datasets.
5. Create a test domain with a mailbox user, and check with the `zfs list`
   command above.

## What the hooks do

| Event | Before-hook | After-hook |
|---|---|---|
| Domain created | creates its dataset | sets the domain's quota |
| Domain modified | nothing | sets the quota from the new values |
| Domain renamed with its home | renames the dataset; everything under it follows | sets the quota |
| Domain deleted | nothing | destroys the dataset, its children and its snapshots |
| User created | creates the home's dataset (and any container) | sets `$default_user_quota`, if any |
| User renamed with its home | renames the dataset | nothing |
| User deleted | nothing | destroys the dataset |
| Alias domain (any event) | nothing | nothing |

The before-hook leaves a home as a plain directory, and says so in the output,
when its parent isn't a dataset (for example a mailbox under an owner that was
never converted). The after-hook leaves a dataset alone if the deleted home
still contains files, meaning Virtualmin was told to keep them, or if the
dataset is mounted somewhere other than the deleted home.

Some Virtualmin behaviours the hooks work around:

- Quotas are only set after a change. Before a change, Virtualmin's
  `VIRTUALSERVER_NEWSERVER_QUOTA` can still hold the old value, for example when
  switching plans.
- During a domain event, Virtualmin leaves `USERADMIN_*` variables from its
  own user changes in the environment. The hooks ignore them, so a domain change
  never acts on a stale user.
- On ZFS, Webmin always passes an empty `USERADMIN_QUOTA`. The hooks treat
  that as "unknown", never as "no quota".

## Converting an existing server

`zfs-home-convert` turns existing plain-directory homes into datasets. It
handles a server with no datasets at all, or a mix of datasets and directories,
such as one where the hooks were added after some domains already existed. It
finds homes in Virtualmin's domain list (not aliases) and in `/etc/passwd`
(UID 1000 and up), and leaves anything that's already a dataset alone. That
makes it safe to run again at any time.

```sh
./zfs-home-convert                               # dry run: shows the plan, changes nothing
./zfs-home-convert --home=/home/example          # one domain and the homes under it
./zfs-home-convert --levels=owners,subservers    # leave mailboxes as they are
./zfs-home-convert --apply                       # do it
```

For each home, parents first, it:

1. creates the dataset (`canmount=off`) and any `domains`/`homes` container;
2. moves the folder aside to `.<name>.pre-zfs-<date>-<time>` in the same directory;
3. mounts the dataset at the home and copies the files in with `cp -ax`,
   keeping owners, modes, timestamps and extended attributes;
4. compares the file counts, and copies immutable and append-only flags across
   (`cp` doesn't). Virtualmin sets the immutable flag on FCGI wrapper scripts;
5. remounts any datasets that were already mounted inside.

It refuses a home that is in use, that has another filesystem mounted inside
it, or that won't fit (quotas and pool space are both checked). If anything
fails before the copy is complete, it removes what it created, puts the folder
back, and stops. Run the dry run first. Then convert one test domain with
`--home=` before doing the rest.

### Before you start: stop the services that use the homes

A process with a file open in a home keeps writing to the *old* copy after the
move. New mail, uploads or log lines would end up in the folder you are about
to delete. The converter refuses homes that are in use, but stopping services
first saves a lot of re-runs. On Debian:

```sh
systemctl list-units --type=service 'php*-fpm*'     # see which PHP-FPM versions you run

systemctl stop apache2 'php*-fpm.service' postfix dovecot proftpd spamd cron usermin
```

Leave out anything you don't run; `systemctl` just reports that the unit isn't
loaded. Use your own web server's unit if it isn't Apache (`nginx`,
`hiawatha`, …). Some notes:

- **Postfix**: while it's stopped, other servers queue mail for you and retry
  later. Nothing is lost if the outage is short.
- **PHP**: with FCGId or CGI instead of PHP-FPM, PHP runs under Apache, so
  stopping Apache covers it.
- **cron**: stops user cron jobs and Virtualmin's scheduled jobs, such as
  backups, from writing into homes. Also check that no Virtualmin backup is
  already running.
- **Webmin**: keep it running if you need it, but don't run the converter from
  Webmin's own shell or file manager. Use SSH as root, from a directory outside
  `/home` (`cd /root`).
- **Users' own sessions**: SSH, `screen` or `tmux` sessions inside a home also
  count. `who` lists them; `loginctl terminate-user <user>` ends them.

Start everything again afterwards with `systemctl start` and the same list.

### Finding what's holding files open

The converter names the processes it found (`in use by dovecot(1234)`). To look
yourself, replace `/home/example` with the home in question:

```sh
# Processes whose working directory is inside the home (shells, cron jobs, scripts)
ls -l /proc/[0-9]*/cwd 2>/dev/null | grep ' -> /home/example'

# Processes with a file open inside the home
find /proc/[0-9]*/fd -lname '/home/example/*' 2>/dev/null | cut -d/ -f3 | sort -u |
    xargs -r ps -o pid,user,comm,args -p

# The same with lsof, which shows the file names too (apt install lsof; slow on big homes)
lsof +D /home/example
```

When `zfs unmount` or `zfs rename` reports **"target is busy"** on something
that is already a dataset, it is its own filesystem, so `fuser` can list
everything using it:

```sh
fuser -vm /home/example/homes/bob
```

Don't use `fuser -m` on a plain directory. It reports every process using the
whole filesystem underneath (usually the root filesystem), which is nearly
everything.

The usual culprits:

| Process | Why it's there | Fix |
|---|---|---|
| your own shell (`bash`) | you `cd`'d into the home | `cd /root` |
| `apache2`, `php-fpm`, `php-cgi` | site files, PHP sessions, logs | stop the web server and PHP-FPM |
| `dovecot`, `imap`, `indexer-worker` | mailboxes | stop dovecot |
| `postfix`, `local`, `procmail`, `spamd` | mail delivery | stop postfix and spamd |
| `cron`, `sh`, `perl` | scheduled jobs, backups | stop cron; wait for backups to finish |
| `sshd`, `sftp-server`, `screen`, `tmux` | a user's login session | `loginctl terminate-user <user>` |
| `proftpd` | FTP sessions | stop proftpd |

### After converting

1. Check the homes: sites load, mail arrives, and `zfs list` shows each home
   mounted.
2. Remove the old copies listed at the end of the run:
   `rm -rf /home/.example.pre-zfs-…`. The converter has already cleared their
   immutable flags. Until you delete them they take up space: an owner's old
   copy sits next to `/home`, a mailbox's old copy sits inside its domain's
   dataset and counts towards that domain's quota.
3. The run writes an undo script (default `/root/zfs-home-undo-convert-…sh`).
   It puts the plain folders back, newest first. It only works while the old
   copies still exist, and anything written to the new homes since is left in
   the (then unmounted) datasets, not copied back.

## Checking the layout

```sh
./zfs-home-convert --check             # prints only problems; exit code 1 if there are any
./zfs-home-convert --check --verbose   # also prints "All good" and datasets outside the layout
```

It changes nothing. It reports:

- datasets with a quota that aren't mounted, so the quota does nothing;
- datasets with `canmount=on` that aren't mounted, i.e. something should have
  mounted and didn't;
- unmounted datasets holding data, which is hidden from view;
- placeholder datasets, unmounted, whose home is a plain folder or no longer
  exists;
- homes that are still plain directories;
- `.pre-zfs-` copies left from a conversion;
- `rpool/home` missing or not set to `mountpoint=/home`.

It prints nothing when all is well, so it can go straight into cron, which
mails you only when there's something to see:

```
# /etc/cron.d/zfs-home-check
30 6 * * 1  root  /root/zscripts/zfs-home-convert --check
```

Run it after every reboot too. That's when a mount that didn't come back would
show up.

## Known behaviours and troubleshooting

- **Reload Virtualmin after renaming a domain.** Its left-hand menu can keep the
  old name, and deleting the domain from that stale page deletes using the old
  details. Configuration under the new name is then left behind, and the
  after-hook is given a home that no longer exists, so it rightly does nothing.
- **Virtualmin's quota and disk usage pages are blank or 0.** They can't read
  ZFS quotas. Use
  `zfs list -r -o name,used,quota rpool/home`.
- **Mailbox quotas.** Virtualmin's own mail quota counts message sizes, while
  ZFS counts compressed blocks on disk, so the mail quota normally triggers
  first and the ZFS quota acts as the backstop.
- **"rm: cannot remove …: Operation not permitted" as root** means the file
  is immutable (`lsattr` shows an `i`). Clear it with `chattr -i <file>`.
- **Restores** recreate the domain through the same hooks, so the files land
  in a new dataset. Mailbox users come back as datasets too.
- **Snapshots** of the whole tree: `zfs snapshot -r rpool/home@<name>`. If
  your snapshot tool works per dataset rather than recursively, add new homes to
  it or switch it to recurse from `rpool/home`.
- **Something isn't working**: set `$logfile` in `zfs-home-lib.pl` and repeat
  the action. Each hook run logs its action, home and every step.
