Script de init para VirtualBox

De Wiki Hackstore

CentOS

#!/bin/bash
#
# chkconfig: 2345 85 15
# description: Este init proporciona o gerenciamento seguro das máquinas virtuais VirtualBox. \
# É possível gerenciar máquinas virtuais individuais ou mesmo parar/iniciar/reiniciar todas ao \
# mesmo tempo.
#
# processname: virtual-machines
# pidfile: /var/run/vms.pid

# Source function library.
if [ -f /etc/init.d/functions ] ; then
. /etc/init.d/functions
elif [ -f /etc/rc.d/init.d/functions ] ; then
. /etc/rc.d/init.d/functions
else
exit 1
fi


RETVAL=0


#VBOX_CMD="su vbox -c"
VBOXDIR="/etc/virtualbox"
VM_USER="vbox"
USE_NAT="no"
SU="su $VM_USER -c"
VBOXMANAGE="VBoxManage --nologo"


# Determine if USE_NAT is set to "yes"
use_nat() {
if [ "$USE_NAT" = "yes" ]; then
return `true`
else
return `false`
fi
}

log_failure_msg() {
echo $1
}

log_action_msg() {
echo $1
}



# Check for running machines every few seconds; return when all machines are
# down
wait_for_closing_machines() {
RUNNING_MACHINES=`$SU "${VBOXMANAGE} list runningvms" | wc -l`
if [ $RUNNING_MACHINES != 0 ]; then
sleep 5
wait_for_closing_machines
fi
}



# Gera lista de todas as VMs existentes
${SU} "${VBOXMANAGE} list vms" |cut -d" " -f1|sed s,\",,g > /etc/virtualbox/machines_enabled


# Inicia os casos do init
case "$1" in

##################### inicia Todas as VMs #####################
start)

echo "iniciando todas as vms"

if [ -f /etc/virtualbox/machines_enabled ]; then

 while read VM; do
log_action_msg "Starting VM: $VM ..."
$SU "VBoxHeadless -startvm "${VM}" --vrde config & "
RETVAL=$?
done < /etc/virtualbox/machines_enabled
touch /var/lock/subsys/vboxcontrol
fi

#$SU "$VBOXMANAGE list vms" | cut -d" " -f1|sed s,'\"',,g

;;

################### inicia VMs individuais ###################
start-vm)

echo "iniciando vms individuais"
$SU "VBoxHeadless -startvm "$2" --vrde config & "

;;

################### Desliga VMs individuais ###################
stop-vm)

echo "parando vms individuais"
$SU "${VBOXMANAGE} controlvm "$2" acpipowerbutton"

;;

#################### Desliga Todas as VMs ####################
stop)

echo -e "\nParando VMs de forma segura....\nPor favor AGUARDE...\n"
$SU "$VBOXMANAGE list runningvms" | cut -d" " -f1|sed s,'\"',,g| while read VM; do
log_action_msg "Shutting down VM: $VM ..."
$SU "$VBOXMANAGE controlvm "$VM" acpipowerbutton"
done
rm -f /var/lock/subsys/vboxcontrol
wait_for_closing_machines

;;	

########################### Status ###########################
status)
echo -e "\n## VMs rodando ##\n"
$SU "${VBOXMANAGE} list runningvms" 
echo -e "\n\n"

;;

info)

$SU "${VBOXMANAGE} showvminfo "$2" "
;;
#####################################################################

*)
echo -e "\nSintaxe: $0 { start | start-vm | stop-vm | stop | status | info }\n"
exit 1
;;
esac

exit $RETVAL