qcow2_utils/compress_qcow2.sh
2025-06-26 12:28:07 -04:00

69 lines
1.6 KiB
Bash
Executable File

#!/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=$(ls -t ${Qcow2Dir}/*.qcow2)
echo "Files to compress: ${Qcow2Files}"
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}
Cmd="chown oleg:oleg ${ShrunkFile}"
echo ${Cmd}
eval ${Cmd}
##
GuestFile="${ShrunkFile#*.}"
GuestFile="${GuestFile%.shrunk}"
Cmd="ln -snf ${ShrunkFile} /opt/vm_drive/${GuestFile}"
echo ${Cmd}
eval ${Cmd}
fi
done
echo "Done $0 $*"