KVM External Snapshots (and Backups) Part 1 – using virsh blockcommit

Today we will look at using external KVM snapshots to create backup images of guest VMs. While external snapshot support in KVM is not as mature compared to internal ones, it is faster to execute while the VM is running and more flexible in terms of generated snapshot files. Here in Part 1 we will be using virsh blockcommit command which allows us to keep the original base image after flattening.

In this example, I am using a VM guest (or virsh domain) with name centos7.0. First, let’s check what disk is being used:

virsh domblklist centos7.0

Look for the entry under “Target”. In my case this is sdb. Take note of the “Source” entry as well, which for now is the original base image /mnt/vm/QEMU/centos.qcow2. Now let’s proceed and create an external snapshot and generate a new active image called overlay.qcow2:

virsh snapshot-create-as –domain centos7.0 centos-state01 –diskspec sdb,file=/mnt/vm_snapshots/centos7.0/overlay.qcow2 –disk-only –atomic

This snapshot execution will take no time at all. You cannot generate it this quickly with internal snaphots. You can also place the overlay file wherever you want – you are not stuck with the original qcow2 image.

Now check the image currently in use, the “Source” entry should now be switched to /mnt/vm_snapshots/centos7.0/overlay.qcow2:

virsh domblklist centos7.0

From here you can safely backup the original base image, copy/rsync to your backup directory:

cp /mnt/vm/QEMU/centos.qcow2 /mnt/backup/centos7.0-20190916.qcow2

Now that we have our backup, lets combine/flatten the snapshot back to the base image using the magic of virsh blockcommit:

virsh blockcommit centos7.0 sdb –active –verbose –pivot

Let’s check the current image in use, should have reverted back to the original base image:

virsh domblklist centos7.0

The “Source” should now be back to /mnt/vm/QEMU/centos.qcow2.

The next step is to delete the snapshot. Because of incomplete support for KVM external snapshots, you cannot just do a virsh snapshot-delete; that only works for internal snapshots.

First let’s delete the XML metadata of the snapshot using the –metadata option:

virsh snapshot-delete centos7.0 –metadata –current

Now we can physically delete the overlay file we created:

rm /mnt/vm_snapshots/centos7.0/overlay.qcow2

There you have it, we have (1) created an external snapshot, (2) backed up our image file, (3) flattened the overlay back to the base image, and (4) cleaned up the overlay file and snapshot metadata. All this without any downtime/pausing of the VM. Maybe we can create a bash script to automate this later on.

Further reading: Red Hat Documentation

Leave a comment

Your email address will not be published.