Is it possible to re-shrink the .qcow2 image files?

Over the course of many system upgrades, logging, etc. the image files have grown substantially. I have deleted as much of such files as I can to drop their sizes back down to about 5 gigs, but their usage on disk still stands at about twice that amount. I am guessing that they must have “grown” to accommodate the data needed, but is there a way I can shrink them back?

yes. for your whonix images, you can use a tool called zerofree free to work, since the disks are ext4 partitions. it’s a little bit involved. but this is how i’ve gotten the best results:

  1. install the package “zerofree” in the virtual machine you want to shrink.
  2. erase what you need in the vm, run apt-get purge, apt-get autoremove, apt-get clean, etc. as needed.
  3. reboot your virtual machine in recovery mode.
  4. at the command prompt, type “systemctl stop systemd-journald.socket && systemctl stop systemd-journald.service && mount -o remount,ro / && zerofree -v /dev/vda1 && shutdown now”
  5. when the vm shuts down, open a terminal on your host.
  6. switch to root. type “sudo -s”
  7. type “cd /var/lib/libvirt/images”
  8. create a back up of the disk you want to shrink. type “mv YourVirtualMachineDisk.qcow2 YourVirtualMachineDisk.qcow2.backup”
  9. shrink the disk. type “qemu-img convert -o qcow2 -p YourVirtualMachineDisk.qcow2.backup YourVirtualMachineDisk.qcow2”
  10. boot up the vm and see if it is working. if it is, you can delete the backup of the qcow file.

there are ways you can get more creative with this using thin provisioned images that are based on a static qcow2 backing file. that’s the method i prefer. but, the above is a basic method for getting a shrunken qcow2 disk file.

1 Like

Would you like to add this to the Kicksecure wiki?

That’s a real long standing thing asked every now and then that is missing in the wiki.

https://phabricator.whonix.org/T64

Where does this belong on both wikis?

only 1 wiki might be sufficient, new wiki page:

1 Like

Added and credited. Thanks @tempest for sharing.

1 Like

this is actually much simpler now in KVM. zerofree runs and the other commands are no longer required. it basically just requires one to set the “discard” flag on a mount option for the disk in question and then set “discard mode” to “unmap” in virt-manager. for example:

  1. in /etc/fstab, set the following for root:
    “/dev/disk/by-uuid/XXXXXX-blah-blah-YourdiskUUID / auto defaults,errors=remount-ro,discard 0 1”

  2. in the “virt-manager” program, click on the virtual machine in question, open the virtual machine in question, click on the lightbulb icon to get to its settings, click on the storage disk in question and go to the “advanced options.” then, next to “discard mode,” choose “unmap.”

the disk will no longer balloon. unused diskspace will get released naturally, or can be forced with the “sudo fstrim -av” command.

1 Like