Search code examples
pythonvirtualboxpywin32

Can't restore VM in Python Virtualbox API


I want to restore a VM in Virtualbox API but I got this exception:

AttributeError: '<win32com.gen_py.VirtualBox Type Library.IConsole instance at 0x41746480>' object has no attribute 'restoreSnapshot'

How can I fix it?

Here is my code:

import vboxapi

def wait(sth):
    sth.waitForCompletion(-1)

class Foo:
    mgr=vboxapi.VirtualBoxManager()
    vbox=mgr.vbox
    vm=vbox.findMachine(const.VM_NAME)

    def __init__(self):
        self.session=self.mgr.getSessionObject(self.vbox)
        wait(self.vm.launchVMProcess(self.session, 'gui', ''))

    def restore(self):
        console=self.session.console
        wait(console.powerDown())
        wait(console.restoreSnapshot(self.vm.findSnapshot('test')))
        wait(console.powerUp())

foo=Foo()
foo.restore()

I'm using vboxapi 5.0.10 under Python 3.4.

Plus, when I changed console.restoreSnapshot to self.vm.restoreSnapshot according to the VirtualBox SDK Ref, it says that Method Machine::restoreSnapshot is not implemented.


Solution

  • Here's my solution after days of trying.

    def restore(self):
        self.log('=== powering down')
        wait(self.session.console.powerDown())
        self.session.unlockMachine()
    
        self.log('=== restoring')
        self.session=self.mgr.openMachineSession(self.vm) # WHY?
        self.vm=self.session.machine
        wait(self.vm.restoreSnapshot(self.vm.findSnapshot(const.VM_BASE_SNAPSHOT)))
        self.session.unlockMachine()
    
        self.log('=== powering up')
        self.vm=self.vbox.findMachine(const.VM_NAME)
        self.session=self.mgr.getSessionObject(self.vbox)
        while True:
            try:
                wait(self.vm.launchVMProcess(self.session,'gui' if const.DEBUG else 'headless',''))
            except pywintypes.com_error: #unlocking machine
                time.sleep(.1)
            else:
                break
    

    Although I don't know the reason, it works anyway.