#!/sbin/runscript description="Virtual Machine Management (libvirt) Guests" depend() { need libvirtd } do_virsh() { local hvuri=$1 shift # if unset, default to qemu [ -z ${hvuri} ] && hvuri="qemu:///system" # if only qemu was supplied then correct the value [ "xqemu" = x${hvuri} ] && hvuri="qemu:///system" # Silence errors because virsh always throws an error about # not finding the hypervisor version when connecting to libvirtd LC_ALL=C virsh -c ${hvuri} "$@" 2>/dev/null } libvirtd_dom_list() { # Make sure that it wouldn't be confused if the domain name # contains the word running. do_virsh $1 list | awk '$3 == "running" { print $1 }' } libvirtd_dom_count() { # Make sure that it wouldn't be confused if the domain name # contains the word running. do_virsh $1 list | awk 'BEGIN { count = 0 } \ $3 == "running" { count++ } \ END { print count }' } libvirtd_net_list() { # The purpose of the awk is to avoid networks with 'active' in the name do_virsh $1 net-list | awk '$2 == "active" { print $1 }' } libvirtd_net_count() { # The purpose of the awk is to avoid networks with 'active' in the name do_virsh $1 net-list | awk 'BEGIN { count = 0 } \ $2 == "active" { count++ } \ END { print count }' } start() { ebegin "Starting libvirt guests" for uri in ${LIBVIRT_URIS}; do do_virsh "${uri}" connect if [ $? -ne 0 ]; then eerror "Failed to connect to '${uri}'. Will " eend 1 exit 1 fi } stop() { local counter= local vm_name= local net_name= local dom_id= ebegin "Stopping libvirt guests" # try to shutdown all (KVM/Qemu) domains if [ "${LIBVIRTD_KVM_SHUTDOWN}" != "none" ] \ && [ "$(libvirtd_dom_count qemu)" != "0" ] ; then einfo " Shutting down domain(s):" for dom_id in $(libvirtd_dom_list qemu) ; do vm_name="$(do_virsh qemu domname ${dom_id} | head -n 1)" einfo " ${vm_name}" do_virsh qemu ${LIBVIRTD_KVM_SHUTDOWN} ${dom_id} > /dev/null done if [ -n "${LIBVIRTD_KVM_SHUTDOWN_MAXWAIT}" ] ; then counter="${LIBVIRTD_KVM_SHUTDOWN_MAXWAIT}" else counter=500 fi if [ "${LIBVIRTD_KVM_SHUTDOWN}" = "shutdown" ]; then einfo " Waiting ${counter} seconds while domains shutdown ..." DOM_COUNT="$(libvirtd_dom_count qemu)" while [ ${DOM_COUNT} -gt 0 ] && [ ${counter} -gt 0 ] ; do DOM_COUNT="$(libvirtd_dom_count qemu)" sleep 1 counter=$((${counter} - 1)) echo -n "." done fi if [ "$(libvirtd_dom_count qemu)" != "0" ] ; then eerror " !!! Some guests are still running, stopping anyway" fi fi if [ "${LIBVIRTD_KVM_NET_SHUTDOWN}" != "no" ] \ && [ "$(libvirtd_net_count qemu)" != "0" ]; then einfo " Shutting down network(s):" for net_name in $(libvirtd_net_list qemu); do einfo " ${net_name}" do_virsh qemu net-destroy ${net_name} > /dev/null done if [ "$(libvirtd_net_count qemu)" != "0" ]; then eerror " !!! Some networks are still active, stopping anyway" fi fi }