Skip to content

Instantly share code, notes, and snippets.

@mbruzek
Last active April 7, 2020 22:15
Show Gist options
  • Save mbruzek/f1b4a79513d1e1295c5c89c7237ce83d to your computer and use it in GitHub Desktop.
Save mbruzek/f1b4a79513d1e1295c5c89c7237ce83d to your computer and use it in GitHub Desktop.
Sparsify a qemu disk with backing file.
#!/bin/bash
# Implement method 1 to compress the VM differencing disks.
LIBVIRT_IMAGES=/var/lib/libvirt/images
TARGET_DOMAIN=${1}
function sparsify {
local TARGET_DISK=${1}
# Print the size of the differencing disk.
ls -al ${LIBVIRT_IMAGES}/${TARGET_DISK}*
# Print out the qemu image information on this target disk.
qemu-img info ${LIBVIRT_IMAGES}/${TARGET_DISK}
# Create a new differencing disk over the current differencing disk.
qemu-img convert -c -f qcow2 -O qcow2 -o backing_file=${LIBVIRT_IMAGES}/${TARGET_DISK}.BASE ${LIBVIRT_IMAGES}/${TARGET_DISK} /tmp/${TARGET_DISK}.sparse1
# Reclaim the freespace in the new disk.
virt-sparsify --in-place /tmp/${TARGET_DISK}.sparse1
# Pull out the non-free blocks from the 2nd disk.
qemu-img convert -c -f qcow2 -O qcow2 -o backing_file=${LIBVIRT_IMAGES}/${TARGET_DISK}.BASE /tmp/${TARGET_DISK}.sparse1 /tmp/${TARGET_DISK}.sparse2
echo "Created disk /tmp/${TARGET_DISK}.sparse2."
# Print out the size of the new differencing disk.
ls -al /tmp/${TARGET_DISK}*
qemu-img info /tmp/${TARGET_DISK}.sparse2
# Remove the first sparse disk.
rm -v /tmp/${TARGET_DISK}.sparse1
}
virsh shutdown ${TARGET_DOMAIN}
sleep 5
# Find the differencing disks for the domain.
pushd ${LIBVIRT_IMAGES}
DISKS=`ls ${TARGET_DOMAIN}*.qcow2`
popd
# Sparsify each disk individually
for DISK in ${DISKS}; do
sparsify ${DISK}
done
# Collect all the results in one file.
tar -cvzf ${TARGET_DOMAIN}.tar.gz /tmp/${TARGET_DOMAIN}*
# Remove temporary files.
rm -v /tmp/${TARGET_DOMAIN}*
# Print the name of the tar file.
echo "Created ${TARGET_DOMAIN}.tar.gz with the sparse files for ${TARGET_DOMAIN}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment