Linux menu

Tuesday, September 23, 2014

How to Rollback a LVM Volume to its Snapshot In Linux

The native Logical Volume Manager (LVM) on Linux also provides a very easy way of rolling back a logical volume to its previously taken snapshot. This gives us flexibility of returning to a good state of the disk (volume) in case if some configuration or similar things goes wrong (but not like complete filesystem crash). For an example you want to test a new software or package, you can take a snapshot of the volume before installing the package, then test your package, in case if you are not happy with the results, rollback to the snapshot. Here is how we can rollback:
First you need to check if your kernel supports snapshot merge feature, for which you need to run dmsetup targets command and look for snapshot-merge in the ouptut:
[root@switchroot ~]# dmsetup targets
snapshot-merge   v1.1.0
snapshot-origin  v1.7.1
snapshot         v1.10.0
mirror           v1.12.0
striped          v1.4.1
linear           v1.1.0
error            v1.0.1
To take a snapshot of a LVM volume:
[root@switchroot ~]# lvcreate -s -n <snapshot name> -L <size of snapshot> <lvm volume for which to take snapshot > 
NOTE: snapshot size can vary depending on your requirement but a minimum recommended size is 30% of the logical volume for which you are taking the snapshot but if you think that you might end up changing all the data in logical volume then make the snapshot size same as logical volume

For Example: To create a 50 MB snapshot of a logical volume "/dev/vg0/lv0" :
[root@switchroot ~]# lvcreate -s -n snap0 -L 50M /dev/vg0/lv0 
Now you do all the changes you want to do on your logical volume and when you want to safely rollback, umount the logical volume (and the snapshot as well, if you had it mounted) and run the following commands:
[root@switchroot ~]# umount  <logical volume path>
[root@switchroot ~]# lvconvert --merge <snapshot path>
If the above lvconvertcommand gives some warning as "Can't merge over open origin volume" then you also need to deactivate and activate the logical volume with following command:
[root@switchroot ~]# lvchange -an <logical volume path>
[root@switchroot ~]# lvchange -ay <logical volume path>
For example: To revert back to snap0 snapshot, which I took above for/dev/vg0/lv0 :
[root@switchroot ~]# umount  /dev/vg0/lv0
[root@switchroot ~]# lvconvert --merge /dev/vg0/snap0
Thats it. Now mount your logical volume back and you will realize that this volume has been roll backed and the snapshot volume has been deleted too .

No comments: