From 25e40ddaca2433755d2bf03e214bd72955d47866 Mon Sep 17 00:00:00 2001 From: Jack-Benny Persson Date: Sat, 16 Sep 2017 21:17:40 +0200 Subject: [PATCH] Added the files --- README.md | 22 ++++++++++++++++++++++ qemu-backup.sh | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 README.md create mode 100644 qemu-backup.sh diff --git a/README.md b/README.md new file mode 100644 index 0000000..809ce56 --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# What is it? +This is a simple Bash script I made to automatically backup my +virtual machines on my server. It's working really well for me, +but there is no guarantee it will work for you. +The script retains a set number of backups before starting to rotate. +The backups are named with a date and timestamp and the rotation-number. + + +# Usage +Replace the made-up names with the name, disktype and diskfile of your +real virtual machines. + +`NUMBACKUPS` decides how many backups should be retained. The file *rotate.txt* +keeps track of the rotation. + +`VMDISKDIR` is the directory where the virtual machines are stored on the +server, not the backup dir. + +Also make sure to check and/or change the directories to match your +machine. + +Then simple put the script in a cronjob. diff --git a/qemu-backup.sh b/qemu-backup.sh new file mode 100644 index 0000000..d94b4aa --- /dev/null +++ b/qemu-backup.sh @@ -0,0 +1,46 @@ +#!/bin/bash +set -e + +PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin" +TODAY=`date +"%F-%s"` + +#### Change these variables ### +NUMBACKUPS=3 +VMS=( "orbit" "red-dwarf" "elektra" "lisa" ) +DISK=( "sda" "vda" "sda" "sda" ) +DISKNAME=("orbit-disk1.raw" "red-dwarf.qcow2" "elektra-disk1.raw" "lisa-disk1.raw") + +BACKUPDIR="/data/vm-backups" +VMDISKDIR="/vm" +XMLDIR="/etc/libvirt/qemu" + + +### Program start ### +SCRIPTDIR=`pwd` + + +if [ ! -e ${SCRIPTDIR}/rotate.txt ]; then + echo 1 > ${SCRIPTDIR}/rotate.txt +fi + +ROTATE=`cat ${SCRIPTDIR}/rotate.txt` + +if [ $ROTATE -gt $NUMBACKUPS ]; then + ROTATE=1 +fi + +for (( i = 0; i < ${#VMS[@]}; i++ )) + do virsh snapshot-create-as --domain ${VMS[i]} --diskspec ${DISK[i]},file=${BACKUPDIR}/${VMS[i]}-snapshot.qcow2 --disk-only --atomic --no-metadata + sleep 5 + rm -rf ${BACKUPDIR}/backup${ROTATE}-*-${DISKNAME[i]} + cp ${VMDISKDIR}/${DISKNAME[i]} ${BACKUPDIR}/backup${ROTATE}-${TODAY}-${DISKNAME[i]} + virsh blockcommit ${VMS[i]} ${DISK[i]} --active --verbose --pivot + sleep 5 + rm ${BACKUPDIR}/${VMS[i]}-snapshot.qcow2 + rm -rf ${BACKUPDIR}/backup${ROTATE}-*-${VMS[i]}.xml + cp ${XMLDIR}/${VMS[i]}.xml ${BACKUPDIR}/backup${ROTATE}-${TODAY}-${VMS[i]}.xml +done + +ROTATE=`echo "$ROTATE + 1" | bc` +echo $ROTATE > ${SCRIPTDIR}/rotate.txt +