i have played with a couple scripts in order to keep the virtual hd images in both virtualbox and kvm from ballooning out of control. the virtualbox script was included in the last short-lived version of the guide i work on. the kvm script is still experimental. i’m posting both here if anyone would like to review or tweak. basically, they search a directory for hd images that have been modified in the past hour, and apply routines to reduce the size. both rely on “zerofree” in some respects. however, the kvm script also has an option to use the qemu compression option. both scripts have resulted in the freeing of gigabytes of hard drive space on the host when used. feedback welcomed.
vbox script
this script requires a user to boot into recovery mode, mount the hd as readonly, and run zerofree on it first.
from a terminal, type
echo "alias vbcompact='find ~/VirtualBox\ VMs/ \ -type f -mtime -1 -size +10M -name *.vdi \ -exec vboxmanage modifymedium --compact {} t {} \;'" >> ~/.bashrc
typing “vbcompact” later will search through the default virtualbox directory and attempt to compact any “vdi” file modified in the past hour.
kvm script
this script will also see advantages from booting into recovery mode, mounting the hds readonly, and running zerofree. however, qemu compression may negate that, but may take longer. i ran into a couple issues with snapshots not working here and there after this process, which i’m exploring.
this one is a little more involved. it’s to be appended to a user’s .bashrc file.
function vmshrink() { list=$(sudo find /var/lib/libvirt/images/ -type f -mtime -1 -size +10M -name *.qcow2)
for f in $list
do
# ask if user wants to shrink image
read -e -p "Shrink $f? [y/N] " choice
if [[ "$choice" == [Yy]* ]]
then
#"yes" choice. show file size and move original to a back up file.
ls -lh $f
sudo mv $f $f.backup
# ask if user wants to use qemu compression
read -e -p "Do you want to enable disk compression on $f? [y/N] " choice2
if [[ "$choice2" == [Yy]* ]]
then
#"yes" choice. apply qemu compression.
sudo qemu-img convert -O qcow2 -p -c $f.backup $f
else
#"no" choice. convert to remove space changed by zerofree only.
sudo qemu-img convert -O qcow2 -p $f.backup $f
fi
ls -lh $f
# ask if user wants to delete the back up copy.
read -e -p "Please run the vm to confirm it still works. If it works, you can remove the back up. Remove $f.backup? [y/N] " choice3
if [[ "$choice3" == [Yy]* ]]
then
#"yes" choice. delete backup
sudo rm $f.backup
elif [[ "$choice3" != [Yy]* ]]
then
#"no" choice. ask if user wants to restore backup.
read -e -p "Restore backup? [y/N] " choice4
if [[ "$choice4" == [Yy]* ]]
then
#restore backup
sudo mv $f.backup $f
fi
fi
fi
done }
the goal of both scripts was to make the process of shrinking hd images after a dist-upgrade a little simpler, rather than having to type the individual commands for each individual file.