Ubuntu – How to minimise the size of an ext3 partition (and its LVM logical volume)

ext3filesystemslvmUbuntu

I am using LVM on Ubuntu 9.10 (Karmic). I have a single LVM physical volume (and a single volume group).

I have an ext3 filesystem inside an LVM logical volume which I no longer use, but for the time being I would like not to delete it. I'm trying to figure out how to minimise the space it takes up inside my PV. resize2fs has the -M option which works well at resizing the filesystem to have zero free space, but of course this doesn't affect the logical volume. Most of the recipes on the web for shrinking ext3 inside an LV (e.g. this one), follow this basic pattern to alleviate problems with inaccurate calculations of filesystem boundaries, etc.:

  • Shrink ext3 more than you quite want with resize2fs
  • Shrink the LV to the exact size you want
  • Re-run resize2fs to grow the filesystem slightly to efficiently use the complete LV.

That doesn't fully solve the problem in my case, because I want the LV size to be driven by the filesystem, rather than the other way round.

Is there a command or commands I can run to do this? Alternatively, it is possible for me to do the calculation of the filesystem size to give to lvresize with some degree of confidence?

Best Answer

In theory, yes, you can calculate the exact size of the LV required by the filesystem -- when resize2fs does it's thing, it'll print out how many blocks are in use. Unfortunately, getting it slightly wrong results in a broken filesystem, and wasting 100MB of space in exchange for not boning a filesystem is a tradeoff most people are willing to make.

EDIT: At the risk of giving a monkey a machine gun and hosing your filesystems for all time, the following process worked for me on a scratch filesystem:

  • fsck -f /dev/vg/sizetest
  • resize2fs -M /dev/vg/sizetest
  • Take the number of blocks (and the block size) from the "Resizing the filesystem" line of resize2fs, and calculate the number of kilobytes involved by multiplying the block count by the block size in kB:
    • "Resizing the filesystem on /dev/vg/sizetest to 119325 (4k) blocks" translates to 119325 * 4 => 477300 (important number for the next step)
  • lvresize -L477300k vg/sizetest
  • At this point, if your size isn't right, you are totally and utterly boned -- expanding the filesystem again won't necessarily get you the same blocks back in the same order.
  • fsck -f /dev/vg/sizetest
  • Remount the filesystem, note that df shows that the filesystem is 100% full, with 0 blocks available

If this bones your crucially important filesystem, don't tell me, for I shall merely engage in a lengthy "told you so" dance, and nobody wants to see me dance. Trust me on that.