Xen Backup Script

From Wiki
Jump to: navigation, search

If you're using LVM based storage for your domains this script will create a snapshot and backup each server to a local drive or a remote system using rdiff-backup.

#!/usr/bin/env bash

PATH="/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin"

BACKUPTYPE="remote"
BACKUPSERVER="10.4.234.234"
BACKUPDEVICE="/dev/sdb1"
FSTYPE="xfs"
LOCALBACKUPDIR="/backup"
BACKUPADMIN="wattersm@example.com"
servertype="linux"

function mount_drive() {
        mount -t $1 $2 $3
}

function do_local_backup() {
        HOSTS=`cat /etc/backup/backup.list`
        for host in $HOSTS; do
                lvcreate -l 500 -s -n vsbackup /dev/my_volume_group/${host}
                if [ $? != 0 ]; then
                        echo "Error creating snapshot volume, exiting."
                        echo
                        exit 1
                fi
                mount -t ext3 /dev/my_volume_group/vsbackup /mnt/lvmsnapshot
                rdiff-backup -v 4 --exclude /mnt/lvmsnapshot/proc/* /mnt/lvmsnapshot /backup/${host}
                umount /mnt/lvmsnapshot
                lvremove -f /dev/my_volume_group/vsbackup
        done
}

function do_remote_backup() {
        HOSTS=`cat /etc/backup/backup.list`
        for host in $HOSTS; do
                lvcreate -L 2048M -s -n vsbackup /dev/my_volume_group/${host}
                if [ $? != 0 ]; then
                        echo "Error creating snapshot volume, exiting."
                        echo
                        exit 1
                fi
                mount -t ext3 /dev/my_volume_group/vsbackup /mnt/lvmsnapshot
                rdiff-backup -v 4 --exclude /mnt/lvmsnapshot/proc/* /mnt/lvmsnapshot ${BACKUPSERVER}::/backup/`hostname`/${host}
                umount /mnt/lvmsnapshot
                lvremove -f /dev/my_volume_group/vsbackup
        done
}

function do_win_backup() {
        cp -fv /xen/images/* /backup
        umount /backup
}

function do_remote_win_backup() {
        rdiff-backup -v 4 /xen/images ${BACKUPSERVER}::/backup/`hostname`
}


if [ ! -d /mnt/lvmsnapshot ]; then
        mkdir /mnt/lvmsnapshot
fi


if [ $BACKUPTYPE != "remote" ] && [ $servertype == "linux" ]
then
        mount_drive $FSTYPE $BACKUPDEVICE $LOCALBACKUPDIR
        do_local_backup
        umount /backup
        exit
fi

if [ $BACKUPTYPE != "remote" ] && [ $servertype == "windows" ]
then
        mount_drive $FSTYPE $BACKUPDEVICE $LOCALBACKUPDIR
        do_win_backup
        umount /backup
        exit
fi

if [ $BACKUPTYPE == "remote" ] && [ $servertype == "linux" ]
then
        echo "Running remote backup..."
        echo $FSTYPE $BACKUPDEVICE $LOCALBACKUPDIR
        do_remote_backup
        exit
fi

if [ $BACKUPTYPE == "remote" ] && [ $servertype == "windows" ]
then
        do_remote_win_backup
        exit
fi

echo
echo "Backups done!"
echo