Thursday, August 12, 2010

Notes - Run a Unix virtualbox machine during boot time

In order to save some memory and cpu on your host machine instead running virtual machines through the X system (windows like method :-p) you can use this method.
#Create a system user for VirtualBox
root@yourmachine:/imadirectory#useradd -r -m vbox
#add it to the right group (note that I'm using the same name for
#the group, not very educational)
root@yourmachine:/metoo#usermod -a -G vbox vbox
Probably you have installed Virtualbox with your user, and that installation will store the VirtualBox config files.
You need to copy all those files to the home directory of your new system user vbox and then change permissions to own the files,
by doing something like:
root@yourmachine:/home/vbox/.VirtualBox#chown -R vbox:vbox *
and make sure your virtual machine file allow write permissions to your vbox user or group:
root@yourmachine:/media/sda1# ls -l | grep openbsd
-rw-rw-r-- 1 dani vbox 1239450112 2010-08-12 21:29 openbsdserver.vdi
Once this is setup you can move to add a init script to your linux box, in my case a Ubuntu Lucid box.

#! /bin/sh 

### BEGIN INIT INFO
# Provides: Starts local virtual machines
# Required-Start: $local_fs $remote_fs $syslog $all
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
### END INIT INFO

N=/etc/init.d/virtual_machines_local
VBOX_RUNNING=`pgrep -c VBoxHeadless`
set -e

case "$1" in
start)
if [ "$VBOX_RUNNING" = 0 ]
then
logger "trying to boot vboxheadless.."
echo "Starting headless virtual machines."
sudo -i -b -u vbox /usr/bin/VBoxHeadless -s \
openbsdserver -vrdp off
else
echo "VBoxHeadless already appears to be running"
fi
;;
stop)
if [ `pgrep -c VBoxHeadless` != 0 ]
then
echo "Sending acpipowerbutton to VMs...."
logger "Sending acpipowerbutton to VMS...."
sudo -i -b -u vbox /usr/bin/VBoxManage controlvm \
openbsdserver acpipowerbutton
I=0
echo "Waiting for successful shutdown: \
60 seconds (or less)."
while [ `pgrep -c VBoxHeadless` != 0 ] && [ $I -lt 60 ]
do
sleep 1
I=$(($I + 1))
echo -n "."
done
fi
;;
reload|restart|force-reload)
;;
*)
echo "Usage: $N {start|stop}" >&2
exit 1
;;
esac
exit 0
Make sure you add it to default start / stop scripts with the proper runlevels, and install if necessary acpid on the guest system, so it can receive the signal acpipowerbutton to shutdown gracefully.
update-rc.d virtual_machines_local defaults

No comments: