Friday, December 17, 2010

KVM weekly backup, the easy way

For the joy of all my readers here it comes the master-of-the-universe weekly script backup for KVM:

# Redirect stdout/stderr to custom log.

exec 1>> /var/log/custom_$(basename ${0}).$(whoami).$(date '+%Y%m%d').log 2>&1
pushd /media/backup/MyServer1/
# Keep copies of the VM for the last 4 weeks.
mv kvm.qemu.gz.1 kvm.qemu.gz.2
mv kvm.qemu.gz.0 kvm.qemu.gz.1
mv kvm.qemu.gz kvm.qemu.gz.0

# Stop KVM instance through telnet.
# KVM has to be started with the option:
# -monitor telnet:127.0.0.1:9942,server,nowait
echo "stop" | nc -q 10 127.0.0.1 9942
# Freeze KVM instance

#Here we do the real backup of the KVM instance

cat /VM-Images/kvm.qemu | gzip > /media/backup/MyServer1/kvm.qemu.gz
if [ $? != 0 ]; then
echo "WARN: KVM backup failed"
fi
echo "c" | nc -q 10 127.0.0.1 9942 # Continue KVM instance
popd

For the previous script to work correctly we have to start the KVM instance with the option -monitor telnet:127.0.0.1:9942.

In my particular system I start KVM instances at startup in /etc/rc.local. This is script is also quite interesting so I extracted all the kvm related stuff:

/etc/rc.local:
# Setting up the bridge (tip: apt-get install bridge-utils)
brctl addbr ofi1
brctl addif ofi1 eth1
ifconfig eth1 0.0.0.0 promisc up
ifconfig ofi1 192.168.2.100 netmask 255.255.0.0 up
ifconfig ofi1:1 172.16.1.3

...
kvm -net nic,macaddr=52:54:00:19:34:56 \
-net tap,script=/etc/qemu-ifup -hda /VM-Images/kvm.qemu \
-boot c -vnc :5 1>/var/log/custom_kvm.qemu.log \
-monitor telnet:127.0.0.1:9942,server,nowait 2>&1 &
...
# ionice/renice down our virtual machine
PID=$(sof /VM-Images/kvm.qemu | grep -v ^COMMAND | while read cmd pid staff; do echo $pid; done)
ionice -c 3 -p ${PID} &
renice 10 -p
${PID} &


/etc/qemu-ifup:
#!/bin/sh
# ofi1 is the choosen name in /etc/rc.local
/usr/sbin/brctl addif ofi1 $1 ;
ifconfig $1 0.0.0.0 up;

TIP: KVM console has lot of interesting options not shown here, including those for migrating a virtual machine.

No comments: