h1

Crear servicio para VirtualBox

09/01/2009

Para ejecutar máquinas virtuales de VirtualBox, la alternativa libre a Vmware desde el inicio del sistema y como servicios es necesario crear un script para el demonio.

Se puede crear una copia del /etc/init.d/skeleton, pero es más rápido utilizar la siguiente plantilla ya predefinida para VirtualBox. Para ello crearemos el script del servicio:

$ sudo nano /etc/init.d/virtualbox-Monowall

y se introduciría el siguiente contenido que posteriormente hay que adaptarlo a la máquina propia (en el ejemplo se ejecuta una máquina Monowall):

#! /bin/sh
### BEGIN INIT INFO
# Provides: virtualbox-Monowall
# Required-Start: $local_fs $remote_fs vboxdrv vboxnet
# Required-Stop: $local_fs $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: S 0 1 6
# Short-Description: Monowall virtual machine
# Description: Monowall virtual machine hosted by VirtualBox
### END INIT INFO

# Author: Brendan Kidwell
#
# Based on /etc/init.d/skeleton from Ubuntu 8.04.

# Do NOT "set -e"

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/usr/sbin:/usr/bin:/sbin:/bin
DESC="Monowall virtual machine"
NAME=virtualbox-Monowall
SCRIPTNAME=/etc/init.d/$NAME

MANAGE_CMD=VBoxManage
VM_OWNER=carlos
VM_NAME="Monowall" #This has to be the name exactly as it appears in your VirtualBox GUI control panel.

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
# Return
# 0 if daemon has been started
# 1 if daemon was already running
# 2 if daemon could not be started

sudo -H -u $VM_OWNER $MANAGE_CMD showvminfo "$VM_NAME"|grep "^State:\s*running" >/dev/null && {
echo "$VM_NAME" is already running.
return 1
}

sudo -H -u $VM_OWNER $MANAGE_CMD startvm "$VM_NAME" --type vrdp >/dev/null || >/dev/null || {
echo Failed to start "$VM_NAME".
return 2
}

echo "$VM_NAME" started or resumed.
return 0
}

#
# Function that stops the daemon/service
#
do_stop()
{
# Return
# 0 if daemon has been stopped
# 1 if daemon was already stopped
# 2 if daemon could not be stopped
# other if a failure occurred

sudo -H -u $VM_OWNER $MANAGE_CMD showvminfo "$VM_NAME"|grep "^State:\s*running" >/dev/null || {
echo "$VM_NAME" is already stopped.
return 1
}

sudo -H -u $VM_OWNER $MANAGE_CMD controlvm "$VM_NAME" savestate || {
echo Failed to stop "$VM_NAME".
return 2
}

echo "$VM_NAME" suspended.
return 0
}

#
# Display "State" field from showinfo action
#
do_status()
{
sudo -H -u $VM_OWNER $MANAGE_CMD showvminfo "$VM_NAME"|grep "^State:\s*.*$"
}

case "$1" in
start)
[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
do_start
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
stop)
[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
do_stop
case "$?" in
0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
esac
;;
restart|force-reload)
#
# If the "reload" option is implemented then remove the
# 'force-reload' alias
#
log_daemon_msg "Restarting $DESC" "$NAME"
do_stop
case "$?" in
0|1)
do_start
case "$?" in
0) log_end_msg 0 ;;
1) log_end_msg 1 ;; # Old process is still running
*) log_end_msg 1 ;; # Failed to start
esac
;;
*)
# Failed to stop
log_end_msg 1
;;
esac
;;
status)
do_status
;;
*)
#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload|status}" >&2
exit 3
;;
esac

:

Resumidamente, hay que incluir el nombre de la máquina tal y como está definida en VirtualBox, el usuario que la ejecuta (y que mantiene por tanto sus ficheros de configuración en $HOME/.VirtualBox y el nombre del propio script).

Dar permisos al script:
$ sudo chmod 755 /etc/init.d/virtualbox-Monowall

Y probar a arrancarlo:
$ sudo /etc/init.d/virtualbox-Monowall start

Comprobar su estado:
$ sudo /etc/init.d/virtualbox-Monowall status

Pararlo:
$ sudo /etc/inid.d/virtualbox-Monowall stop

Por último hay que dar de alta ese script en los correspondientes runlevels:

$ sudo update-rc.d virtualbox-Monowall defaults

Fuente Glump.net (en Inglés)

13 comentarios

  1. […] Linux y software libre Experiencias y desarrollo de proyectos con software libre « Crear servicio para VirtualBox Monitorizar máquinas virtuales VirtualBox con Monit Enero 9, 2009 Utilizando Monit se […]


  2. Estimado:
    Existe un problema en el script, este no permite conectarse a la VM po VRDP, es en la linea 54

    dice

    sudo -H -u $VM_OWNER $MANAGE_CMD startvm «$VM_NAME» -type vrdp >/dev/null || {

    debiera decir

    sudo -H -u $VM_OWNER $MANAGE_CMD startvm «$VM_NAME» –type vrdp >/dev/null || >/dev/null || {

    Saludos y grasias por el aporte


  3. Cierto, ya lo he corregido, gracias por la nota.


  4. Fantástico el script, gracias por ponerlo a nuestra disposición, me funciona sin problemas


  5. Pues a mi no me va. Tengo Ubuntu 10.04 y ni el virtualtools ni este me funciona.

    He ido a la página de glump http://www.glump.net/howto/virtualbox_as_a_service#install_the_initd_script y he corregido el comentario anterior de

    sudo -H -u $VM_OWNER $MANAGE_CMD startvm “$VM_NAME” –type vrdp >/dev/null || >/dev/null || {

    y me da el siguente error

    sudo /etc/init.d/virtualbox-XP-PRO-Litel status
    : not found/virtualbox-XP-PRO-Litel: 1:
    : not found/virtualbox-XP-PRO-Litel: 12:
    : not found/virtualbox-XP-PRO-Litel: 19:
    : not found/virtualbox-XP-PRO-Litel: 21:
    : not found/virtualbox-XP-PRO-Litel: 34:
    .: 36: Can’t open /etc/default/rcS

    ¿alguna idea?


  6. así sin más información parece algo de permisos o de alguna ruta en los parámetros mal puesta.


  7. Efectivamente, el usuario estaba mal puesto… una mayúscula.


  8. Usando Virtualbox 4.0

    replace «vrdp» by «headless»

    sudo -H -u $VM_OWNER $MANAGE_CMD startvm «$VM_NAME» -type vrdp >/dev/null || {

    now:
    sudo -H -u $VM_OWNER $MANAGE_CMD startvm «$VM_NAME» -type headless >/dev/null || {


  9. […] Entrada sacade de gacimartin.com . […]


  10. […] Crear servicio para VirtualBox […]


  11. Este script fue probado en ubuntu 12.04 con la vrsion de virtualbox 4.2? tengo esa duda pues no me funciona


    • No, pero comenta directamente el error que te produce e intentamos ayudarte…


  12. Hola. Desde ya, muchísimas gracias por facilitarnos el script. Tengo un inconveniente al dar de alta el script y da un error haciendo referencia a la necesidad de que exista el servicio vboxnet. Te paso la salida del mensaje:

    update-rc.d: using dependency based boot sequencing
    update-rc.d: warning: mailingserver stop runlevel arguments (0 1 6) do not match LSB Default-Stop values (S 0 1 6)
    insserv: Service vboxnet has to be enabled to start service VirtualBox
    insserv: exiting now!
    update-rc.d: error: insserv rejected the script header

    Mientras espero la respuesta, voy viendo por qué no levanta el vboxnet.
    Cualquier sugerencia es bienvenida.
    Gracias!



Deja un comentario

Este sitio utiliza Akismet para reducir el spam. Conoce cómo se procesan los datos de tus comentarios.