VirtualBox

Changeset 47979 in vbox


Ignore:
Timestamp:
Aug 21, 2013 6:44:35 PM (11 years ago)
Author:
vboxsync
Message:

vboxapi.py: Some cleaning up. New features: Documentation. ;-) Dropped the session manager class as it served no purpose I could fathom.

Location:
trunk/src/VBox
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r47848 r47979  
    1 #!/usr/bin/python
    2 
     1#!/usr/bin/env python
     2# -*- coding: utf-8 -*-
     3# $Id$
     4"""
     5VirtualBox Python Shell.
     6
     7This program is a simple interactive shell for VirtualBox. You can query
     8information and issue commands from a simple command line.
     9
     10It also provides you with examples on how to use VirtualBox's Python API.
     11This shell is even somewhat documented, supports TAB-completion and
     12history if you have Python readline installed.
     13
     14Finally, shell allows arbitrary custom extensions, just create
     15.VirtualBox/shexts/ and drop your extensions there.
     16                                               Enjoy.
     17
     18P.S. Our apologies for the code quality.
     19"""
     20
     21__copyright__ = \
    322"""
    423Copyright (C) 2009-2013 Oracle Corporation
     
    1231hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
    1332"""
    14 
    15 #################################################################################
    16 # This program is a simple interactive shell for VirtualBox. You can query      #
    17 # information and issue commands from a simple command line.                    #
    18 #                                                                               #
    19 # It also provides you with examples on how to use VirtualBox's Python API.     #
    20 # This shell is even somewhat documented, supports TAB-completion and           #
    21 # history if you have Python readline installed.                                #
    22 #                                                                               #
    23 # Finally, shell allows arbitrary custom extensions, just create                #
    24 # .VirtualBox/shexts/ and drop your extensions there.                           #
    25 #                                                Enjoy.                         #
    26 ################################################################################
     33__version__ = "$Revision$"
     34
    2735
    2836import os, sys
     
    3543from pprint import pprint
    3644
     45
     46
     47#
     48# Global Variables
     49#
    3750g_fBatchMode = False
    3851g_sScriptFile = None
     
    4760g_sPrompt = "vbox> "
    4861
    49 g_fHasColors = True
    50 g_aTermColors = {
    51     'red':'\033[31m',
    52     'blue':'\033[94m',
    53     'green':'\033[92m',
    54     'yellow':'\033[93m',
    55     'magenta':'\033[35m',
    56     'cyan':'\033[36m'
    57     }
     62g_fHasColors  = True
     63g_dTermColors = {
     64    'red':      '\033[31m',
     65    'blue':     '\033[94m',
     66    'green':    '\033[92m',
     67    'yellow':   '\033[93m',
     68    'magenta':  '\033[35m',
     69    'cyan':     '\033[36m'
     70}
     71
     72
     73
    5874def colored(strg, color):
    5975    """
     
    6278    if not g_fHasColors:
    6379        return strg
    64     col = g_aTermColors.get(color, None)
     80    col = g_dTermColors.get(color, None)
    6581    if col:
    6682        return col+str(strg)+'\033[0m'
    67     else:
    68         return strg
     83    return strg
    6984
    7085if g_fHasReadline:
     
    238253
    239254def startVm(ctx, mach, vmtype):
    240     mgr = ctx['mgr']
    241255    vbox = ctx['vb']
    242256    perf = ctx['perf']
    243     session = mgr.getSessionObject(vbox)
     257    session = ctx['global'].getSessionObject(vbox)
    244258    progress = mach.launchVMProcess(session, vmtype, "")
    245259    if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0:
     
    670684    try:
    671685        vbox = ctx['vb']
    672         session = ctx['mgr'].getSessionObject(vbox)
     686        session = ctx['global'].getSessionObject(vbox)
    673687        mach.lockMachine(session, ctx['global'].constants.LockType_Shared)
    674688    except Exception, e:
     
    34713485
    34723486def main(argv):
    3473     style = None
    3474     params = None
    3475     autopath = False
    3476     script_file = None
     3487
     3488    #
     3489    # Parse command line arguments.
     3490    #
    34773491    parse = OptionParser()
    34783492    parse.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help = "switch on verbose")
     
    34953509        g_fHasReadline = False
    34963510        g_sCmd = options.command_line
     3511
     3512    params = None
    34973513    if options.opt_line is not None:
    34983514        params = {}
     
    35023518            (key, value) = strparam.split('=')
    35033519            params[key] = value
    3504     else:
    3505         params = None
    35063520
    35073521    if options.autopath:
    35083522        cwd = os.getcwd()
    35093523        vpp = os.environ.get("VBOX_PROGRAM_PATH")
    3510         if vpp is None and (os.path.isfile(os.path.join(cwd, "VirtualBox")) or os.path.isfile(os.path.join(cwd, "VirtualBox.exe"))) :
     3524        if    vpp is None \
     3525          and (   os.path.isfile(os.path.join(cwd, "VirtualBox")) \
     3526               or os.path.isfile(os.path.join(cwd, "VirtualBox.exe")) ):
    35113527            vpp = cwd
    35123528            print "Autodetected VBOX_PROGRAM_PATH as", vpp
     
    35163532        if vsp is None and os.path.isfile(os.path.join(cwd, "sdk", "bindings", "VirtualBox.xidl")) :
    35173533            vsp = os.path.join(cwd, "sdk")
    3518         if vsp is None and os.path.isfile(os.path.join(vpp, "sdk", "bindings", "VirtualBox.xidl")) :
     3534        if vsp is None and vpp is not None and os.path.isfile(os.path.join(vpp, "sdk", "bindings", "VirtualBox.xidl")) :
    35193535            vsp = os.path.join(vpp, "sdk")
    35203536        if vsp is not None :
     
    35223538            os.environ["VBOX_SDK_PATH"] = vsp
    35233539
     3540    #
     3541    # Set up the shell interpreter context and
     3542    #
    35243543    from vboxapi import VirtualBoxManager
    3525     virtualBoxManager = VirtualBoxManager(style, params)
    3526     ctx = {'global':virtualBoxManager,
    3527            'mgr':virtualBoxManager.mgr,
    3528            'vb':virtualBoxManager.vbox,
    3529            'const':virtualBoxManager.constants,
    3530            'remote':virtualBoxManager.remote,
    3531            'type':virtualBoxManager.type,
    3532            'run': lambda cmd, args: runCommandCb(ctx, cmd, args),
    3533            'guestlambda': lambda uuid, guestLambda, args: runGuestCommandCb(ctx, uuid, guestLambda, args),
    3534            'machById': lambda uuid: machById(ctx, uuid),
    3535            'argsToMach': lambda args: argsToMach(ctx, args),
    3536            'progressBar': lambda p: progressBar(ctx, p),
    3537            'typeInGuest': typeInGuest,
    3538            '_machlist': None,
    3539            'prompt': g_sPrompt,
    3540            'scriptLine': 0,
    3541            'interrupt': False
    3542            }
     3544    oVBoxMgr = VirtualBoxManager(style, params)
     3545    ctx = {
     3546        'global':       oVBoxMgr,
     3547        'vb':           oVBoxMgr.vbox,
     3548        'const':        oVBoxMgr.constants,
     3549        'remote':       oVBoxMgr.remote,
     3550        'type':         oVBoxMgr.type,
     3551        'run':          lambda cmd, args: runCommandCb(ctx, cmd, args),
     3552        'guestlambda': lambda uuid, guestLambda, args: runGuestCommandCb(ctx, uuid, guestLambda, args),
     3553        'machById':    lambda uuid: machById(ctx, uuid),
     3554        'argsToMach':  lambda args: argsToMach(ctx, args),
     3555        'progressBar': lambda p: progressBar(ctx, p),
     3556        'typeInGuest': typeInGuest,
     3557        '_machlist':    None,
     3558        'prompt':      g_sPrompt,
     3559        'scriptLine':  0,
     3560        'interrupt':    False,
     3561    }
    35433562    interpret(ctx)
    3544     virtualBoxManager.deinit()
    3545     del virtualBoxManager
     3563    oVBoxMgr.deinit()
     3564    del oVBoxMgr
    35463565
    35473566if __name__ == '__main__':
    35483567    main(sys.argv)
     3568
  • trunk/src/VBox/Main/glue/vboxapi.py

    r47546 r47979  
     1# -*- coding: utf-8 -*-
     2# $Id$
     3"""
     4VirtualBox Python API Glue.
     5"""
     6
     7__copyright__ = \
    18"""
    29Copyright (C) 2009-2013 Oracle Corporation
     
    1017hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
    1118"""
    12 
     19__version__ = "$Revision$"
     20
     21
     22# Note! To set Python bitness on OSX use 'export VERSIONER_PYTHON_PREFER_32_BIT=yes'
     23
     24
     25# Standard Python imports.
    1326import sys, os
    1427import traceback
    1528
    16 # To set Python bitness on OSX use 'export VERSIONER_PYTHON_PREFER_32_BIT=yes'
    17 
     29
     30#
     31# Globals, environment and sys.path changes.
     32#
    1833VBoxBinDir = os.environ.get("VBOX_PROGRAM_PATH", None)
    1934VBoxSdkDir = os.environ.get("VBOX_SDK_PATH", None)
     
    3146sys.path.append(VBoxBinDir)
    3247
     48
     49#
     50# Import the generated VirtualBox constants.
     51#
    3352from VirtualBox_constants import VirtualBoxReflectionInfo
    3453
    35 class PerfCollector:
     54
     55class PerfCollector(object):
    3656    """ This class provides a wrapper over IPerformanceCollector in order to
    3757    get more 'pythonic' interface.
     
    107127        return out
    108128
     129#
     130# Attribute hacks.
     131#
    109132def ComifyName(name):
    110133    return name[0].capitalize()+name[1:]
    111134
    112 _COMForward = { 'getattr' : None,
    113                 'setattr' : None}
     135
     136## This is for saving the original DispatchBaseClass __getattr__ and __setattr__
     137#  method references.
     138_g_dCOMForward = {
     139    'getattr': None,
     140    'setattr': None,
     141}
    114142
    115143def CustomGetAttr(self, attr):
     
    124152            return getattr(self, k)
    125153    try:
    126         return _COMForward['getattr'](self, ComifyName(attr))
     154        return _g_dCOMForward['getattr'](self, ComifyName(attr))
    127155    except AttributeError:
    128         return _COMForward['getattr'](self, attr)
     156        return _g_dCOMForward['getattr'](self, attr)
    129157
    130158def CustomSetAttr(self, attr, value):
    131159    try:
    132         return _COMForward['setattr'](self, ComifyName(attr), value)
     160        return _g_dCOMForward['setattr'](self, ComifyName(attr), value)
    133161    except AttributeError:
    134         return _COMForward['setattr'](self, attr, value)
    135 
    136 class PlatformMSCOM:
    137     # Class to fake access to constants in style of foo.bar.boo
    138     class ConstantFake:
     162        return _g_dCOMForward['setattr'](self, attr, value)
     163
     164
     165
     166class PlatformBase(object):
     167    """
     168    Base class for the platform specific code.
     169    """
     170
     171    def __init__(self, aoParams):
     172        _ = aoParams;
     173
     174    def getVirtualBox(self):
     175        """
     176        Gets a the IVirtualBox singleton.
     177        """
     178        return None;
     179
     180    def getSessionObject(self, oIVBox):
     181        """
     182        Get a session object that can be used for opening machine sessions.
     183
     184        The oIVBox parameter is an getVirtualBox() return value, i.e. an
     185        IVirtualBox reference.
     186
     187        See also openMachineSession.
     188        """
     189        _ = oIVBox;
     190        return None;
     191
     192    def getType(self):
     193        """ Returns the platform type (class name sans 'Platform'). """
     194        return None;
     195
     196    def isRemote(self):
     197        """
     198        Returns True if remote (web services) and False if local (COM/XPCOM).
     199        """
     200        return False
     201
     202    def getArray(self, oInterface, sAttrib):
     203        """
     204        Retrives the value of the array attribute 'sAttrib' from
     205        interface 'oInterface'.
     206
     207        This is for hiding platform specific differences in attributes
     208        returning arrays.
     209        """
     210        _ = oInterface;
     211        _ = sAttrib;
     212        return None;
     213
     214    def initPerThread(self):
     215        """
     216        Does backend specific initialization for the calling thread.
     217        """
     218        return True;
     219
     220    def deinitPerThread(self):
     221        """
     222        Does backend specific uninitialization for the calling thread.
     223        """
     224        return True;
     225
     226    def createListener(self, oImplClass, dArgs):
     227        """
     228        Instantiates and wraps an active event listener class so it can be
     229        passed to an event source for registration.
     230
     231        oImplClass is a class (type, not instance) which implements
     232        IEventListener.
     233
     234        dArgs is a dictionary with string indexed variables.  This may be
     235        modified by the method to pass platform specific parameters. Can
     236        be None.
     237
     238        This currently only works on XPCOM.  COM support is not possible due to
     239        shortcuts taken in the COM bridge code, which is not under our control.
     240        Use passive listeners for COM and web services.
     241        """
     242        _ = oImplClass;
     243        _ = dArgs;
     244        raise Exception("No active listeners for this platform");
     245        return None;
     246
     247    def waitForEvents(self, cMsTimeout):
     248        """
     249        Wait for events to arrive and process them.
     250
     251        The timeout (cMsTimeout) is in milliseconds for how long to wait for
     252        events to arrive.  A negative value means waiting for ever, while 0
     253        does not wait at all.
     254
     255        Returns 0 if events was processed.
     256        Returns 1 if timed out or interrupted in some way.
     257        Returns 2 on error (like not supported for web services).
     258
     259        Raises an exception if the calling thread is not the main thread (the one
     260        that initialized VirtualBoxManager) or if the time isn't an integer.
     261        """
     262        _ = cMsTimeout;
     263        return 2;
     264
     265    def interruptWaitEvents(self):
     266        """
     267        Interrupt a waitForEvents call.
     268        This is normally called from a worker thread to wake up the main thread.
     269
     270        Returns True on success, False on failure.
     271        """
     272        return False;
     273
     274    def deinit(self):
     275        """
     276        Unitializes the platform specific backend.
     277        """
     278        return None;
     279
     280    def queryInterface(self, oIUnknown, sClassName):
     281        """
     282        IUnknown::QueryInterface wrapper.
     283
     284        oIUnknown is who to ask.
     285        sClassName is the name of the interface we're asking for.
     286        """
     287        return None;
     288
     289
     290class PlatformMSCOM(PlatformBase):
     291    """
     292    Platform specific code for MS COM.
     293    """
     294
     295    ## @name VirtualBox COM Typelib definitions (should be generate)
     296    #
     297    # @remarks Must be updated when the corresponding VirtualBox.xidl bits
     298    #          are changed.  Fortunately this isn't very often.
     299    # @{
     300    VBOX_TLB_GUID  = '{D7569351-1750-46F0-936E-BD127D5BC264}'
     301    VBOX_TLB_LCID  = 0
     302    VBOX_TLB_MAJOR = 1
     303    VBOX_TLB_MINOR = 3
     304    ## @}
     305
     306
     307    class ConstantFake(object):
     308        """ Class to fake access to constants in style of foo.bar.boo """
     309
    139310        def __init__(self, parent, name):
    140311            self.__dict__['_parent'] = parent
     
    193364                    return self.__dict__['_rootFake'].__getattr__(a)
    194365
    195     VBOX_TLB_GUID  = '{D7569351-1750-46F0-936E-BD127D5BC264}'
    196     VBOX_TLB_LCID  = 0
    197     VBOX_TLB_MAJOR = 1
    198     VBOX_TLB_MINOR = 3
    199 
    200     def __init__(self, params):
     366    def __init__(self, dParams):
     367        PlatformBase.__init__(self, dParams);
     368
     369        #
     370        # Since the code runs on all platforms, we have to do a lot of
     371        # importing here instead of at the top of the file where it's normally located.
     372        #
    201373        from win32com import universal
    202374        from win32com.client import gencache, DispatchBaseClass
     
    208380        from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess
    209381        import threading
    210         pid = GetCurrentProcess()
     382
     383        pid      = GetCurrentProcess()
    211384        self.tid = GetCurrentThreadId()
    212385        handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS)
    213386        self.handles = []
    214387        self.handles.append(handle)
    215         _COMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__']
    216         DispatchBaseClass.__dict__['__getattr__'] = CustomGetAttr
    217         _COMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__']
    218         DispatchBaseClass.__dict__['__setattr__'] = CustomSetAttr
     388
     389        # Hack the COM dispatcher base class so we can modify method and
     390        # attribute names to match those in xpcom.
     391        if _g_dCOMForward['setattr'] is None:
     392            _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__']
     393            DispatchBaseClass.__dict__['__getattr__'] = CustomGetAttr
     394            _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__']
     395            DispatchBaseClass.__dict__['__setattr__'] = CustomSetAttr
     396
     397        # Hack the exception base class so the users doesn't need to check for
     398        # XPCOM or COM and do different things.
     399        ## @todo
     400
     401
    219402        win32com.client.gencache.EnsureDispatch('VirtualBox.Session')
    220403        win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox')
     404
    221405        self.oIntCv = threading.Condition()
    222406        self.fInterrupted = False;
    223407
    224     def getSessionObject(self, vbox):
     408        _ = dParams;
     409
     410    def getSessionObject(self, oIVBox):
     411        _ = oIVBox
    225412        import win32com
    226413        from win32com.client import Dispatch
     
    235422        return 'MSCOM'
    236423
    237     def getRemote(self):
    238         return False
    239 
    240     def getArray(self, obj, field):
    241         return obj.__getattr__(field)
     424    def getArray(self, oInterface, sAttrib):
     425        return oInterface.__getattr__(sAttrib)
    242426
    243427    def initPerThread(self):
     
    249433        pythoncom.CoUninitialize()
    250434
    251     def createListener(self, impl, arg):
     435    def createListener(self, oImplClass, dArgs):
    252436        if True:
    253437            raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() '
     
    256440        # Did this code ever really work?
    257441        d = {}
    258         d['BaseClass'] = impl
    259         d['arg'] = arg
    260         d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID
     442        d['BaseClass'] = oImplClass
     443        d['dArgs']     = dArgs
     444        d['tlb_guid']  = PlatformMSCOM.VBOX_TLB_GUID
    261445        d['tlb_major'] = PlatformMSCOM.VBOX_TLB_MAJOR
    262446        d['tlb_minor'] = PlatformMSCOM.VBOX_TLB_MINOR
     
    275459        # capitalized version of listener method
    276460        str += "   HandleEvent=BaseClass.handleEvent\n"
    277         str += "   def __init__(self): BaseClass.__init__(self, arg)\n"
     461        str += "   def __init__(self): BaseClass.__init__(self, dArgs)\n"
    278462        str += "result = win32com.server.util.wrap(ListenerImpl())\n"
    279         exec (str, d, d)
     463        exec(str, d, d)
    280464        return d['result']
    281465
     
    320504    def interruptWaitEvents(self):
    321505        """
    322         Basically a python implementation of EventQueue::postEvent().
     506        Basically a python implementation of NativeEventQueue::postEvent().
    323507
    324508        The magic value must be in sync with the C++ implementation or this
     
    350534        pass
    351535
    352     def queryInterface(self, obj, className):
     536    def queryInterface(self, oIUnknown, sClassName):
    353537        from win32com.client import CastTo
    354         return CastTo(obj, className)
    355 
    356 class PlatformXPCOM:
    357     def __init__(self, params):
     538        return CastTo(oIUnknown, sClassName)
     539
     540
     541class PlatformXPCOM(PlatformBase):
     542    """
     543    Platform specific code for XPCOM.
     544    """
     545
     546    def __init__(self, dParams):
     547        PlatformBase.__init__(self, dParams);
    358548        sys.path.append(VBoxSdkDir+'/bindings/xpcom/python/')
    359549        import xpcom.vboxxpcom
    360550        import xpcom
    361551        import xpcom.components
    362 
    363     def getSessionObject(self, vbox):
     552        _ = dParams;
     553
     554    def getSessionObject(self, oIVBox):
     555        _ = oIVBox;
    364556        import xpcom.components
    365557        return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
     
    372564        return 'XPCOM'
    373565
    374     def getRemote(self):
    375         return False
    376 
    377     def getArray(self, obj, field):
    378         return obj.__getattr__('get'+ComifyName(field))()
     566    def getArray(self, oInterface, sAttrib):
     567        return oInterface.__getattr__('get'+ComifyName(sAttrib))()
    379568
    380569    def initPerThread(self):
     
    386575        xpcom._xpcom.DetachThread()
    387576
    388     def createListener(self, impl, arg):
     577    def createListener(self, oImplClass, dArgs):
    389578        d = {}
    390         d['BaseClass'] = impl
    391         d['arg'] = arg
     579        d['BaseClass'] = oImplClass
     580        d['dArgs']     = dArgs
    392581        str = ""
    393582        str += "import xpcom.components\n"
    394583        str += "class ListenerImpl(BaseClass):\n"
    395584        str += "   _com_interfaces_ = xpcom.components.interfaces.IEventListener\n"
    396         str += "   def __init__(self): BaseClass.__init__(self, arg)\n"
     585        str += "   def __init__(self): BaseClass.__init__(self, dArgs)\n"
    397586        str += "result = ListenerImpl()\n"
    398587        exec (str, d, d)
     
    411600        xpcom._xpcom.DeinitCOM()
    412601
    413     def queryInterface(self, obj, className):
     602    def queryInterface(self, oIUnknown, sClassName):
    414603        import xpcom.components
    415         return obj.queryInterface(getattr(xpcom.components.interfaces, className))
    416 
    417 class PlatformWEBSERVICE:
    418     def __init__(self, params):
    419         sys.path.append(os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib'))
    420         #import VirtualBox_services
     604        return oIUnknown.queryInterface(getattr(xpcom.components.interfaces, sClassName))
     605
     606
     607class PlatformWEBSERVICE(PlatformBase):
     608    """
     609    VirtualBox Web Services API specific code.
     610    """
     611
     612    def __init__(self, dParams):
     613        PlatformBase.__init__(self, dParams);
     614        # Import web services stuff.  Fix the sys.path the first time.
     615        sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib');
     616        if sWebServLib not in sys.path:
     617            sys.path.append(sWebServLib);
    421618        import VirtualBox_wrappers
    422619        from VirtualBox_wrappers import IWebsessionManager2
    423620
    424         if params is not None:
    425             self.user = params.get("user", "")
    426             self.password = params.get("password", "")
    427             self.url = params.get("url", "")
     621        # Initialize instance variables from parameters.
     622        if dParams is not None:
     623            self.user     = dParams.get("user", "")
     624            self.password = dParams.get("password", "")
     625            self.url      = dParams.get("url", "")
    428626        else:
    429             self.user = ""
     627            self.user     = ""
    430628            self.password = ""
    431             self.url = None
    432         self.vbox = None
    433 
    434     def getSessionObject(self, vbox):
    435         return self.wsmgr.getSessionObject(vbox)
     629            self.url      = None
     630        self.vbox  = None
     631        self.wsmgr = None;
     632
     633    #
     634    # Base class overrides.
     635    #
     636
     637    def getSessionObject(self, oIVBox):
     638        return self.wsmgr.getSessionObject(oIVBox)
    436639
    437640    def getVirtualBox(self):
    438641        return self.connect(self.url, self.user, self.password)
     642
     643    def getType(self):
     644        return 'WEBSERVICE'
     645
     646    def isRemote(self):
     647        """ Returns True if remote VBox host, False if local. """
     648        return True
     649
     650    def getArray(self, oInterface, sAttrib):
     651        return oInterface.__getattr__(sAttrib)
     652
     653    def waitForEvents(self, timeout):
     654        # Webservices cannot do that yet
     655        return 2;
     656
     657    def interruptWaitEvents(self, timeout):
     658        # Webservices cannot do that yet
     659        return False;
     660
     661    def deinit(self):
     662        try:
     663           disconnect()
     664        except:
     665           pass
     666
     667    def queryInterface(self, oIUnknown, sClassName):
     668        d = {}
     669        d['oIUnknown'] = oIUnknown
     670        str = ""
     671        str += "from VirtualBox_wrappers import "+sClassName+"\n"
     672        str += "result = "+sClassName+"(oIUnknown.mgr, oIUnknown.handle)\n"
     673        # wrong, need to test if class indeed implements this interface
     674        exec (str, d, d)
     675        return d['result']
     676
     677    #
     678    # Web service specific methods.
     679    #
    439680
    440681    def connect(self, url, user, passwd):
     
    459700    def disconnect(self):
    460701        if self.vbox is not None and self.wsmgr is not None:
    461                 self.wsmgr.logoff(self.vbox)
    462                 self.vbox = None
    463                 self.wsmgr = None
    464 
    465     def getType(self):
    466         return 'WEBSERVICE'
    467 
    468     def getRemote(self):
    469         return True
    470 
    471     def getArray(self, obj, field):
    472         return obj.__getattr__(field)
    473 
    474     def initPerThread(self):
    475         pass
    476 
    477     def deinitPerThread(self):
    478         pass
    479 
    480     def createListener(self, impl, arg):
    481         raise Exception("no active listeners for webservices")
    482 
    483     def waitForEvents(self, timeout):
    484         # Webservices cannot do that yet
    485         return 2;
    486 
    487     def interruptWaitEvents(self, timeout):
    488         # Webservices cannot do that yet
    489         return False;
    490 
    491     def deinit(self):
    492         try:
    493            disconnect()
    494         except:
    495            pass
    496 
    497     def queryInterface(self, obj, className):
    498         d = {}
    499         d['obj'] = obj
    500         str = ""
    501         str += "from VirtualBox_wrappers import "+className+"\n"
    502         str += "result = "+className+"(obj.mgr, obj.handle)\n"
    503         # wrong, need to test if class indeed implements this interface
    504         exec (str, d, d)
    505         return d['result']
    506 
    507 class SessionManager:
    508     def __init__(self, mgr):
    509         self.mgr = mgr
    510 
    511     def getSessionObject(self, vbox):
    512         return self.mgr.platform.getSessionObject(vbox)
    513 
    514 class VirtualBoxManager:
    515     def __init__(self, style, platparams):
    516         if style is None:
     702            self.wsmgr.logoff(self.vbox)
     703            self.vbox  = None
     704            self.wsmgr = None
     705
     706
     707
     708class VirtualBoxManager(object):
     709    """
     710    VirtualBox API manager class.
     711
     712    The API users will have to instantiate this.  If no parameters are given,
     713    it will default to interface with the VirtualBox running on the local
     714    machine.  sStyle can be None (default), MSCOM, XPCOM or WEBSERVICES.  Most
     715    users will either be specifying None or WEBSERVICES.
     716
     717    The dPlatformParams is an optional dictionary for passing parameters to the
     718    WEBSERVICE backend.
     719    """
     720
     721    def __init__(self, sStyle = None, dPlatformParams = None):
     722        if sStyle is None:
    517723            if sys.platform == 'win32':
    518                 style = "MSCOM"
     724                sStyle = "MSCOM"
    519725            else:
    520                 style = "XPCOM"
    521 
    522 
    523         exec "self.platform = Platform"+style+"(platparams)"
     726                sStyle = "XPCOM"
     727        if sStyle == 'XPCOM':
     728            self.platform = PlatformXPCOM(dPlatformParams);
     729        elif sStyle == 'MSCOM':
     730            self.platform = PlatformMSCOM(dPlatformParams);
     731        elif sStyle == 'WEBSERVICE':
     732            self.platform = PlatformWEBSERVICE(dPlatformParams);
     733        else:
     734            raise Exception('Unknown sStyle=%s' % (sStyle,));
     735        self.style     = sStyle
     736        self.type      = self.platform.getType()
     737        self.remote    = self.platform.isRemote()
    524738        # for webservices, enums are symbolic
    525         self.constants = VirtualBoxReflectionInfo(style == "WEBSERVICE")
    526         self.type = self.platform.getType()
    527         self.remote = self.platform.getRemote()
    528         self.style = style
    529         self.mgr = SessionManager(self)
     739        self.constants = VirtualBoxReflectionInfo(sStyle == "WEBSERVICE")
    530740
    531741        try:
     
    542752            else:
    543753                raise e
    544 
    545     def getArray(self, obj, field):
    546         return self.platform.getArray(obj, field)
    547 
    548     def getVirtualBox(self):
    549         return self.platform.getVirtualBox()
     754        ## @deprecated
     755        # This used to refer to a session manager class with only one method
     756        # called getSessionObject.  The method has moved into this call.
     757        self.mgr = self;
    550758
    551759    def __del__(self):
    552760        self.deinit()
    553761
     762
     763    #
     764    # Wrappers for self.platform methods.
     765    #
     766
     767    def getVirtualBox(self):
     768        """ See PlatformBase::getVirtualBox(). """
     769        return self.platform.getVirtualBox()
     770
     771    def getSessionObject(self, oIVBox):
     772        """ See PlatformBase::getSessionObject(). """
     773        return self.platform.getSessionObject(oIVBox);
     774
     775    def getArray(self, oInterface, sAttrib):
     776        """ See PlatformBase::getArray(). """
     777        return self.platform.getArray(oInterface, sAttrib)
     778
     779    def createListener(self, oImplClass, dArgs = None):
     780        """ See PlatformBase::createListener(). """
     781        return self.platform.createListener(oImplClass, dArgs)
     782
     783    def waitForEvents(self, cMsTimeout):
     784        """ See PlatformBase::waitForEvents(). """
     785        return self.platform.waitForEvents(cMsTimeout)
     786
     787    def interruptWaitEvents(self):
     788        """ See PlatformBase::interruptWaitEvents(). """
     789        return self.platform.interruptWaitEvents()
     790
     791    def queryInterface(self, oIUnknown, sClassName):
     792        """ See PlatformBase::queryInterface(). """
     793        return self.platform.queryInterface(oIUnknown, sClassName)
     794
     795
     796    #
     797    # Init and uninit.
     798    #
     799
     800    def initPerThread(self):
     801        """ See PlatformBase::deinitPerThread(). """
     802        self.platform.initPerThread()
     803
     804    def deinitPerThread(self):
     805        """ See PlatformBase::deinitPerThread(). """
     806        return self.platform.deinitPerThread()
     807
    554808    def deinit(self):
     809        """
     810        For unitializing the manager.
     811        Do not access it after calling this method.
     812        """
    555813        if hasattr(self, "vbox"):
    556814            del self.vbox
     
    559817            self.platform.deinit()
    560818            self.platform = None
    561 
    562     def initPerThread(self):
    563         self.platform.initPerThread()
    564 
    565     def openMachineSession(self, mach, permitSharing = True):
    566          session = self.mgr.getSessionObject(self.vbox)
    567          if permitSharing:
    568              type = self.constants.LockType_Shared
    569          else:
    570              type = self.constants.LockType_Write
    571          mach.lockMachine(session, type)
    572          return session
    573 
    574     def closeMachineSession(self, session):
    575         if session is not None:
    576             session.unlockMachine()
    577 
    578     def deinitPerThread(self):
    579         self.platform.deinitPerThread()
    580 
    581     def createListener(self, impl, arg = None):
    582         return self.platform.createListener(impl, arg)
    583 
    584     def waitForEvents(self, timeout):
    585         """
    586         Wait for events to arrive and process them.
    587 
    588         The timeout is in milliseconds.  A negative value means waiting for
    589         ever, while 0 does not wait at all.
    590 
    591         Returns 0 if events was processed.
    592         Returns 1 if timed out or interrupted in some way.
    593         Returns 2 on error (like not supported for web services).
    594 
    595         Raises an exception if the calling thread is not the main thread (the one
    596         that initialized VirtualBoxManager) or if the time isn't an integer.
    597         """
    598         return self.platform.waitForEvents(timeout)
    599 
    600     def interruptWaitEvents(self):
    601         """
    602         Interrupt a waitForEvents call.
    603         This is normally called from a worker thread.
    604 
    605         Returns True on success, False on failure.
    606         """
    607         return self.platform.interruptWaitEvents()
    608 
    609     def getPerfCollector(self, vbox):
    610         return PerfCollector(self, vbox)
     819        return True;
     820
     821
     822    #
     823    # Utility methods.
     824    #
     825
     826    def openMachineSession(self, oIMachine, fPermitSharing = True):
     827        """
     828        Attemts to open the a session to the machine.
     829        Returns a session object on success.
     830        Raises exception on failure.
     831        """
     832        oSession = self.mgr.getSessionObject(self.vbox);
     833        if fPermitSharing:
     834            type = self.constants.LockType_Shared;
     835        else:
     836            type = self.constants.LockType_Write;
     837        oIMachine.lockMachine(oSession, type);
     838        return oSession;
     839
     840    def closeMachineSession(self, oSession):
     841        """
     842        Closes a session opened by openMachineSession.
     843        Ignores None parameters.
     844        """
     845        if oSession is not None:
     846            oSession.unlockMachine()
     847        return True;
     848
     849    def getPerfCollector(self, oIVBox):
     850        """
     851        Returns a helper class (PerfCollector) for accessing performance
     852        collector goodies.  See PerfCollector for details.
     853        """
     854        return PerfCollector(self, oIVBox)
    611855
    612856    def getBinDir(self):
     
    624868        return VBoxSdkDir
    625869
    626     def queryInterface(self, obj, className):
    627         return self.platform.queryInterface(obj, className)
Note: See TracChangeset for help on using the changeset viewer.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette