15 April, 2009

Starting VirtualBox as a Service

I've been trying to compare VirtualBox features with VMware Server 2.0. One of the first features that doesn't exist (without some work) is the concept of auto-starting virtual machines at system start-up.

With head-less virtual machine modes and RDP connectivity, it appears that all the core features exist.

By incorporating the starting of virtual machines in head-less modes as a service that is started at system start-up you'd have the equivalent of VMware Server. This post will document the means to do just that.

First, since system start-up is executed by root, the virtual machine will need to be associated with the root user. You can accomplish this by firing up VirtualBox interactively and create the desired virtual machines. I, however, had the virtual machines I wanted to start created in an alternative user account, so I created a soft-link between the root user home directory and the user directory (keep you security concerns to yourself, this is simply proof of concept).


# cd /root
# ln -s /home/user/.VirtualBox .VirtualBox


Next, create a script that serves as the necessary service daemon:


#!/bin/bash
# scriptName: VBoxD

VBOXHEADLESS="/usr/bin/VBoxHeadless"

vbox_start() {
echo "...starting $1" >> /var/tmp/myLog
$VBOXHEADLESS -s $1 > /dev/null &
}

#---main---
case "$1" in
start)
echo "...starting my service" >> /var/tmp/myLog
logger -p user.notice "starting service"
vbox_start WinXp
;;
stop)
echo "...stopping my service" >> /var/tmp/myLog
logger -p user.notice "stopping service"
;;
restart)
echo "...restarting my service" >> /var/tmp/myLog
;;
esac

exit 0



Note that this script has hard-coded virtual machine named WinXp; again, this is proof of concept. Please keep in mind, this isn't a complete service script solely enough to demonstrate the ability of introducing a service into system start-up.

You can test the script behavior can by invoking:

# ./VBoxD start
# ./VBoxD stop


To incorporate this into the system start-up, you first find what runlevel you are currently running:

# ps -aef | grep init
root 1 0 0 20:23 ? 00:00:00 init [2]
root 5047 4725 0 20:58 pts/0 00:00:00 grep init


Shows run-level 2; meaning that the service must reside in /etc/rc2.d

Changing to /etc/rc2.d you add the service by creating a soft-link to /root/VBoxD with a prefix S followed by a 2-digit numeric (the larger the numeric the later the service is started). In this example, I created S91VBoxD as follows:

xion:/etc/rc2.d# ls -l S91VBoxD
lrwxrwxrwx 1 root root 11 2009-04-12 19:47 S91VBoxD -> /root/VBoxD


If you've properly enabled RDP for this machine at port 3389 you should be able to connect to the head-less virtual machine by:

$ rdesktop 127.0.0.1:3389

No comments: