Windows: Creating a service out of headless application (VirtualBox). Stop/shutdown script

headlessservicevirtualboxwindows

My client needs to have a virtualized Linux running on his Windows Server 2008 (R1). I've managed to setup VirtualBox as a service with srvany, but I see no way of creating a kind of 'stop script' so the virtual machine powers off correctly when I stop the registered service.

I know there may be other options of creating a headless VM, but that's not the point. How can I create a 'stop script' that is executed when I stop the registered service (or the system is rebooted)?

Or maybe, there are some other ways to launch 'system shutdown' scripts so VM is stopped properly on shutdown?


(for those that might be interested)

How I created a VirtualBox service

  1. Setup a virtual machine
  2. Install "Windows Server 2003 Resource Kit Tools.exe".
  3. Copy ".VirtualBox" folder to 'C:\Windows\System32\config\systemprofile\' so 'system' user (which runs services) has its VirtualBox machines there.

    WARN: You'll need to correct VirtualBox.xml paths to snapshots, if your VM has any.
  4. Create an empty service named "UbuntuD" with the help of srvany:
    sc create UbuntuD binPath= "C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe" start= auto DisplayName= "Ubuntu Daemon"
  5. Specify the service start command. Add these keys to registry
    [HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Services\UbuntuD\Parameters]
    Application="C:\Program Files\Sun\VirtualBox\VBoxHeadless.exe"
    AppParameters="--vrdp=off -s Ubuntu"
    AppDirectory="C:\Program Files\Sun\VirtualBox\"
  6. There's no 'stop script' for our hacky service, so we add a shutdown script in 'Local Policy' -> Computer configuration -> Windows Settings -> Scripts (Startup/shutdown):

    C:\Program Files\Sun\VirtualBox\vboxmanage, params: controlvm Ubuntu savestate
  7. Run the service

Best Answer

"Real" service programs have code to handle performing cleanup and shutdown activities. You're running a program that wasn't intended to be run as a service, and it has no such code to handle graceful termination when the Service Control Manager (SCM) signals that the service is stopping.

Somebody could write a nice service wrapper for VirtualBox that could gracefully handle running as a service. That's the real solution. Unfortunately, you're not going to come up with a "hack" that will do what you're looking for. SRVANY (and every other program of the same type that I'm aware of) doesn't have any capability to execute user-specified code when SCM signals that the service is stopping.