Success! Use Task Scheduler to create auto VM start/stop

Discussions related to using VirtualBox on Windows hosts.
maerkis
Posts: 1
Joined: 19. Apr 2012, 15:24

Success! Use Task Scheduler to create auto VM start/stop

Post by maerkis »

VirtualBox Automatic VM Startup/Shutdown
=====================================

Tested: Windows 7 64bit, Server 2008 64 bit.
**This is untested in XP, Server 2003 or 2000**.

22 AUG 2012 UPDATE: Successfully tested on Windows Server 2008 R2!

This howto details setting up VirtualBox virtual machines to start and stop automatically (and safely!) through the Windows 7/Vista/Server 2008 Task Scheduler. It also explains how to execute vboxmanage commands in a modular way, free from the command line. Virtualbox has no (as of 19/04/12) way to run vm's automatically, so this is the most practical way to achieve vm automation without any registry hacking or using third party service utilities. Much of the text below is explanatory, the actual steps are quite simple once you have the theory down pat. The end result is fully automatic start/stop/save/pause/control (depending how you choose to configure tasks) of vm's in much the same way as if they were running as a proper windows service. No knowlege of any scripting, programming or registry settings is required. At the time of writing, I have a vm running on a headless 2008 server quite happily (see updates above for more recent progress).

There are some things to be aware of when using this technique:

= Vm's will be headless and non-interactive, except through vboxmanage tasks configured in Task Manager. GUI and command line tools will not see or know that they are running when called directly from the command line. Attempts to run or control vm's in the usual ways will be met with errors and should not be attempted until the vm is shutdown or state-saved through operations configured in Task Scheduler (detailed below). If you want to use the command line or the GUI, you will need to stop the vm through the Task Scheduler first.

= Tasks need to be run under accounts with local administrator privileges. Active Directory accounts must be of type BUILTIN and members of either "performance log users" or "power backup users" groups. The user account must also be the same account that owns the vm's or they will fail to start. If any Task Scheduler configured tasks need to interact with other running tasks, they must ALL run under the same user account.

= Vm's have successfully been started/controlled/stopped/savestate'd using a local system user account on Windows 7, so you don't need to be a member of a network or domain, nor is it necessary to have a server operating system. Local administrator privileges are sufficient in this case.

Method (in the madness):

1. It would be sensible to dedicate a local system administrator account for this purpose, with a strong password and no other functions beside running your vm's. Login as a local system administrator (or builtin Active Directory admin for Server 2008) and create/import your vm's in the normal way. Verify that they run and behave as normal, then close them down. Go to Control Panel -> System -> Advanced System Settings -> Environment Variables and add a new system variable called VBOX_USER_HOME and enter the path of your dedicated virtualbox user, something like C:\Users\USERNAME_GOES_HERE\.Virtualbox. You could also add the Virtualbox install directory to your %PATH% to save some clicking later on.

*****SAVE AND REBOOT!***** Nothing will work until you reboot.

2. Run Task Scheduler with administrator privileges, if it doesn't prompt you for them (Start -> type in task scheduler) and click on the Task Scheduler Library folder. Right click on the folder and create a new folder called VirtualBox (or whatever you please, it doesn't matter). Click on this new folder, then right click on it to create another folder and name it after your vm, or something like that. Once again, the name can be anything, this is just a way to keep tasks grouped by vm to avoid confusion.

3. Click on the new vm folder you just created and in the Actions panel, click on Create Task. In the General tab, give the task a name that relates to it's function eg: auto-startup-foobar-vm or something like that. Add a meaningful description if you're one of those haggered sysadmins that doesn't get enough sleep to remember what you did 5 mins ago. Tick "Run whether user is logged on or not" and also "Run with highest privileges" to avoid other windows things blocking/tampering with it. Check that the user it is set to run as is the user you are logged in as. Leave the other options in the General tab as default.

4. In the Triggers tab, add a new trigger. You have some options here, as follows:

A) Schedule: If you need a vm to run on a set time/date. Not suitable for reboots, though you can set "Run task as soon as possible after a scheduled start is missed" in the Settings tab.
B) At log on: Vm only starts if a user logs on.
C) At startup: Suitable for reboots. Set "Delay task for:" to 1 minute for slow booting machines, as this will allow time for network interfaces and firewall/dhcp clients/servers to configure themselves. Alternatively, you can use the timeout command as an action to delay vm startup (see below).
D) On an event: Finer grained control of startup triggering, there are a few (not all though, there are oodles of event ID's you could use) particularly useful event ID's for use when a host boots. You need to at least specify the event ID and the log it resides in. Listed in order of boot sequence:

4201 Tcpip: System event log. Registers hardware interface events on boot. Probably a bit too early in the boot stage for starting vm's.

4608 Windows is starting up: Security log. Logged after basic system hardware initialization/config has taken place and system boot is in full swing. Little or no networking services available at this stage, so a delay is advisable, probably 30 seconds if your vm boots faster than the host.

6005 Event log start: System log. This is the event logging service. Logs about 20 seconds (slow 2008 host) after 4608. Useful as a single startup trigger that isn't tied to any specific process which might reset on you and cause unwanted triggers while your vm is manually switched off.

6013 Event log uptime: System log. Like the name says, logs system uptime. First logs at the same time as 6005 and once a day after that. Useful as a heartbeat timer, but has the remote chance that it will trigger the vm on a shutdown, just after it has been saved. Flip a coin on this one.

5033 Firewall driver is loaded: Security log. For the paranoid amongst us, only triggers a vm if the firewall is ready to start. Note that this only loads the driver, the actual service starts a couple of seconds later so you have a few second attack window, where someone could attack your vm as it is booting. OCD admins will appreciate this.

5024 Firewall service start: Security log. For people who huddle in a corner wearing a tin foil hat and biting their nails. Only triggers a vm when the firewall is fully operational. Note that this will generate a trigger event every time the service restarts, so set options in the Settings tab in lieu of this to avoid multiple instances being started.

1043 DHCP server running: System log. Provides a late starting, absolute point to start a vm if the host is running a DHCP server. Rather than specifying a timer, you just use this to trigger the vm so it is guaranteed to have a DHCP ACK as soon as it requests it. Avoids expired leases lingering and keeps dynamic DNS records fresh, if you use them.

Using system events is a powerful way to automate tasks on your vm's. Snapshots, scheduled reboots, specific responses to system events- pretty much whatever you want is availabe and Task Manager also lets you provide custom XML filters. A word of caution with event ID's- they can be affected by things like group policy, so have a browse through your event viewer (start -> type in event viewer) and verify that your system actually uses them. This will save you some teeth grinding and several days of pure pain.

You can add as many or few triggers as you wish for a task, they can be disabled/enabled for testing as well. The condition is, one task per operation eg 'vboxmanage controlvm "foobar" savestate' would require you to create an additional task with it's own triggers and settings, which we will do at Step 8. If you want to take a shortcut for sequential operations, you can group them in the actions tab and they will be executed in sequence. This saves creating a single task for each operational step.

5. In the Actions tab, add a new action "Start a program" and browse to the location of VBoxHeadless.exe, which is "C:\Program Files\Oracle\VirtualBox\VBoxHeadless.exe" in server 2008. Add arguments --startvm "your-vbox-vm-name-here" --more-options=foo. Note that the quotes are necessary and names are case sensetive. Adding --vrde=config allows you to switch vrdp on/off via the config file. By default it is on (if you have it installed) when running vboxheadless. Tasks will fail if the user is not the owner of the vm. Note also that you can add multiple actions here so something like "timeout" with 20 as an argument could be used to insert a delay of 20 seconds, or you could run other commands to set up environment conditions before the vm starts. Just make sure that the command to start the vm is the last one. Execution is sequential, so A must exit before B can start, etc. Paths for standard programs may already be recognized, negating the need to navigate to the directory of each one eg, Timeout only requires double quotes to work.

6. You can pretty much leave all options disabled in the Conditions tab, unless your setup absolutely needs a particular option. *****WARNING****: Virtualbox binaries such as vboxheadless DO NOT like system kill signals and WILL NOT shutdown/savestate your vm automatically! Do not allow any settings in a task to stop it, unless your vm is tolerant of brute force kills. In my testing, the task would exit, but leave vboxheadless running. In a system shutdown scenario, this would either stop the system shutting down, or result in vboxheadless being forcibly decapitated. In Step 8, we will set up a separate automatic task to shutdown gracefully. Also be aware that though the Conditions tab has a setting for network adaptors, the exact behaviour is unknown and last I tried it, I couldn't get a vm to boot at all. Using sytem event ID's is far more reliable.

7. Settings tab: Tick "Allow task to be run on demand" so you can go into Task Scheduler and manually control the vm. Set this for all tasks you create, for this reason. All other options in this tab can be disabled. The Fail/restart option could be useful as a heartbeat timer. By default, if the task is already running, no new instances will be started. This is necessary for our configuration and ALL tasks should be set this way to avoid multiple instances being activated. We are now finished creating the task. Click OK and you will be prompted to enter your password to finish. While we're on the topic, make sure your password is strong and set to never expire.

8. Now create another task and call it foobar-vm-savestate (or whatever pleases you). This will have an event ID of 1074 "shutdown/reboot" (system log) and will use pretty much all the same settings as the first task, except the action will be "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe" controlvm savestate. As already noted, make sure that this ID is in use. You can verify savestate operation over reboots by your vm's log file and also Task Manager's logs. All successful actions should terminate with 0. A 1 indicates a failure, even if it tells you it succeeded. If 1074 is not available, you'll have to scrounge around for some other shutdown related event ID to use. I stopped searching when I found 1074. 8)

9. Manually start your vm through Task Manager and refresh the logs to verify a running process. Now Start foobar-vm-savestate and refresh your logs again. Both actions should terminate with 0. If you get this far, start the vm again and go for a reboot. Once you login again (or ssh, vrdp etc to your vm) you should be greeted with happy log files and a cleanly restored and running vboxheadless.

Be aware that though Task Scheduler displays task status, it isn't always accurate. If a task is triggered multiple times (say, if you have multiple start triggers configured), the task may show as being "Ready" when in fact the vm is actually running. This is because Task Scheduler logs the state of a task by it's last run attempt and not by what programs it starts/stops. The best way to check the realtime status of programs you run through Task Scheduler is to attempt using those programs to see if they are running. You can also find the program in the Task Manager (Ctrl-Alt-Del) and select "Show tasks from all users", or check the logs of the programs you automate through Task Scheduler.

10. Create another task called foobar-vm-acpipowerbutton identical to the previous task but with acpipowerbutton as the argument. Choose which of these you prefer to activate on reboots and enable/disable the triggers accordingly.

By now you get the idea that Task Scheduler can be filled with specially configured tasks to interact with your vm's via vboxmanage. You get logs and a reasonably simple but configurable interface that saves you manually typing everything on a command line each time you use it. If vrdp is installed, you can also have a remote desktop on your screen to interact with vm's directly. Just remember that you need to shutdown or savestate/pause vm's and end the task before you can access them with the virtualbox desktop gui. For the more adventurous, it is possible to set up automatic snapshots, backups, exports, cloning, etc and even a manual teleporting function is do-able. With careful configuration of actions, command line output can be sent to log files in a directory for future reference, and a task or two set up to clean them up regularly to avoid filling up your hard drive. Task scheduler also gives feedback as to which vm's are running or stopped and allows you to run a task on each one at a click of a mouse.

I'm off to bed now. Five days with a few hours of broken sleep do weird things to a person's mind. :idea:
Last edited by maerkis on 22. Aug 2012, 11:34, edited 1 time in total.
maxchen
Posts: 25
Joined: 27. Oct 2010, 15:57
Primary OS: Ubuntu other
VBox Version: PUEL
Guest OSses: Windows

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by maxchen »

thanks so much!
but I am using VBoxVmService now on my friend's computer (I am using Ubuntu host, not windows host), see viewtopic.php?f=6&t=8595
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

I've managed to get Task Scheduler to work and load up a VM at a pre-determined time each day. However, I am unable to "Savestate" for any VM that is launched from the Scheduler.

If I launch the VM from a command line "normally", i.e. not scheduled, I am able to "savestate" in the same "session" in the CMD prompt without any issues. As soon as a VM is launched on a schedule in another "session" (environment?), the savesate will not work.

Is there any way around this? I'd like to schedule a savestate event in the task scheduler to end the VM.

Thanks.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

A bit old topic I must say, but I'll go with it. What do you *exactly* do to save the state?
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

If I launch a headless VM (WHS_V1) from a command line with:

VBoxManage.exe startvm WHS_V1 --type headless

I can savestate with

VBoxManage.exe controlvm WHS_V1 savestate

But launching the headless VM from a schedules task, and the savestate will not work.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

What do you *exactly* mean (once again) by "savestate will not work"? Paste the command you type in and the exact error you are getting.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

If I open a "normal" command prompt and run the "green" command, the VM will start in headless mode fine.

When I run the command in red to savestate of the VM, I get the percentages scroll across the screen/line and the VM is saved.

Image

Image

However, if the same start command is launched from a task schedule:

Image

When I run the savestate command in a command prompt, the program appears to hang and then reports the following:

Image

But the VM is running fine in headless from the scheduled task, but will not save as it will when launched directly from a command line.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

You don't show the user under which the task is running
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

It runs under my own credentials, not Administrator.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

Then that's your problem. As explained already on the forums, you need to run under the same user.
Different users cannot see each other's VMs. Running "As administrator" like you do in the CMD is also considered another user.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

I also ran the Scheduled task as "Administrator" and I get the same issue from the command line. I'll try it under my own credentials but then launch a non-admin command prompt and see what happens.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

Sadly it's not that easy. The task scheduler doesn't open a regular desktop session with a full profile and the likes, so some environment variables, data, inherited permissions will be missing.
Worse if you try to run it as SYSTEM, since there is no profile at all (unless you hack your way around).
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

That'll probably explain why if I run a VM from a Scheduled Task, the "GUI" won't load and gives this error:

Image


Hence my question:

How do I "savestate" for a headless VM that has been launched from a Scheduled Task?

Thanks.
noteirak
Site Moderator
Posts: 5229
Joined: 13. Jan 2012, 11:14
Primary OS: Debian other
VBox Version: OSE Debian
Guest OSses: Debian, Win 2k8, Win 7
Contact:

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by noteirak »

run another schedule task with the same environment parameters as the one that started the VM.
Hyperbox - Virtual Infrastructure Manager - https://apps.kamax.lu/hyperbox/
Manage your VirtualBox infrastructure the free way!
Mr_Inc
Posts: 7
Joined: 20. Jun 2014, 22:45

Re: Success! Use Task Scheduler to create auto VM start/stop

Post by Mr_Inc »

That works! Thanks.

My "issue" was that I ran the "savestate" command with some other tasks from within a batch file, and of course the VM would not save. I'll just split that line out to the task scheduler, run that first, then my batch file a few minutes later.

Cheers!
Post Reply