lmn-client/roles/lmn_vm/files/upload-vm.sh
2023-07-13 15:44:17 +02:00

59 lines
2.4 KiB
Bash
Executable file

#!/usr/bin/bash
# Push VM-Disk-Image on server
set -eu
show_help() {
cat << EOF >&2
Usage: $(basename "$0") vmname"
Create torrent and upload disk, torrent and xml-VM-Definiton on server.
EOF
}
VM_DIR="/tmp/${SUDO_UID}/vmimages"
upload_image() {
# check if VM-Diskimage exists
if [[ ! (-f "/var/lib/libvirt/images/${VM_NAME}.qcow2" || -f "${VM_DIR}/${VM_NAME}.qcow2") ]]; then
echo "File not found ${VM_NAME}.qcow2" >&2
exit 1
fi
# link private VM-Diskimage to system-Dir
if [[ -f "${VM_DIR}/${VM_NAME}.qcow2" \
&& ( -f "/var/lib/libvirt/images/${VM_NAME}.qcow2" && ("${VM_DIR}/${VM_NAME}.qcow2" -nt "/var/lib/libvirt/images/${VM_NAME}.qcow2") \
|| ! -f "/var/lib/libvirt/images/${VM_NAME}.qcow2") ]]; then
echo "copy private VM-Diskimage to system-dir"
ln -f "${VM_DIR}/${VM_NAME}.qcow2" "/var/lib/libvirt/images/${VM_NAME}.qcow2"
fi
# check if VM-Machine-Definition XML exists
if [[ ! (-f "/var/lib/libvirt/images/xml/${VM_NAME}.xml" || -f "${VM_DIR}/xml/${VM_NAME}.xml") ]]; then
echo "File not found ${VM_NAME}.xml" >&2
exit 1
fi
# copy private VM-Maschine-Definition XML to system-Dir
if [[ -f "${VM_DIR}/xml/${VM_NAME}.xml" \
&& ( -f "/var/lib/libvirt/images/xml/${VM_NAME}.xml" && $(cmp -s "${VM_DIR}/xml/${VM_NAME}.xml" "/var/lib/libvirt/images/xml/${VM_NAME}.xml") \
|| ! -f "/var/lib/libvirt/images/xml/${VM_NAME}.xml") ]]; then
echo "copy private VM-Maschine-Definition XML to system-dir"
cp "${VM_DIR}/xml/${VM_NAME}.xml" "/var/lib/libvirt/images/xml/"
fi
cd /var/lib/libvirt/images
# (re-) create torrent file
/usr/local/bin/vmimage-torrent create "${VM_NAME}.qcow2"
# Upload Torrent, qcow2 and machine-definition-XML
[[ -f "/var/lib/libvirt/images/${VM_NAME}.qcow2.torrent" ]] && rsync -av --password-file=/etc/rsync.secret \
"/var/lib/libvirt/images/${VM_NAME}.qcow2.torrent" rsync://vmuser@server:/vmimages-upload/
rsync -av --password-file=/etc/rsync.secret "/var/lib/libvirt/images/${VM_NAME}.qcow2" \
rsync://vmuser@server:/vmimages-upload/
rsync -av --password-file=/etc/rsync.secret "/var/lib/libvirt/images/xml/${VM_NAME}.xml" \
rsync://vmuser@server:/vmimages-upload/xml/
}
# if less than one arguments supplied, display usage
if [[ $# -ne 1 ]] ; then
show_help
exit 1
fi
VM_NAME=$1
upload_image