Created
September 4, 2018 12:42
-
-
Save mikehardy/e2ca84df357dfea5f642525aa1c61a9f to your computer and use it in GitHub Desktop.
A script to manage suspend/resume/stop for all libvirt guests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# | |
# Inspired by https://github.com/kumina/shutdown-kvm-guests/blob/master/shutdown-kvm-guests.sh | |
# | |
# Configure timeout (in seconds). | |
TIMEOUT=300 | |
VIRSH=/usr/bin/virsh | |
# List running domains. | |
list_domains_by_state() { | |
$VIRSH list | grep $1 | awk '{ print $2}' | |
} | |
case "$1" in | |
start,reload,restart,force-reload) | |
;; | |
suspend) | |
echo "Trying to suspend all running KVM domains..." | |
list_domains_by_state running | while read DOMAIN; do | |
$VIRSH suspend $DOMAIN | |
done | |
echo "...done suspending KVM domains." | |
;; | |
resume) | |
echo "Trying to resume all suspended KVM domains..." | |
list_domains_by_state paused | while read DOMAIN; do | |
$VIRSH resume $DOMAIN | |
done | |
echo "...done resuming KVM domains." | |
;; | |
stop) | |
echo "Try to cleanly shut down all running KVM domains..." | |
# Create some sort of semaphore. | |
touch /tmp/shutdown-kvm-guests | |
# Try to shutdown each domain, one by one. | |
list_domains_by_state running | while read DOMAIN; do | |
# Try to shutdown given domain. | |
$VIRSH shutdown $DOMAIN | |
done | |
# Wait until all domains are shut down or timeout has reached. | |
END_TIME=$(date -d "$TIMEOUT seconds" +%s) | |
while [ $(date +%s) -lt $END_TIME ]; do | |
# Break while loop when no domains are left. | |
test -z "$(list_running_domains)" && break | |
# Wait a litte, we don't want to DoS libvirt. | |
sleep 1 | |
done | |
# Clean up left over domains, one by one. | |
list_domains_by_state running | while read DOMAIN; do | |
# Try to shutdown given domain. | |
$VIRSH destroy $DOMAIN | |
# Give libvirt some time for killing off the domain. | |
sleep 3 | |
done | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment