vboxapi.py revision 15fe3cf8212d4ca73ea0a4fe547892bcddef6e16
# -*- coding: utf-8 -*-
# $Id$
"""
VirtualBox Python API Glue.
"""
__copyright__ = \
"""
Copyright (C) 2009-2015 Oracle Corporation
This file is part of VirtualBox Open Source Edition (OSE), as
available from http://www.virtualbox.org. This file is free software;
General Public License (GPL) as published by the Free Software
Foundation, in version 2 as it comes in the "COPYING" file of the
VirtualBox OSE distribution. VirtualBox OSE is distributed in the
hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
"""
__version__ = "$Revision$"
# Note! To set Python bitness on OSX use 'export VERSIONER_PYTHON_PREFER_32_BIT=yes'
# Standard Python imports.
import os
import sys
import traceback
import builtins
import __builtin__
else:
"""The new-style print function for Python 2.4 and 2.5."""
if fp is None:
return
# If the file has an encoding, encode unicode with it.
if errors is None:
errors = "strict"
if sep is not None:
raise TypeError("sep must be None or a string")
if end is not None:
raise TypeError("end must be None or a string")
if kwargs:
raise TypeError("invalid keyword arguments to print()")
if not want_unicode:
break
if want_unicode:
else:
newline = "\n"
space = " "
if sep is None:
if end is None:
if i:
#
# Globals, environment and sys.path changes.
#
if VBoxBinDir is None:
# Will be set by the installer
VBoxBinDir = "%VBOX_INSTALL_PATH%"
else:
if VBoxSdkDir is None:
# Will be set by the installer
VBoxSdkDir = "%VBOX_SDK_PATH%"
else:
#
# Import the generated VirtualBox constants.
#
from .VirtualBox_constants import VirtualBoxReflectionInfo
class PerfCollector(object):
""" This class provides a wrapper over IPerformanceCollector in order to
get more 'pythonic' interface.
To begin collection of metrics use setup() method.
To get collected data use query() method.
It is possible to disable metric collection without changing collection
parameters with disable() method. The enable() method resumes metric
collection.
"""
""" Initializes the instance.
"""
""" Discards all previously collected values for the specified
metrics, sets the period of collection and the number of retained
samples, enables collection.
"""
""" Resumes metric collection for the specified metrics.
"""
""" Suspends metric collection for the specified metrics.
"""
""" Retrieves collected metric values as well as some auxiliary
information. Returns an array of dictionaries, one dictionary per
metric. Each dictionary contains the following entries:
'name': metric name
'object': managed object this metric associated with
'unit': unit of measurement
'scale': divide 'values' by this number to get float numbers
'values': collected data
'values_as_string': pre-processed values ready for 'print' statement
"""
# Get around the problem with input arrays returned in output
# parameters (see #3953) for MSCOM.
else:
out = []
if scale != 1:
fmt = '%.2f%s'
else:
fmt = '%d %s'
'scale': scale,
})
return out
#
# Attribute hacks.
#
def ComifyName(name):
## This is for saving the original DispatchBaseClass __getattr__ and __setattr__
# method references.
_g_dCOMForward = {
'getattr': None,
'setattr': None,
}
""" Our getattr replacement for DispatchBaseClass. """
# Fastpath.
if oRet is not None:
return oRet
# Try case-insensitivity workaround for class attributes (COM methods).
if k.lower() == sAttrLower:
# Slow path.
try:
except AttributeError:
""" Our setattr replacement for DispatchBaseClass. """
try:
except AttributeError:
class PlatformBase(object):
"""
Base class for the platform specific code.
"""
_ = aoParams
def getVirtualBox(self):
"""
Gets a the IVirtualBox singleton.
"""
return None
"""
Get a session object that can be used for opening machine sessions.
The oIVBox parameter is an getVirtualBox() return value, i.e. an
IVirtualBox reference.
See also openMachineSession.
"""
_ = oIVBox
return None
""" Returns the platform type (class name sans 'Platform'). """
return None
"""
"""
return False
"""
Retrives the value of the array attribute 'sAttrib' from
interface 'oInterface'.
This is for hiding platform specific differences in attributes
returning arrays.
"""
_ = oInterface
_ = sAttrib
return None
def initPerThread(self):
"""
Does backend specific initialization for the calling thread.
"""
return True
def deinitPerThread(self):
"""
Does backend specific uninitialization for the calling thread.
"""
return True
"""
Instantiates and wraps an active event listener class so it can be
passed to an event source for registration.
oImplClass is a class (type, not instance) which implements
IEventListener.
dArgs is a dictionary with string indexed variables. This may be
modified by the method to pass platform specific parameters. Can
be None.
This currently only works on XPCOM. COM support is not possible due to
shortcuts taken in the COM bridge code, which is not under our control.
Use passive listeners for COM and web services.
"""
_ = oImplClass
_ = dArgs
raise Exception("No active listeners for this platform")
"""
Wait for events to arrive and process them.
The timeout (cMsTimeout) is in milliseconds for how long to wait for
events to arrive. A negative value means waiting for ever, while 0
does not wait at all.
Returns 0 if events was processed.
Returns 1 if timed out or interrupted in some way.
Returns 2 on error (like not supported for web services).
Raises an exception if the calling thread is not the main thread (the one
that initialized VirtualBoxManager) or if the time isn't an integer.
"""
_ = cMsTimeout
return 2
def interruptWaitEvents(self):
"""
Interrupt a waitForEvents call.
This is normally called from a worker thread to wake up the main thread.
Returns True on success, False on failure.
"""
return False
"""
Unitializes the platform specific backend.
"""
return None
"""
IUnknown::QueryInterface wrapper.
oIUnknown is who to ask.
sClassName is the name of the interface we're asking for.
"""
return None
#
# Error (exception) access methods.
#
"""
Returns the COM status code from the VBox API given exception.
"""
return None
"""
Returns True if the exception indicates that the interface is dead, False if not.
"""
return False
"""
hrStatus.
The oXcpt parameter can be any kind of object, we'll just return True
if it doesn't behave like a our exception class.
Will not raise any exception as long as hrStatus and self are not bad.
"""
try:
except AttributeError:
return False
return True
# Fudge for 32-bit signed int conversion.
return True
return False
"""
Returns the best error message found in the COM-like exception.
Returns None to fall back on xcptToString.
Raises exception if oXcpt isn't our kind of exception object.
"""
return None
def xcptGetBaseXcpt(self):
"""
Returns the base exception class.
"""
return None
"""
"""
return oDst
"""
Copy everything that looks like error constants from oDst to oSrc.
"""
return oDst
class PlatformMSCOM(PlatformBase):
"""
Platform specific code for MS COM.
"""
## @name VirtualBox COM Typelib definitions (should be generate)
#
# @remarks Must be updated when the corresponding VirtualBox.xidl bits
# are changed. Fortunately this isn't very often.
# @{
VBOX_TLB_GUID = '{D7569351-1750-46F0-936E-BD127D5BC264}'
VBOX_TLB_LCID = 0
VBOX_TLB_MAJOR = 1
VBOX_TLB_MINOR = 3
## @}
#
# Since the code runs on all platforms, we have to do a lot of
# importing here instead of at the top of the file where it's normally located.
#
import win32com
import pythoncom
import win32api
import winerror
from win32con import DUPLICATE_SAME_ACCESS
import threading
pid = GetCurrentProcess()
# Hack the COM dispatcher base class so we can modify method and
# attribute names to match those in xpcom.
if _g_dCOMForward['setattr'] is None:
# Hack the exception base class so the users doesn't need to check for
# XPCOM or COM and do different things.
## @todo
#
# Make sure the gencache is correct (we don't quite follow the COM
# versioning rules).
#
_ = dParams
"""
Flushes VBox related files in the win32com gen_py cache.
This is necessary since we don't follow the typelib versioning rules
that everyeone else seems to subscribe to.
"""
#
# The EnsureModule method have broken validation code, it doesn't take
# typelib module directories into account. So we brute force them here.
# (It's possible the directory approach is from some older pywin
# version or the result of runnig makepy or gencache manually, but we
# need to cover it as well.)
#
import shutil
#
# Ensure that our typelib is valid.
#
return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR)
_ = oIVBox
import win32com
def getVirtualBox(self):
import win32com
return 'MSCOM'
def initPerThread(self):
import pythoncom
def deinitPerThread(self):
import pythoncom
if True:
raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() '
'returns new gateway objects all the time, thus breaking EventQueue '
'assumptions about the listener interface pointer being constants between calls ')
# Did this code ever really work?
d = {}
d['BaseClass'] = oImplClass
d['dArgs'] = dArgs
str_ = ""
str_ += "import win32com.server.util\n"
str_ += "import pythoncom\n"
str_ += "class ListenerImpl(BaseClass):\n"
str_ += " _com_interfaces_ = ['IEventListener']\n"
str_ += " _typelib_guid_ = tlb_guid\n"
str_ += " _typelib_version_ = tlb_major, tlb_minor\n"
str_ += " _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n"
# Maybe we'd better implement Dynamic invoke policy, to be more flexible here
str_ += " _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"
# capitalized version of listener method
str_ += " HandleEvent=BaseClass.handleEvent\n"
str_ += " def __init__(self): BaseClass.__init__(self, dArgs)\n"
str_ += "result = win32com.server.util.wrap(ListenerImpl())\n"
exec(str_, d, d)
return d['result']
from win32api import GetCurrentThreadId
from win32event import INFINITE
from win32event import MsgWaitForMultipleObjects, \
from pythoncom import PumpWaitingMessages
import types
raise TypeError("The timeout argument is not an integer")
raise Exception("wait for events from the same thread you inited!")
if timeout < 0:
else:
# is it possible?
rc = 2
# Waiting messages
rc = 0
else:
# Timeout
rc = 1
# check for interruption
if self.fInterrupted:
rc = 1
return rc
def interruptWaitEvents(self):
"""
Basically a python implementation of NativeEventQueue::postEvent().
The magic value must be in sync with the C++ implementation or this
won't work.
Note that because of this method we cannot easily make use of a
non-visible Window to handle the message like we would like to do.
"""
from win32api import PostThreadMessage
try:
except:
return False
return True
import pythoncom
from win32file import CloseHandle
if h is not None:
CloseHandle(h)
pass
# The DISP_E_EXCEPTION + excptinfo fun needs checking up, only
# empirical info on it so far.
try:
except:
pass
return hrXcpt
0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE.
0x800706be, -2147023170, # RPC_S_CALL_FAILED.
0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE.
0x80010108, -2147417848, # RPC_E_DISCONNECTED.
0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF
]
try:
return sRet[0:]
except:
pass
try:
return sRet
except:
pass
return None
def xcptGetBaseXcpt(self):
import pythoncom
import winerror
# XPCOM compatability constants.
return oDst
class PlatformXPCOM(PlatformBase):
"""
Platform specific code for XPCOM.
"""
import xpcom
import xpcom.components
_ = dParams
_ = oIVBox
import xpcom.components
def getVirtualBox(self):
import xpcom.components
return 'XPCOM'
def initPerThread(self):
import xpcom
def deinitPerThread(self):
import xpcom
d = {}
d['BaseClass'] = oImplClass
d['dArgs'] = dArgs
str = ""
str += "import xpcom.components\n"
str += "class ListenerImpl(BaseClass):\n"
str += " _com_interfaces_ = xpcom.components.interfaces.IEventListener\n"
str += " def __init__(self): BaseClass.__init__(self, dArgs)\n"
str += "result = ListenerImpl()\n"
exec(str, d, d)
return d['result']
import xpcom
def interruptWaitEvents(self):
import xpcom
import xpcom
import xpcom.components
0x80004004, -2147467260, # NS_ERROR_ABORT
0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)
]
try:
return sRet
except:
pass
return None
def xcptGetBaseXcpt(self):
import xpcom
import xpcom
# COM compatability constants.
return oDst
class PlatformWEBSERVICE(PlatformBase):
"""
VirtualBox Web Services API specific code.
"""
# Import web services stuff. Fix the sys.path the first time.
import VirtualBox_wrappers
from VirtualBox_wrappers import IWebsessionManager2
# Initialize instance variables from parameters.
if dParams is not None:
else:
#
# Base class overrides.
#
def getVirtualBox(self):
return 'WEBSERVICE'
""" Returns True if remote VBox host, False if local. """
return True
# Webservices cannot do that yet
return 2
# Webservices cannot do that yet
return False
try:
except:
pass
d = {}
d['oIUnknown'] = oIUnknown
str = ""
# wrong, need to test if class indeed implements this interface
exec(str, d, d)
return d['result']
#
# Web service specific methods.
#
from VirtualBox_wrappers import IWebsessionManager2
if url is None:
url = ""
if user is None:
user = ""
if passwd is None:
passwd = ""
def disconnect(self):
## The current (last) exception class.
# This is reinitalized whenever VirtualBoxManager is called, so it will hold
# was used. Most clients does talk to multiple VBox instance on different
# platforms at the same time, so this should be sufficent for most uses and
# be way simpler to use than VirtualBoxManager::oXcptClass.
CurXctpClass = None
class VirtualBoxManager(object):
"""
VirtualBox API manager class.
The API users will have to instantiate this. If no parameters are given,
it will default to interface with the VirtualBox running on the local
machine. sStyle can be None (default), MSCOM, XPCOM or WEBSERVICES. Most
users will either be specifying None or WEBSERVICES.
The dPlatformParams is an optional dictionary for passing parameters to the
WEBSERVICE backend.
"""
pass
if sStyle is None:
sStyle = "MSCOM"
else:
sStyle = "XPCOM"
if sStyle == 'XPCOM':
elif sStyle == 'MSCOM':
elif sStyle == 'WEBSERVICE':
else:
## VirtualBox API constants (for webservices, enums are symbolic).
## Status constants.
## @todo Add VBOX_E_XXX to statuses? They're already in constants...
## Dictionary for errToString, built on demand.
self._dErrorValToName = None
## The exception class for the selected platform.
global CurXcptClass
# Get the virtualbox singleton.
try:
except NameError:
print_("Installation problem: check that appropriate libs in place")
raise
except Exception:
print_("init exception: ", e)
else:
raise e
## @deprecated
# This used to refer to a session manager class with only one method
# called getSessionObject. The method has moved into this call.
def getPythonApiRevision(self):
"""
Returns a Python API revision number.
This will be incremented when features are added to this file.
"""
return 3
#
# Wrappers for self.platform methods.
#
def getVirtualBox(self):
""" See PlatformBase::getVirtualBox(). """
""" See PlatformBase::getSessionObject(). """
""" See PlatformBase::getArray(). """
""" See PlatformBase::createListener(). """
""" See PlatformBase::waitForEvents(). """
def interruptWaitEvents(self):
""" See PlatformBase::interruptWaitEvents(). """
""" See PlatformBase::queryInterface(). """
#
# Init and uninit.
#
def initPerThread(self):
""" See PlatformBase::deinitPerThread(). """
def deinitPerThread(self):
""" See PlatformBase::deinitPerThread(). """
"""
For unitializing the manager.
Do not access it after calling this method.
"""
return True
#
# Utility methods.
#
"""
Attemts to open the a session to the machine.
Returns a session object on success.
Raises exception on failure.
"""
if fPermitSharing:
else:
return oSession
"""
Closes a session opened by openMachineSession.
Ignores None parameters.
"""
if oSession is not None:
return True
"""
Returns a helper class (PerfCollector) for accessing performance
collector goodies. See PerfCollector for details.
"""
"""
Returns the VirtualBox binary directory.
"""
global VBoxBinDir
return VBoxBinDir
"""
Returns the VirtualBox SDK directory.
"""
global VBoxSdkDir
return VBoxSdkDir
#
# Error code utilities.
#
## @todo port to webservices!
"""
Gets the status code from an exception. If the exception parameter
isn't specified, the current exception is examined.
"""
if oXcpt is None:
"""
Returns True if the exception indicates that the interface is dead,
False if not. If the exception parameter isn't specified, the current
exception is examined.
"""
if oXcpt is None:
"""
Checks if the exception is one that could come from the VBox API. If
the exception parameter isn't specified, the current exception is
examined.
"""
return False
if oXcpt is None:
"""
hrStatus.
The oXcpt parameter can be any kind of object, we'll just return True
if it doesn't behave like a our exception class. If it's None, we'll
query the current exception and examine that.
Will not raise any exception as long as hrStatus and self are not bad.
"""
if oXcpt is None:
"""
Negated xcptIsEqual.
"""
"""
Converts the specified COM status code, or the status code of the
specified exception, to a C constant string. If the parameter isn't
specified (is None), the current exception is examined.
"""
# Deal with exceptions.
else:
# Build the dictionary on demand.
if self._dErrorValToName is None:
dErrorValToName = dict()
# Do the lookup, falling back on formatting the status number.
try:
except KeyError:
return sStr
"""
Returns the best error message found in the COM-like exception. If the
exception parameter isn't specified, the current exception is examined.
"""
if oXcpt is None:
if sRet is None:
return sRet
# Legacy, remove in a day or two.