| by Arround The Web | No comments

Automatically shrink your VM disk images when you delete files (Fedora 32 update)

I’ve already written about this in 2017, but things got simpler since then. Time for an update!

If you use virtual machines, your disk images just grow and grow, but never shrink – deleted files inside a VM never free up the space on the host. But you can configure the VM to handle TRIM (discard) commands, and then your disk images will reflect deleted files and shrink as well. Here’s how (with Fedora 32 using qemu 4.2 and virt-manager 2.2).

Adjust VM configuration

  1. When creating a new VM, use qcow2 disk images (that’s the default), not raw.
  2. Your new VM should have VirtIO disks (that’s the default).
  3. In virt-manager in VM configuration, select your VirtIO disk, go to Advanced -> Performance, and set Discard mode: unmap.
    virt-manager-unmap

Test it

Now boot your VM and try to issue a TRIM command:

$ sudo fstrim -av
/boot: 908.5 MiB (952631296 bytes) trimmed on /dev/vda1
/: 6.8 GiB (7240171520 bytes) trimmed on /dev/mapper/fedora-root

You should see some output printed, even if it’s just 0 bytes trimmed, not an error.

Let’s see if the disk image actually shrinks. You need to list its size using du (or ls -s) to see the disk allocated size, not the apparent file size (because the disk image is sparse):

$ du -h discardtest.qcow2 
1.4G discardtest.qcow2

Now create a file inside the VM:

$ dd if=/dev/urandom of=file bs=1M count=500

We created a 500 MB file inside the VM and the disk image grew accordingly (give it a few seconds):

$ du -h discardtest.qcow2
1.9G discardtest.qcow2

Now, remove the file inside the VM and issue a TRIM:

$ rm file -f
$ sudo fstrim -av

And the disk image size should shrink back (give it a few seconds):

$ du -h discardtest.qcow2
1.4G discardtest.qcow2

If you configure your system to send TRIM in real-time (see below), it should shrink right after rm and no fstrim should be needed.

Issue TRIM automatically

With Fedora 32, fstrim.timer is automatically enabled and will trim your system once per week. You can reconfigure it to run more frequently, if you want. You can check the timer using:

$ sudo systemctl list-timers

If you want a real-time TRIM, edit /etc/fstab in the VM and add a discard mount option to the filesystem in question, like this:

UUID=6d368798-f4c2-44f9-8334-6be3c64cc449 / ext4 defaults,discard 1 1

This has some performance impact (they say), but the disk image will shrink right after a file is deleted. (Note: XFS as a root filesystem doesn’t issue TRIM commands without additional tweaking, read more here).

Share Button

Source: Kparal's Fedora Blog

Leave a Reply