Good times with LVM snapshots
There’s a lot of good documentation out there already, but I’m going to go ahead and post this so that in 6 months or a year when I’ve forgotten it again, hopefully I’ll stumble upon my own explanation.
I was having some discussions with some people at work about more efficient database restores with mysql and at one point the discussion turned to LVM snapshots for mysql backups. I’ve used LVM for a long time but have never really used the snapshot volumes. (Now that I think of it, however, that’s something of a lie. I’ve used it to expedite building vm’s under Xen… but I digress.)
I had this conception in my head that an LVM snapshot == an LVM backup. It doesn’t. This may be a simple concept, but from all the documentation out there such as this great howtoforge writeup or the tldp documentation, one point seemed to be missing, at least for my simple brain: An LVM snapshot is NOT a backup. An LVM snapshot allows you to create a consistent backup.
So what is an LVM snapshot volume, you ask? An LVM snapshot works by creating another logical volume in the context of one that already exists. Subsequently, an exception log of i/o on the original volume is kept in the snapshot volume. This exception log is used in the context of the original logical volume to allow it to be read in a consistent state at any point in time during the life of the snapshot.
Say, for example, I have a Xen domU whose disk is on a logical volume /dev/xen/ops1test-disk. An LVM snapshot volume could be created like so:
$ sudo lvcreate --snapshot --size 1G --name test_snapshot /dev/xen/ops1test-disk
This creates a logical volume called test_snapshot (which will be in /dev/xen/test_snapshot in my case) with room for 1GB of changes to the original ops1test-disk volume. Depending on how much i/o the original volume is undergoing, this number can obviously be changed.
Now your snapshot can be mounted like normal while the original volume continues on its merry way.
$ sudo mount /dev/xen/test_snapshot /mnt
Once the snapshot volume is mounted, it will be read in a consistent state from the point in time that it is mounted. Any changes that have happened since the time of snapshot creation will be read from the exception log and any continuing changes will be noted in the exception log but won’t affect the consistent state that you’re currently reading from.
So now you can do the backup via normal means (whatever that may be). It could be done using backup software, dd, or tar, for example:
$ tar -pcvf ./test_snapshot_backup.tar.gz /mnt/test_snapshot
Once the backup is complete (or whatever else you’re doing with the snapshot), the snapshot should be removed to avoid consumption of resources. Remember that the exception log will continue until the snapshot volume is at capacity. Remove the snapshot like so:
$sudo lvremove /dev/xen/test_snapshot
Voila. Your backup is complete and consistent.