Programster's Blog

Tutorials focusing on Linux, programming, and open-source

KVM External Snapshots

With external snapshots, a new file is created where all future changes are written to (the "delta" file), and the original file is stored in a read-only saved state.

Related Posts

Advantages of External over Internal

  • Much faster creation (creating an empty file to store future data and setting up links).
  • Can be performed on both qcow2 and raw disk based guests.
  • Allows for live backups of guests.
    • The disk (and possibly state) of the guest at the point of the snapshot is now in read-only file that can be copied to an external host whilst the guest is still running.

The basic KVM setup in Ubuntu 16.04/18.04 and Debian 9/10 results in not being able to use virsh-snapshot-delete or virsh snapshot-revert on external snapshots. However, you can get work around this manually.

How To Take An External Snapshot

External snapshots are taken in the same manner as internal snapshots, but with the additional --diskspec, --memspec, and --disk-only parameters specifying where to save the disk and state files, or whether we are only saving the disk. You cannot specify --diskspec alone without one of the other two parameters which should be used depending on whether the VM is running or not.

Below is a script I use to automatically determine whether a VM is running or not in order to take the appropriate type of snapshot. It also automatically creates a folder structure whereby snapshots are stored in a snapshots folder which has subfolders of the timestamps of when the snapshots were taken. Feel free to use/adapt it to your needs.

#!/bin/bash
DOMAIN="test"
TIMESTAMP=`date +%s`
SNAPSHOT_NAME=$TIMESTAMP

VM_FOLDER="/path/to/vms"
SNAPSHOT_FOLDER="`echo $VM_FOLDER`/`echo $DOMAIN`/snapshots/`echo $TIMESTAMP`"
mkdir -p $SNAPSHOT_FOLDER

MEM_FILE="`echo $SNAPSHOT_FOLDER`/mem.qcow2"
DISK_FILE="`echo $SNAPSHOT_FOLDER`/disk.qcow2"

# Find out if running or not
STATE=`virsh dominfo $DOMAIN | grep "State" | cut -d " " -f 11`

if [ "$STATE" = "running" ]; then

  virsh snapshot-create-as \
    --domain $DOMAIN $SNAPSHOT_NAME \
    --diskspec vda,file=$DISK_FILE,snapshot=external \
    --memspec file=$MEM_FILE,snapshot=external \
    --atomic

else

  virsh snapshot-create-as \
    --domain $DOMAIN $SNAPSHOT_NAME \
    --diskspec vda,file=$DISK_FILE,snapshot=external \
    --disk-only \
    --atomic

fi

Taking It Further

Now you have learnt about external snapshots, why not use this new power to create thinly provisioned guests.

References

Last updated: 24th September 2022
First published: 16th August 2018