Sunday, June 19, 2011

An introduction to Logical Volume Management (LVM)


harddisk
Logical Volume Management (LVM) is a method of allocating space on mass storage devices that is more flexible than conventional partitioning schemes. To understand how LVM works we will first take a look at some terminology:
  • PV: Physical Volume. This can be an entire harddisk, a partition on a harddisk, a RAID device (software or hardware), a LUN, etc.
  • VG: Volume Group. This is an aggregation of one or more PVs, summing small storage spaces into a bigger consolidated one.
  • LV: Logical Volume. This is a part of a VG that can be used to put a filesystem on.
As an example of how these terms work together, have a look at the following picture:
lvm
Breaking things up into these parts means that we can do fun stuff with LVM. First of all, we can have a filesystem that is bigger than the biggest harddisk we have in the system. We can also grow and shrink the space that is given to a filesystem and even do this while the filesystem is being used. Finally, we can create snapshots, read-only ones for backup purposes and read-write ones that allow us to have multiple versions of a filesystem.
Creating
We start by creating the physical volumes (PVs). If you are using a full harddisk as a physical volume it is best to create 1 partition on it that fills the whole disk. The type of the partition can best be set to “8E”, which is the type for “Linux LVM”. You can do this by running fdisk (“n” for new partition, “t” to change the type and “w” to write changes). Afterwards run partprobe to detect the new partitions:
fdisk /dev/sdb
partprobe
Create the physical volume on the partitions. Let’s assume we have three volumes: /dev/sdb1, /dev/sdb2 and /dev/sdb3:
pvcreate /dev/sdb{1,2,3}
pvdisplay /dev/sdb{1,2,3}
Create the volume group “vg0″ that will group these physical volumes together:
vgcreate /dev/vg0 /dev/sdb{1,2,3}
vgdisplay /dev/vg0
Create a logical volume named “lv0″ from the volume group “vg0″ with a size of 100MiB:
lvcreate -L 100M -n lv0 /dev/vg0
lvdisplay /dev/vg0/lv0
Create a filesystem on top of the logical volume “lv0″ and mount it:
mke2fs -j /dev/vg0/lv0
mount /dev/vg0/lv0 /mnt
Growing
We will now grow the filesystem. This can be done when the filesystem is offline, but ext3 also supports online growing. We start by growing the space that is available to the filesystem in the logical volume “lv0″:
lvextend -L 120M /dev/vg0/lv0
Now we can ask the filesystem to occupy the extra space it has been given:
resize2fs /dev/vg0/lv0
Shrinking
Shrinking a filesystem is a bit more difficult. First we need to unmount the filesystem:
umount /mnt
Run a filesystem check and resize it:
e2fsck -f /dev/vg0/lv0
resize2fs /dev/vg0/lv0 80M
Mount the filesystem again:
mount /dev/vg0/lv0 /mnt
At this time, the filesystem is smaller than its logical volume, so we can shrink it:
lvreduce -L 80M /dev/vg0/lv0