Backup

How to backup a Xen VM on a ZFS filesystem

!/bin/bash
VM="test"
BACKUP_TARGET="/root/backup-${VM}.tar.gz"
BACKUP_DIR="/mnt/backup/${VM}"
ZFS_SNAPSHOT=tank/${VM}-disk@backup
ZFS_CLONE="tank/${VM}-disk-backup"
echo "Checking backup directory"
mount | grep "$BACKUP_DIR" && umount $BACKUP_DIR
mkdir -p $BACKUP_DIR || exit 1
echo "Cleanup backup snapshot"
zfs list $ZFS_CLONE > /dev/null 2>&1 && zfs destroy $ZFS_CLONE
zfs list -t snapshot $ZFS_SNAPSHOT > /dev/null 2>&1 && zfs destroy $ZFS_SNAPSHOT
echo "Create snapshot"
zfs snapshot $ZFS_SNAPSHOT || exit 1
echo "Clone snapshot"
zfs clone $ZFS_SNAPSHOT $ZFS_CLONE || exit 2
# ZFS needs some time
sleep 5
echo "Mounting snapshot"
mount /dev/zvol/$ZFS_CLONE $BACKUP_DIR || exit 3
echo "Creating backup archive"
tar -cvpzf $BACKUP_TARGET -C $BACKUP_DIR .
echo "Cleanup"
umount $BACKUP_DIR
zfs destroy $ZFS_CLONE
zfs destroy $ZFS_SNAPSHOT