04 September, 2019

Automatically restoring running VirtualBox VMS after restart

VirtualBox has a built in solution for automatically starting and stopping vitual machines, as it is well explained in this post. However, I have a lot of virtual machines, and depending on what I am doing a different set of machines are running. I am not in a critical environment, therefore my vm host is set to automatically install updates, and if needed restart. In order not to loose the virtual machines I have written a small systemd service, which on shutdown saves all running virtual machine states and on restart starts them again.

The solution consists of 2 bash scripts and a service configuration file.

Here is the save state script (virtbox_savevms.sh):

#!/bin/bash
VBoxManage list runningvms | awk '{gsub(/"/,"",$1); print $1 }' \
 > /home/laco/sambapublic/serverconfig/runningvms

vms=`cat /home/laco/sambapublic/serverconfig/runningvms`

for vm in $vms
do
   VBoxManage controlvm $vm savestate
done

The script simply takes a list of the running VMs, saves the list to a secure place, then in a for loop stops them all.

Here is the restart script (virtbox_startvms.sh):

#!/bin/bash
vms = ''


if [ -f /home/laco/sambapublic/serverconfig/runningvms ]; then
  vms=`cat /home/laco/sambapublic/serverconfig/runningvms`
  for vm in $vms
    do
    VBoxManage startvm $vm --type headless
    done
fi

rm -f /tmp/runningvms


Again very simple, checks if there is a list of stopped VMs, if yes, in a loop restarts them.

The last step is to create a systemd service file (keep_vms_onrestart.service):

[Unit]
Description=Keep Virtual Box virtual machines running after computer restarts
Requires=vboxdrv.service
After=vboxdrv.service
Conflicts=shutdown.target

[Service]
Type=oneshot
User=laco
Group=laco
ExecStart=/home/laco/sambapublic/serverconfig/virtbox_startvms.sh
ExecStop=/home/laco/sambapublic/serverconfig/virtbox_savevms.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

This ensures that the saving is done before the VirtualBox drivers are unloaded and the restoration after the drivers are loaded. On how to install systemd services here is a good description.

In practice you should copy the two scripts to the location you like, and then update the vmlist file location in the scripts. Next you should copy the service file to /etc/systemd/system. In this file you should update the script locations. After this you can test the service with sudo service keep_vms_onrestart stop and sudo service keep_vms_onrestart start, and when it is working you can enable the service with sudo systemctl enamble keep_vms_onrestart.service.

After next reboot your running vms should remain :-)

No comments: