Sparse qcow2 images can be convenient for allowing you to over-subscribe your disk for your KVM guests in case they might need that space later. For example, you could provision 3 guests each with 400 GB of storage, on a single 500 GB drive. To begin with, the guests will only use a few GB of space each and use more as and when they need it.
Unfortunately, this can also have the opposite effect, causing the sparse image to use more space than was actually allocated to the guest. This is especially noticeable on smaller guests. I noticed that my 20 GB guest was using over 3 times that. The screenshot below shows the storage required of the image before and after I performed the recovery operation I am about to describe.
Log into the guest with SSH.
Fill the remaining space in the guest with 0's before be filling the guest with an empty file before deleting it. This will allow an operation we use later to know that this area is free.
dd if=/dev/zero of=mytempfile rm mytempfile
You should see output similar to below:
dd: writing to ‘mytempfile’: No space left on device 14538105+0 records in 14538104+0 records out 7443509248 bytes (7.4 GB) copied, 23.6383 s, 315 MB/s
Now shutdown the guest.
sudo shutdownNow log into your KVM server and move your file to another location, before converting it back to the original location again.
mv guest-image.qcow2 guest-image.qcow2.bak qemu-img convert -O qcow2 \ guest-image.qcow2.bak \ guest-image.qcow2
Now you can boot your guest back up.
sudo virsh start my.guest.org
When you are all happy with everything and there are no issues, you can delete the original image that you had been using.