#!/usr/bin/env bash # Snapshot ZFS filesystems and stream each snapshot to a remote ZFS host. set -Eeuo pipefail usage() { cat <<'EOF' Usage: zfs-move-over-ssh.sh [options] SOURCE_POOL REMOTE_HOST DESTINATION_ROOT Create one snapshot for every filesystem in SOURCE_POOL and send each one over SSH. Filesystems retain their relative paths below DESTINATION_ROOT. Arguments: SOURCE_POOL Source ZFS pool, for example: tank REMOTE_HOST SSH host, optionally user@host DESTINATION_ROOT Existing or new destination ZFS filesystem, for example: backup/data Options: -n, --dry-run Print the ZFS and SSH commands without running them. -i, --identity-file FILE SSH private key to use. -p, --ssh-port PORT SSH port to use. --destroy-source-snapshots Destroy each local migration snapshot after its successful receive. --no-ui Disable the live progress display; print plain output. -h, --help Show this help. SSH must use key or agent authentication; password prompts are disabled. The remote SSH account must be able to run `sudo -n zfs receive` without a password prompt. This script does not destroy source filesystems or data. EOF } die() { printf 'Error: %s\n' "$*" >&2 exit 1 } DRY_RUN=false DESTROY_SOURCE_SNAPSHOTS=false NO_UI=false SSH_OPTIONS=(-o BatchMode=yes) while (($#)); do case "$1" in -n|--dry-run) DRY_RUN=true ;; -i|--identity-file) (($# >= 2)) || die "$1 requires a file path" SSH_OPTIONS+=(-i "$2") shift ;; -p|--ssh-port) (($# >= 2)) || die "$1 requires a port" SSH_OPTIONS+=(-p "$2") shift ;; --destroy-source-snapshots) DESTROY_SOURCE_SNAPSHOTS=true ;; --no-ui) NO_UI=true ;; -h|--help) usage exit 0 ;; --) shift break ;; -*) die "unknown option: $1" ;; *) break ;; esac shift done (($# == 3)) || { usage >&2 exit 2 } SOURCE_POOL="$1" REMOTE_HOST="$2" DESTINATION_ROOT="${3%/}" SNAPSHOT_NAME="move-$(date +%Y%m%d-%H%M%S)" [[ "$REMOTE_HOST" != *@ ]] || die "REMOTE_HOST is missing a hostname; use user@server-name or server-name" command -v zfs >/dev/null || die "zfs command was not found" command -v zpool >/dev/null || die "zpool command was not found" command -v ssh >/dev/null || die "ssh command was not found" zpool list -H -o name "$SOURCE_POOL" >/dev/null || die "source pool does not exist: $SOURCE_POOL" if ! $DRY_RUN; then ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" true \ || die "cannot authenticate to $REMOTE_HOST with SSH keys or an SSH agent" ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" 'sudo -n zfs list -H -o name -t filesystem >/dev/null' \ || die "$REMOTE_HOST accepts SSH, but cannot run 'sudo -n zfs'; configure passwordless sudo for zfs" fi map_destination() { local filesystem="$1" local relative_path="${filesystem#"$SOURCE_POOL"}" printf '%s%s\n' "$DESTINATION_ROOT" "$relative_path" } run() { if $DRY_RUN; then printf '+' >&2 printf ' %q' "$@" >&2 printf '\n' >&2 else "$@" fi } remote_snapshot_exists() { local remote_snapshot="$1" ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" \ "sudo -n zfs list -H -o name -t snapshot '$remote_snapshot' >/dev/null 2>&1" } remove_remote_snapshot() { local remote_snapshot="$1" local reply printf 'Remote snapshot %s already exists. Delete it and retry? [y/N] ' "$remote_snapshot" >&2 read -r reply [[ "$reply" =~ ^[Yy]([Ee][Ss])?$ ]] || die "remote snapshot was not deleted; stopping" ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "sudo -n zfs destroy '$remote_snapshot'" \ || die "could not delete remote snapshot $remote_snapshot" } mapfile -t FILESYSTEMS < <(zfs list -H -o name -t filesystem -r "$SOURCE_POOL") ((${#FILESYSTEMS[@]} > 0)) || die "no filesystems found in $SOURCE_POOL" # Progress UI needs a terminal and a real transfer. UI=false if ! $DRY_RUN && ! $NO_UI && [[ -t 1 ]]; then UI=true exec 4>&1 fi # Per-filesystem weights so the overall bar reflects data size, not dataset count. declare -A WEIGHT=() TOTAL_WEIGHT=0 if $UI; then while IFS=$'\t' read -r fs_name fs_weight; do [[ "$fs_weight" =~ ^[0-9]+$ ]] || fs_weight=0 WEIGHT["$fs_name"]=$fs_weight TOTAL_WEIGHT=$((TOTAL_WEIGHT + fs_weight)) done < <(zfs list -Hp -o name,logicalreferenced -t filesystem -r "$SOURCE_POOL") if ((TOTAL_WEIGHT == 0)); then for fs_name in "${FILESYSTEMS[@]}"; do WEIGHT["$fs_name"]=1; done TOTAL_WEIGHT=${#FILESYSTEMS[@]} fi fi # Reads `zfs send -P -v` output on stdin and redraws a 3-line block on fd 4. send_progress() { local idx="$1" count="$2" name="$3" prior_w="$4" cur_w="$5" total_w="$6" fresh="$7" awk -F'\t' -v idx="$idx" -v count="$count" -v name="$name" -v fresh="$fresh" \ -v prior_w="$prior_w" -v cur_w="$cur_w" -v total_w="$total_w" ' function human(b, u, i) { split("B KB MB GB TB PB", u, " "); i = 1 while (b >= 1024 && i < 6) { b /= 1024; i++ } return sprintf("%.1f%s", b, u[i]) } function bar(p, n, s, i) { if (p > 100) p = 100 n = int(p * 30 / 100); s = "" for (i = 0; i < 30; i++) s = s (i < n ? "#" : "-") return "[" s "]" } function hms(s) { return sprintf("%d:%02d:%02d", s / 3600, (s % 3600) / 60, s % 60) } function render( pct, op, eta) { pct = (est > 0) ? b * 100 / est : 0 if (pct > 100) pct = 100 op = (total_w > 0) ? (prior_w + cur_w * pct / 100) * 100 / total_w : 0 eta = (rate > 0 && est > b) ? " ETA " hms((est - b) / rate) : "" printf "\033[3A\r\033[2K [%d/%d] %s\n", idx, count, name printf "\033[2K Dataset %s %3d%% %s / %s %s/s%s\n", bar(pct), pct, human(b), human(est), human(rate), eta printf "\033[2K Overall %s %3d%%\n", bar(op), op } BEGIN { if (fresh == 1) printf "\n\n\n" } $1 == "size" { est = $2 + 0; render(); next } $1 == "full" || $1 == "incremental" { next } $1 ~ /^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$/ { split($1, t, ":"); s = t[1] * 3600 + t[2] * 60 + t[3]; b = $2 + 0 if (seen && s > ls) { inst = (b - lb) / (s - ls); rate = rate ? 0.7 * rate + 0.3 * inst : inst } ls = s; lb = b; seen = 1; render(); next } { printf "\033[3A\033[J%s\n\n\n\n", $0 } END { render() } ' >&4 3>&- } prior_weight=0 index_now=0 BLOCK_DRAWN=0 FAILED=() SKIPPED=() trap 'printf "\nInterrupted.\n" >&2; exit 130' INT TERM remote_dataset_exists() { ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" \ "sudo -n zfs list -H -o name -t filesystem '$1' >/dev/null 2>&1" } printf 'Migration snapshot: %s\n' "$SNAPSHOT_NAME" for filesystem in "${FILESYSTEMS[@]}"; do destination="$(map_destination "$filesystem")" snapshot="${filesystem}@${SNAPSHOT_NAME}" remote_snapshot="${destination}@${SNAPSHOT_NAME}" index_now=$((index_now + 1)) # Never touch datasets that already exist on the destination (no -F, no rollback). if ! $DRY_RUN && remote_dataset_exists "$destination"; then $UI || printf 'Skipping %s: %s already exists on %s\n' "$filesystem" "$destination" "$REMOTE_HOST" SKIPPED+=("$filesystem") prior_weight=$((prior_weight + ${WEIGHT[$filesystem]:-0})) continue fi $UI || printf 'Transferring %s to %s:%s\n' "$filesystem" "$REMOTE_HOST" "$destination" run zfs snapshot "$snapshot" if $DRY_RUN; then printf '+ zfs send -p %q | ssh' "$snapshot" >&2 printf ' %q' "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "sudo -n zfs receive -u '$destination'" >&2 printf '\n' >&2 else if remote_snapshot_exists "$remote_snapshot"; then BLOCK_DRAWN=0 remove_remote_snapshot "$remote_snapshot" fi if $UI; then ssh_err="$(mktemp)" send_status=0 { zfs send -p -P -v "$snapshot" 2>&1 1>&3 3>&- \ | send_progress "$index_now" "${#FILESYSTEMS[@]}" "$filesystem" \ "$prior_weight" "${WEIGHT[$filesystem]:-0}" "$TOTAL_WEIGHT" \ "$((1 - BLOCK_DRAWN))" } 3>&1 | ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "sudo -n zfs receive -u '$destination'" 2>"$ssh_err" \ || send_status=$? BLOCK_DRAWN=1 if ((send_status != 0)); then BLOCK_DRAWN=0 printf '\nTransfer of %s failed (exit %d):\n' "$filesystem" "$send_status" >&2 cat "$ssh_err" >&2 rm -f "$ssh_err" FAILED+=("$filesystem") prior_weight=$((prior_weight + ${WEIGHT[$filesystem]:-0})) continue fi rm -f "$ssh_err" prior_weight=$((prior_weight + ${WEIGHT[$filesystem]:-0})) else zfs send -p "$snapshot" | ssh "${SSH_OPTIONS[@]}" "$REMOTE_HOST" "sudo -n zfs receive -u '$destination'" fi fi if $DESTROY_SOURCE_SNAPSHOTS; then run zfs destroy "$snapshot" fi done if ((${#SKIPPED[@]} > 0)); then printf 'Skipped %d filesystem(s) that already exist on the destination:\n' "${#SKIPPED[@]}" printf ' %s\n' "${SKIPPED[@]}" fi if ((${#FAILED[@]} > 0)); then printf 'Finished with %d failed filesystem(s):\n' "${#FAILED[@]}" >&2 printf ' %s\n' "${FAILED[@]}" >&2 exit 1 fi printf 'Completed. Local source filesystems were not destroyed.\n'