Skip to content

Instantly share code, notes, and snippets.

@philpep
Created June 23, 2011 20:05
Show Gist options
  • Save philpep/1043499 to your computer and use it in GitHub Desktop.
Save philpep/1043499 to your computer and use it in GitHub Desktop.
zfs backup script
#!/bin/sh
set -e
# Used in ssh command, example user@host -p 2222
REMOTE_HOST="diophante"
# Source zfs pool
POOL_SRC="tank"
# zfs sets to backup (relative to POOL_SRC)
SETS="usr/local/vmail usr/local/data usr/local/pgsql/backups usr/home usr/local/git var/backups"
# Destination pool
POOL_DST="tank/backup/${REMOTE_HOST}"
# We use ssh connection sharing
SSH_ARGS="-o ControlPath=~/.ssh/%r@%h:%p"
# zfs snapshot prefix => tank/foo@bck-2011-05-25
PREFIX="bck-"
# Remote zfs command
REMOTE_ZFS="ssh ${SSH_ARGS} ${REMOTE_HOST} sudo zfs"
# Local zfs command
LOCAL_ZFS="sudo zfs"
# Launch master ssh for sharing connections
ssh -MNn ${SSH_ARGS} ${REMOTE_HOST} &
ssh_master_pid=$!
for zfs_set in ${SETS}
do
# Test if destination exist
${LOCAL_ZFS} list -H ${POOL_DST}/${zfs_set} >/dev/null
date_suffix="${PREFIX}`date +%F`"
snap="${POOL_SRC}/${zfs_set}@${date_suffix}"
old_snap=`${REMOTE_ZFS} list -Ht snapshot 2>/dev/null | grep "^${POOL_SRC}/${zfs_set}@${PREFIX}" 2>/dev/null| awk -F' ' '{ print $1 }' 2>/dev/null`
if [ "${old_snap}" ]
then
if [ "${old_snap}" != "`echo ${old_snap} | head -n 1`" ]
then
echo "[!] Multiple zfs snapshot found: ${old_snap}"
echo "[!] Consider changing PREFIX or fix the issue yourself"
continue
fi
if [ "${old_snap}" = "${snap}" ]
then
echo "[!] ${snap} exists"
continue
fi
fi
echo ${REMOTE_ZFS} snapshot "${snap}"
${REMOTE_ZFS} snapshot "${snap}"
if [ "${old_snap}" ]
then
extra_args="-i ${old_snap}"
else
extra_args=""
fi
echo ${REMOTE_ZFS} send $extra_args "${snap}" '|' ${LOCAL_ZFS} recv -F "${POOL_DST}/${zfs_set}"
${REMOTE_ZFS} send $extra_args "${snap}" | ${LOCAL_ZFS} recv -F "${POOL_DST}/${zfs_set}"
if [ "${old_snap}" ]
then
echo ${REMOTE_ZFS} destroy "${old_snap}"
${REMOTE_ZFS} destroy "${old_snap}"
fi
done
kill $ssh_master_pid
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment