#!/bin/bash if [ "$(id -u)" -ne 0 ]; then echo "This script must be run as root." >&2 exit 1 fi # ------ Settings Qcow2Dir=/localdisk/backup/qcow2 ShrunkDir=/opt/vm_drive/shrunk TmpDir=/localdisk/tmp mkdir -p ${ShrunkDir} mkdir -p ${TmpDir} # ------ Settings Qcow2Files=$(find ${Qcow2Dir} -type f -name "*.qcow2" -mtime -1 -print) echo "Files to compress:" echo ${Qcow2Files} exit for file in ${Qcow2Files} do echo "Compressing file ${file}..." SparseFile="${ShrunkDir}/$(basename ${file}).sparse" ShrunkFile="${ShrunkDir}/$(basename ${file}).shrunk" if [ -f ${ShrunkFile} ] then echo Shrunk file ${ShrunkFile} exists. Skipping... continue fi Cmd="/usr/bin/virt-sparsify" Cmd="${Cmd} --check-tmpdir=continue" Cmd="${Cmd} --tmp=${TmpDir}" Cmd="${Cmd} -q" Cmd="${Cmd} ${file} ${SparseFile}" Cmd="${Cmd} && /usr/bin/qemu-img convert" Cmd="${Cmd} -c" Cmd="${Cmd} -O qcow2" Cmd="${Cmd} ${SparseFile} ${ShrunkFile}" echo ${Cmd} eval ${Cmd} if [ ${?} -ne 0 ] then echo "Compression failed. Removing ${ShrunkFile}" rm ${ShrunkFile} else filesz=$(stat -c %s ${file}) cfilesz=$(stat -c %s ${ShrunkFile}) ratio=$((cfilesz * 100 / filesz)) echo "Compression is successful. Compression ratio is ${ratio}%" rm ${SparseFile} ## GuestFile="${ShrunkFile#*.}" GuestFile="${GuestFile%.shrunk}" Cmd="ln -snf ${ShrunkFile} /opt/vm_drive/${GuestFile}" echo ${Cmd} eval ${Cmd} ## Cmd="chown oleg:oleg ${ShrunkFile}" echo ${Cmd} eval ${Cmd} fi done echo "Done $0 $*"