Skip to content

Instantly share code, notes, and snippets.

@vanokg
Created October 4, 2018 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanokg/7e27c5d577f850430b888cebd396345b to your computer and use it in GitHub Desktop.
Save vanokg/7e27c5d577f850430b888cebd396345b to your computer and use it in GitHub Desktop.
backup virtual
#!/bin/bash
LANG=C
# Default variables
dest="/srv/backups/virt"
cleanup=0
confdir="/etc/libvirt/qemu"
shell="/usr/bin/virsh"
xmldir="${dest}/xml"
images="${dest}/images"
date=$(date +%d_%m_%Y)
usage() {
echo -e "\n Usage: $0 [PARAMETERS] \n
Run backup of virtual machines.
\n
PARAMETERS:
-n, --name= name of virtual machine to backup (required)\n
Optional (see script header for defaults):
-d, --dest= backup destination directory
-r, --remove= days to store backups, older files will be removed. Default is 0 (forever)
-h, --help display this help"
}
if [ "$#" -eq 0 ]; then
usage
exit
fi
while [ "$#" -gt 0 ]; do
case "$1" in
-n) name="$2"; shift 2;;
-d) dest="$2"; shift 2;;
-r) cleanup="$2"; shift 2;;
-h) usage; exit; ;;
--name=*) name="${1#*=}"; shift 1;;
--dest=*) sest="${1#*=}"; shift 1;;
--remove=*) cleanup="${1#*=}"; shift 1;;
--help) usage; exit; ;;
--name|--dest) echo "$1 requires an argument" >&2; exit 1;;
-*) echo -e "Unknown option: $1\nUse --help or -h for usage information" >&2; exit 1;;
*) handle_argument "$1"; shift 1;;
esac
done
if [ "x${name}" = "x" ]; then
echo "Error: Virtual machine name is a required argument!"
exit 0
fi
# lock|unlock for service status check script
lock() {
if [ ! -f /tmp/bcp ]; then
mkdir -p /tmp/bcp
fi
echo "Locking ${name}"
touch /tmp/bcp/${name}.lock
}
unlock() {
echo "Unlocking ${name}"
rm -f /tmp/bcp/${name}.lock
}
copy() {
for disk in $($shell -q -r domblklist ${name} --details | grep disk | awk '{ print $4 }')
do
ext=$(echo ${disk} | rev | cut -d\. -f 1 | rev)
img=$(echo ${disk} | cut -d\. -f 1 | rev | cut -d\/ -f 1 | rev)
echo "Copying ${disk} to destination directory"
cp ${disk} ${images}/${img}-${date}.${ext}
done
echo "Copying ${name}'s config to destination directory"
cp ${confdir}/${name}.xml ${xmldir}/${name}-${date}.xml
}
clean(){
for fldr in ${images} ${xmldir}
do
echo "Delete files in ${fldr} older than ${days}"
find ${fldr} -type f -name ${name}\* -mtime $days -delete
done
}
# Check target directory structure
if [ ! -d ${images} ]; then
mkdir -p ${images}
elif [ ! -d ${xmldir} ]; then
mkdir -p ${xmldir}
fi
state=$($shell domstate ${name})
if [ "x${state}" = "xrunning" ]; then
lock
locked=1
$shell suspend $name
fi
copy
if [ $cleanup -gt 0 ]; then
clean
fi
if [ $locked -eq 1 ]; then
$shell resume $name
unlock
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment