From: "Neil Aggarwal", Thursday, November 12, 2009 5:34 PM
Is there a command in virsh to shutdown all domains? I can do one at a time, but that is untenable for a large number of domains.
I use a script to shutdown my domains. I am not always happy with stopping the service, which is supposed to have the effect of stopping the virtual machines. I use xm and do other things, including rebooting my MS Windows XP VM's on a schedule, but here's the piece that just does a shutdown on running VM's. I'm sure my script isn't very efficient and I'd appreciate any polite, constructive suggestions. Also, since I've pulled it out of a script and modified it on the fly for virsh, there might be bugs.
The debug environment var is use for verbosity. The fake environment variable is used for 'faking' the run. Setting both while debugging might be a good idea unless you are using a test system without any production virtual machines.
---------- #!/bin/bash # file: /usr/local/sbin/vm-shutdown # Description: shutdown active virtual machines
# Get list of active virtual machines vmList="`virsh list | ( while read vmID vmName vmStatus do if [ -n "$vmName" -a "$vmName" != "Name" -a "$vmName" != "Domain-0" ] then [ -z "$vmList" ] && vmList="$vmName" || vmList="$vmList $vmName" fi done echo $vmList )`"
# check there are some active VM's if [ -n "$vmList" ]; then # Shutdown VM's with verification for vmName in $vmList do # send initial request [ -n "$debug" ] && echo -n "Attempting to shutdown $vmName " [ -z "$fake" ] && virsh shutdown $vmName # wait a limited time for the VM to be not running count=300 while ( virsh list | grep $vmName >/dev/null ) && [ count -gt 0 ] do sleep 1 let count=count-1 [ -n "$debug" ] && echo -n "." done # report current status ( virsh list | grep $vmName >/dev/null ) && echo " failed!" || echo " down." # if still running, destroy it if ( virsh list | grep $vmName >/dev/null ) then [ -n "$debug" ] && echo -n "Attempting to destroy $vmName " [ -z "$fake" ] && virsh destroy $vmName # wait a limited time for the VM to be not running count=60 while ( virsh list | grep $vmName >/dev/null ) && [ count -gt 0 ] do sleep 1 let count=count-1 [ -n "$debug" ] && echo -n "." done # report current status ( virsh list | grep $vmName >/dev/null ) && echo " failed!" || echo " down." fi fi ---------- over engineering and over analysing for 3 decades... or is it over analysing and over engineering...