Changeset 47979 in vbox
- Timestamp:
- Aug 21, 2013 6:44:35 PM (11 years ago)
- 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 """ 5 VirtualBox Python Shell. 6 7 This program is a simple interactive shell for VirtualBox. You can query 8 information and issue commands from a simple command line. 9 10 It also provides you with examples on how to use VirtualBox's Python API. 11 This shell is even somewhat documented, supports TAB-completion and 12 history if you have Python readline installed. 13 14 Finally, shell allows arbitrary custom extensions, just create 15 .VirtualBox/shexts/ and drop your extensions there. 16 Enjoy. 17 18 P.S. Our apologies for the code quality. 19 """ 20 21 __copyright__ = \ 3 22 """ 4 23 Copyright (C) 2009-2013 Oracle Corporation … … 12 31 hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. 13 32 """ 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 27 35 28 36 import os, sys … … 35 43 from pprint import pprint 36 44 45 46 47 # 48 # Global Variables 49 # 37 50 g_fBatchMode = False 38 51 g_sScriptFile = None … … 47 60 g_sPrompt = "vbox> " 48 61 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 } 62 g_fHasColors = True 63 g_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 58 74 def colored(strg, color): 59 75 """ … … 62 78 if not g_fHasColors: 63 79 return strg 64 col = g_ aTermColors.get(color, None)80 col = g_dTermColors.get(color, None) 65 81 if col: 66 82 return col+str(strg)+'\033[0m' 67 else: 68 return strg 83 return strg 69 84 70 85 if g_fHasReadline: … … 238 253 239 254 def startVm(ctx, mach, vmtype): 240 mgr = ctx['mgr']241 255 vbox = ctx['vb'] 242 256 perf = ctx['perf'] 243 session = mgr.getSessionObject(vbox)257 session = ctx['global'].getSessionObject(vbox) 244 258 progress = mach.launchVMProcess(session, vmtype, "") 245 259 if progressBar(ctx, progress, 100) and int(progress.resultCode) == 0: … … 670 684 try: 671 685 vbox = ctx['vb'] 672 session = ctx[' mgr'].getSessionObject(vbox)686 session = ctx['global'].getSessionObject(vbox) 673 687 mach.lockMachine(session, ctx['global'].constants.LockType_Shared) 674 688 except Exception, e: … … 3471 3485 3472 3486 def main(argv): 3473 style = None 3474 params = None3475 autopath = False3476 script_file = None3487 3488 # 3489 # Parse command line arguments. 3490 # 3477 3491 parse = OptionParser() 3478 3492 parse.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help = "switch on verbose") … … 3495 3509 g_fHasReadline = False 3496 3510 g_sCmd = options.command_line 3511 3512 params = None 3497 3513 if options.opt_line is not None: 3498 3514 params = {} … … 3502 3518 (key, value) = strparam.split('=') 3503 3519 params[key] = value 3504 else:3505 params = None3506 3520 3507 3521 if options.autopath: 3508 3522 cwd = os.getcwd() 3509 3523 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")) ): 3511 3527 vpp = cwd 3512 3528 print "Autodetected VBOX_PROGRAM_PATH as", vpp … … 3516 3532 if vsp is None and os.path.isfile(os.path.join(cwd, "sdk", "bindings", "VirtualBox.xidl")) : 3517 3533 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")) : 3519 3535 vsp = os.path.join(vpp, "sdk") 3520 3536 if vsp is not None : … … 3522 3538 os.environ["VBOX_SDK_PATH"] = vsp 3523 3539 3540 # 3541 # Set up the shell interpreter context and 3542 # 3524 3543 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': False3542 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 } 3543 3562 interpret(ctx) 3544 virtualBoxManager.deinit()3545 del virtualBoxManager3563 oVBoxMgr.deinit() 3564 del oVBoxMgr 3546 3565 3547 3566 if __name__ == '__main__': 3548 3567 main(sys.argv) 3568 -
trunk/src/VBox/Main/glue/vboxapi.py
r47546 r47979 1 # -*- coding: utf-8 -*- 2 # $Id$ 3 """ 4 VirtualBox Python API Glue. 5 """ 6 7 __copyright__ = \ 1 8 """ 2 9 Copyright (C) 2009-2013 Oracle Corporation … … 10 17 hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. 11 18 """ 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. 13 26 import sys, os 14 27 import traceback 15 28 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 # 18 33 VBoxBinDir = os.environ.get("VBOX_PROGRAM_PATH", None) 19 34 VBoxSdkDir = os.environ.get("VBOX_SDK_PATH", None) … … 31 46 sys.path.append(VBoxBinDir) 32 47 48 49 # 50 # Import the generated VirtualBox constants. 51 # 33 52 from VirtualBox_constants import VirtualBoxReflectionInfo 34 53 35 class PerfCollector: 54 55 class PerfCollector(object): 36 56 """ This class provides a wrapper over IPerformanceCollector in order to 37 57 get more 'pythonic' interface. … … 107 127 return out 108 128 129 # 130 # Attribute hacks. 131 # 109 132 def ComifyName(name): 110 133 return name[0].capitalize()+name[1:] 111 134 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 } 114 142 115 143 def CustomGetAttr(self, attr): … … 124 152 return getattr(self, k) 125 153 try: 126 return _ COMForward['getattr'](self, ComifyName(attr))154 return _g_dCOMForward['getattr'](self, ComifyName(attr)) 127 155 except AttributeError: 128 return _ COMForward['getattr'](self, attr)156 return _g_dCOMForward['getattr'](self, attr) 129 157 130 158 def CustomSetAttr(self, attr, value): 131 159 try: 132 return _ COMForward['setattr'](self, ComifyName(attr), value)160 return _g_dCOMForward['setattr'](self, ComifyName(attr), value) 133 161 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 166 class 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 290 class 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 139 310 def __init__(self, parent, name): 140 311 self.__dict__['_parent'] = parent … … 193 364 return self.__dict__['_rootFake'].__getattr__(a) 194 365 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 # 201 373 from win32com import universal 202 374 from win32com.client import gencache, DispatchBaseClass … … 208 380 from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess 209 381 import threading 210 pid = GetCurrentProcess() 382 383 pid = GetCurrentProcess() 211 384 self.tid = GetCurrentThreadId() 212 385 handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS) 213 386 self.handles = [] 214 387 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 219 402 win32com.client.gencache.EnsureDispatch('VirtualBox.Session') 220 403 win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') 404 221 405 self.oIntCv = threading.Condition() 222 406 self.fInterrupted = False; 223 407 224 def getSessionObject(self, vbox): 408 _ = dParams; 409 410 def getSessionObject(self, oIVBox): 411 _ = oIVBox 225 412 import win32com 226 413 from win32com.client import Dispatch … … 235 422 return 'MSCOM' 236 423 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) 242 426 243 427 def initPerThread(self): … … 249 433 pythoncom.CoUninitialize() 250 434 251 def createListener(self, impl, arg):435 def createListener(self, oImplClass, dArgs): 252 436 if True: 253 437 raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() ' … … 256 440 # Did this code ever really work? 257 441 d = {} 258 d['BaseClass'] = impl259 d[' arg'] = arg260 d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID442 d['BaseClass'] = oImplClass 443 d['dArgs'] = dArgs 444 d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID 261 445 d['tlb_major'] = PlatformMSCOM.VBOX_TLB_MAJOR 262 446 d['tlb_minor'] = PlatformMSCOM.VBOX_TLB_MINOR … … 275 459 # capitalized version of listener method 276 460 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" 278 462 str += "result = win32com.server.util.wrap(ListenerImpl())\n" 279 exec 463 exec(str, d, d) 280 464 return d['result'] 281 465 … … 320 504 def interruptWaitEvents(self): 321 505 """ 322 Basically a python implementation of EventQueue::postEvent().506 Basically a python implementation of NativeEventQueue::postEvent(). 323 507 324 508 The magic value must be in sync with the C++ implementation or this … … 350 534 pass 351 535 352 def queryInterface(self, o bj, className):536 def queryInterface(self, oIUnknown, sClassName): 353 537 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 541 class PlatformXPCOM(PlatformBase): 542 """ 543 Platform specific code for XPCOM. 544 """ 545 546 def __init__(self, dParams): 547 PlatformBase.__init__(self, dParams); 358 548 sys.path.append(VBoxSdkDir+'/bindings/xpcom/python/') 359 549 import xpcom.vboxxpcom 360 550 import xpcom 361 551 import xpcom.components 362 363 def getSessionObject(self, vbox): 552 _ = dParams; 553 554 def getSessionObject(self, oIVBox): 555 _ = oIVBox; 364 556 import xpcom.components 365 557 return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance() … … 372 564 return 'XPCOM' 373 565 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))() 379 568 380 569 def initPerThread(self): … … 386 575 xpcom._xpcom.DetachThread() 387 576 388 def createListener(self, impl, arg):577 def createListener(self, oImplClass, dArgs): 389 578 d = {} 390 d['BaseClass'] = impl391 d[' arg'] = arg579 d['BaseClass'] = oImplClass 580 d['dArgs'] = dArgs 392 581 str = "" 393 582 str += "import xpcom.components\n" 394 583 str += "class ListenerImpl(BaseClass):\n" 395 584 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" 397 586 str += "result = ListenerImpl()\n" 398 587 exec (str, d, d) … … 411 600 xpcom._xpcom.DeinitCOM() 412 601 413 def queryInterface(self, o bj, className):602 def queryInterface(self, oIUnknown, sClassName): 414 603 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 607 class 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); 421 618 import VirtualBox_wrappers 422 619 from VirtualBox_wrappers import IWebsessionManager2 423 620 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", "") 428 626 else: 429 self.user = ""627 self.user = "" 430 628 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) 436 639 437 640 def getVirtualBox(self): 438 641 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 # 439 680 440 681 def connect(self, url, user, passwd): … … 459 700 def disconnect(self): 460 701 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 708 class 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: 517 723 if sys.platform == 'win32': 518 s tyle = "MSCOM"724 sStyle = "MSCOM" 519 725 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() 524 738 # 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") 530 740 531 741 try: … … 542 752 else: 543 753 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; 550 758 551 759 def __del__(self): 552 760 self.deinit() 553 761 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 554 808 def deinit(self): 809 """ 810 For unitializing the manager. 811 Do not access it after calling this method. 812 """ 555 813 if hasattr(self, "vbox"): 556 814 del self.vbox … … 559 817 self.platform.deinit() 560 818 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) 611 855 612 856 def getBinDir(self): … … 624 868 return VBoxSdkDir 625 869 626 def queryInterface(self, obj, className):627 return self.platform.queryInterface(obj, className)
Note:
See TracChangeset
for help on using the changeset viewer.