TIMEOUT=300 LOGFILE=/var/log/libvirt/libvirt-bin.log VIRSH="/usr/bin/virsh -c qemu:///system" list_active_vms () { ACTIVE_VMs="" for VM_NAME in $($VIRSH list --all | awk 'NR > 2 {print $2}'); do if [ "$($VIRSH domstate $VM_NAME)" != "shut off" ]; then if [ "$ACTIVE_VMs" = "" ] ; then ACTIVE_VMs=$VM_NAME else ACTIVE_VMs="$ACTIVE_VMs $VM_NAME" fi fi done echo $ACTIVE_VMs } # depends on constant system time (small NTP changes should be okay) TIMEOUT_END=$($DATE -d "$TIMEOUT seconds" +%s) echo "[$(date +%H:%M:%S)] libvirt-bin: shutdown all guests " >> $LOGFILE 2>&1 # send shutdown to all VMs with status other than "shut off" # guests must handle acpi-power-button! for VM_NAME in $(list_active_vms); do $VIRSH shutdown $VM_NAME >> $LOGFILE 2>&1 done # wait until timeout has reached or no running are vms left while [ $($DATE +%s) -lt $TIMEOUT_END ] do if [ -z "$(list_active_vms)" ]; then break fi # slow down the loop sleep 0.5 done # if any vms left not shutdowned destroy them now if [ -n "$(list_active_vms)" ]; then for VM_NAME in $(list_active_vms); do $VIRSH destroy $VM_NAME >> $LOGFILE 2>&1 done # give processing of destroy signal some time sleep 3 fi