Changeset 54057 in vbox
- Timestamp:
- Feb 2, 2015 12:35:10 PM (10 years ago)
- File:
-
- 1 edited
-
trunk/src/VBox/Main/glue/vboxapi.py (modified) (74 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/VBox/Main/glue/vboxapi.py
r51415 r54057 6 6 7 7 __copyright__ = \ 8 """9 Copyright (C) 2009-2013Oracle Corporation10 11 This file is part of VirtualBox Open Source Edition (OSE), as12 available from http://www.virtualbox.org. This file is free software;13 you can redistribute it and/or modify it under the terms of the GNU14 General Public License (GPL) as published by the Free Software15 Foundation, in version 2 as it comes in the "COPYING" file of the16 VirtualBox OSE distribution. VirtualBox OSE is distributed in the17 hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.18 """8 """ 9 Copyright (C) 2009-2015 Oracle Corporation 10 11 This file is part of VirtualBox Open Source Edition (OSE), as 12 available from http://www.virtualbox.org. This file is free software; 13 you can redistribute it and/or modify it under the terms of the GNU 14 General Public License (GPL) as published by the Free Software 15 Foundation, in version 2 as it comes in the "COPYING" file of the 16 VirtualBox OSE distribution. VirtualBox OSE is distributed in the 17 hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. 18 """ 19 19 __version__ = "$Revision$" 20 20 … … 24 24 25 25 # Standard Python imports. 26 import sys, os 26 import os 27 import sys 27 28 import traceback 28 29 30 31 if sys.version_info >= (3, 0): 32 xrange = range 33 long = int 34 import builtins 35 print_ = getattr(builtins, 'print', None) 36 elif sys.version_info >= (2, 6): 37 import __builtin__ 38 print_ = getattr(__builtin__, 'print', None) 39 else: 40 def print_(*args, **kwargs): 41 """The new-style print function for Python 2.4 and 2.5.""" 42 fp = kwargs.pop("file", sys.stdout) 43 if fp is None: 44 return 45 46 def write(data): 47 if not isinstance(data, basestring): 48 data = str(data) 49 # If the file has an encoding, encode unicode with it. 50 if isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None: 51 errors = getattr(fp, "errors", None) 52 if errors is None: 53 errors = "strict" 54 data = data.encode(fp.encoding, errors) 55 fp.write(data) 56 57 want_unicode = False 58 sep = kwargs.pop("sep", None) 59 if sep is not None: 60 if isinstance(sep, unicode): 61 want_unicode = True 62 elif not isinstance(sep, str): 63 raise TypeError("sep must be None or a string") 64 end = kwargs.pop("end", None) 65 if end is not None: 66 if isinstance(end, unicode): 67 want_unicode = True 68 elif not isinstance(end, str): 69 raise TypeError("end must be None or a string") 70 if kwargs: 71 raise TypeError("invalid keyword arguments to print()") 72 if not want_unicode: 73 for arg in args: 74 if isinstance(arg, unicode): 75 want_unicode = True 76 break 77 if want_unicode: 78 newline = unicode("\n") 79 space = unicode(" ") 80 else: 81 newline = "\n" 82 space = " " 83 if sep is None: 84 sep = space 85 if end is None: 86 end = newline 87 for i, arg in enumerate(args): 88 if i: 89 write(sep) 90 write(arg) 91 write(end) 29 92 30 93 # … … 38 101 VBoxBinDir = "%VBOX_INSTALL_PATH%" 39 102 else: 40 VBoxBinDir = os.path.abspath(VBoxBinDir) ;103 VBoxBinDir = os.path.abspath(VBoxBinDir) 41 104 42 105 if VBoxSdkDir is None: … … 44 107 VBoxSdkDir = "%VBOX_SDK_PATH%" 45 108 else: 46 VBoxSdkDir = os.path.abspath(VBoxSdkDir) ;109 VBoxSdkDir = os.path.abspath(VBoxSdkDir) 47 110 48 111 os.environ["VBOX_PROGRAM_PATH"] = VBoxBinDir … … 54 117 # Import the generated VirtualBox constants. 55 118 # 56 from VirtualBox_constants import VirtualBoxReflectionInfo119 from .VirtualBox_constants import VirtualBoxReflectionInfo 57 120 58 121 … … 110 173 if self.isMscom: 111 174 (values, names, objects, names_out, objects_out, units, scales, sequence_numbers, 112 indices, lengths) = self.collector.queryMetricsData(names, objects)175 indices, lengths) = self.collector.queryMetricsData(names, objects) 113 176 else: 114 177 (values, names_out, objects_out, units, scales, sequence_numbers, 115 indices, lengths) = self.collector.queryMetricsData(names, objects)178 indices, lengths) = self.collector.queryMetricsData(names, objects) 116 179 out = [] 117 180 for i in xrange(0, len(names_out)): … … 122 185 fmt = '%d %s' 123 186 out.append({ 124 'name':str(names_out[i]), 125 'object':str(objects_out[i]), 126 'unit':str(units[i]), 127 'scale':scale, 128 'values':[int(values[j]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))], 129 'values_as_string':'['+', '.join([fmt % (int(values[j])/scale, units[i]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))])+']' 187 'name': str(names_out[i]), 188 'object': str(objects_out[i]), 189 'unit': str(units[i]), 190 'scale': scale, 191 'values': [int(values[j]) for j in xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))], 192 'values_as_string': '[' + ', '.join([fmt % (int(values[j]) / scale, units[i]) for j in 193 xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))]) + ']' 130 194 }) 131 195 return out 196 132 197 133 198 # … … 145 210 } 146 211 212 147 213 def _CustomGetAttr(self, sAttr): 148 214 """ Our getattr replacement for DispatchBaseClass. """ 149 215 # Fastpath. 150 oRet = self.__class__.__dict__.get(sAttr) ;151 if oRet !=None:152 return oRet ;216 oRet = self.__class__.__dict__.get(sAttr) 217 if oRet is not None: 218 return oRet 153 219 154 220 # Try case-insensitivity workaround for class attributes (COM methods). 155 sAttrLower = sAttr.lower() ;156 for sKeyin self.__class__.__dict__.keys():157 if sKey.lower() == sAttrLower:158 se lf.__class__.__dict__[sAttr] = self.__class__.__dict__[sKey]159 return getattr(self, sKey)221 sAttrLower = sAttr.lower() 222 for k in self.__class__.__dict__.keys(): 223 if k.lower() == sAttrLower: 224 setattr(self.__class__, sAttr, self.__class__.__dict__[k]) 225 return getattr(self, k) 160 226 161 227 # Slow path. … … 164 230 except AttributeError: 165 231 return _g_dCOMForward['getattr'](self, sAttr) 232 166 233 167 234 def _CustomSetAttr(self, sAttr, oValue): … … 173 240 174 241 175 176 242 class PlatformBase(object): 177 243 """ … … 180 246 181 247 def __init__(self, aoParams): 182 _ = aoParams ;248 _ = aoParams 183 249 184 250 def getVirtualBox(self): … … 186 252 Gets a the IVirtualBox singleton. 187 253 """ 188 return None ;254 return None 189 255 190 256 def getSessionObject(self, oIVBox): … … 197 263 See also openMachineSession. 198 264 """ 199 _ = oIVBox ;200 return None ;265 _ = oIVBox 266 return None 201 267 202 268 def getType(self): 203 269 """ Returns the platform type (class name sans 'Platform'). """ 204 return None ;270 return None 205 271 206 272 def isRemote(self): … … 218 284 returning arrays. 219 285 """ 220 _ = oInterface ;221 _ = sAttrib ;222 return None ;286 _ = oInterface 287 _ = sAttrib 288 return None 223 289 224 290 def initPerThread(self): … … 226 292 Does backend specific initialization for the calling thread. 227 293 """ 228 return True ;294 return True 229 295 230 296 def deinitPerThread(self): … … 232 298 Does backend specific uninitialization for the calling thread. 233 299 """ 234 return True ;300 return True 235 301 236 302 def createListener(self, oImplClass, dArgs): … … 250 316 Use passive listeners for COM and web services. 251 317 """ 252 _ = oImplClass; 253 _ = dArgs; 254 raise Exception("No active listeners for this platform"); 255 return None; 318 _ = oImplClass 319 _ = dArgs 320 raise Exception("No active listeners for this platform") 256 321 257 322 def waitForEvents(self, cMsTimeout): … … 270 335 that initialized VirtualBoxManager) or if the time isn't an integer. 271 336 """ 272 _ = cMsTimeout ;273 return 2 ;337 _ = cMsTimeout 338 return 2 274 339 275 340 def interruptWaitEvents(self): … … 280 345 Returns True on success, False on failure. 281 346 """ 282 return False ;347 return False 283 348 284 349 def deinit(self): … … 286 351 Unitializes the platform specific backend. 287 352 """ 288 return None ;353 return None 289 354 290 355 def queryInterface(self, oIUnknown, sClassName): … … 295 360 sClassName is the name of the interface we're asking for. 296 361 """ 297 return None ;362 return None 298 363 299 364 # … … 305 370 Returns the COM status code from the VBox API given exception. 306 371 """ 307 return None ;372 return None 308 373 309 374 def xcptIsDeadInterface(self, oXcpt): … … 311 376 Returns True if the exception indicates that the interface is dead, False if not. 312 377 """ 313 return False ;378 return False 314 379 315 380 def xcptIsEqual(self, oXcpt, hrStatus): … … 324 389 """ 325 390 try: 326 hrXcpt = self.xcptGetStatus(oXcpt) ;391 hrXcpt = self.xcptGetStatus(oXcpt) 327 392 except AttributeError: 328 return False ;393 return False 329 394 if hrXcpt == hrStatus: 330 return True ;395 return True 331 396 332 397 # Fudge for 32-bit signed int conversion. 333 if hrStatus > 0x7fffffff andhrStatus <= 0xffffffff and hrXcpt < 0:398 if 0x7fffffff < hrStatus <= 0xffffffff and hrXcpt < 0: 334 399 if (hrStatus - 0x100000000) == hrXcpt: 335 return True ;336 return False ;400 return True 401 return False 337 402 338 403 def xcptGetMessage(self, oXcpt): … … 342 407 Raises exception if oXcpt isn't our kind of exception object. 343 408 """ 344 return None ;409 return None 345 410 346 411 def xcptGetBaseXcpt(self): … … 348 413 Returns the base exception class. 349 414 """ 350 return None ;415 return None 351 416 352 417 def xcptSetupConstants(self, oDst): … … 354 419 Copy/whatever all error constants onto oDst. 355 420 """ 356 return oDst ;421 return oDst 357 422 358 423 @staticmethod … … 363 428 for sAttr in dir(oSrc): 364 429 if sAttr[0].isupper() and (sAttr[1].isupper() or sAttr[1] == '_'): 365 oAttr = getattr(oSrc, sAttr) ;430 oAttr = getattr(oSrc, sAttr) 366 431 if type(oAttr) is int: 367 setattr(oDst, sAttr, oAttr); 368 return oDst; 369 432 setattr(oDst, sAttr, oAttr) 433 return oDst 370 434 371 435 … … 380 444 # are changed. Fortunately this isn't very often. 381 445 # @{ 382 VBOX_TLB_GUID = '{D7569351-1750-46F0-936E-BD127D5BC264}'383 VBOX_TLB_LCID = 0446 VBOX_TLB_GUID = '{D7569351-1750-46F0-936E-BD127D5BC264}' 447 VBOX_TLB_LCID = 0 384 448 VBOX_TLB_MAJOR = 1 385 449 VBOX_TLB_MINOR = 3 … … 387 451 388 452 def __init__(self, dParams): 389 PlatformBase.__init__(self, dParams) ;453 PlatformBase.__init__(self, dParams) 390 454 391 455 # … … 404 468 import threading 405 469 406 self.winerror = winerror ;407 408 pid = GetCurrentProcess()470 self.winerror = winerror 471 472 pid = GetCurrentProcess() 409 473 self.tid = GetCurrentThreadId() 410 474 handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS) … … 416 480 if _g_dCOMForward['setattr'] is None: 417 481 _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__'] 418 DispatchBaseClass.__dict__['__getattr__'] = _CustomGetAttr419 482 _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__'] 420 DispatchBaseClass.__dict__['__setattr__'] = _CustomSetAttr 483 setattr(DispatchBaseClass, '__getattr__', _CustomGetAttr) 484 setattr(DispatchBaseClass, '__setattr__', _CustomSetAttr) 421 485 422 486 # Hack the exception base class so the users doesn't need to check for … … 428 492 # versioning rules). 429 493 # 430 self.flushGenPyCache(win32com.client.gencache) ;431 win32com.client.gencache.EnsureDispatch('VirtualBox.Session') ;432 win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') ;494 self.flushGenPyCache(win32com.client.gencache) 495 win32com.client.gencache.EnsureDispatch('VirtualBox.Session') 496 win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox') 433 497 434 498 self.oIntCv = threading.Condition() 435 self.fInterrupted = False ;436 437 _ = dParams ;499 self.fInterrupted = False 500 501 _ = dParams 438 502 439 503 def flushGenPyCache(self, oGenCache): … … 451 515 # need to cover it as well.) 452 516 # 453 sName = oGenCache.GetGeneratedFileName(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID,454 self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR);455 sGenPath = oGenCache.GetGeneratePath() ;517 sName = oGenCache.GetGeneratedFileName(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, 518 self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR) 519 sGenPath = oGenCache.GetGeneratePath() 456 520 if len(sName) > 36 and len(sGenPath) > 5: 457 sTypelibPath = os.path.join(sGenPath, sName) ;521 sTypelibPath = os.path.join(sGenPath, sName) 458 522 if os.path.isdir(sTypelibPath): 459 import shutil ;460 shutil.rmtree(sTypelibPath, ignore_errors = True);523 import shutil 524 shutil.rmtree(sTypelibPath, ignore_errors=True) 461 525 462 526 # 463 527 # Ensure that our typelib is valid. 464 528 # 465 return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR) ;529 return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR) 466 530 467 531 def getSessionObject(self, oIVBox): … … 494 558 raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() ' 495 559 'returns new gateway objects all the time, thus breaking EventQueue ' 496 'assumptions about the listener interface pointer being constants between calls ') ;560 'assumptions about the listener interface pointer being constants between calls ') 497 561 # Did this code ever really work? 498 562 d = {} 499 563 d['BaseClass'] = oImplClass 500 d['dArgs'] = dArgs501 d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID564 d['dArgs'] = dArgs 565 d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID 502 566 d['tlb_major'] = PlatformMSCOM.VBOX_TLB_MAJOR 503 567 d['tlb_minor'] = PlatformMSCOM.VBOX_TLB_MINOR 504 str = ""505 str += "import win32com.server.util\n"506 str += "import pythoncom\n"507 508 str += "class ListenerImpl(BaseClass):\n"509 str += " _com_interfaces_ = ['IEventListener']\n"510 str += " _typelib_guid_ = tlb_guid\n"511 str += " _typelib_version_ = tlb_major, tlb_minor\n"512 str += " _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n"568 str_ = "" 569 str_ += "import win32com.server.util\n" 570 str_ += "import pythoncom\n" 571 572 str_ += "class ListenerImpl(BaseClass):\n" 573 str_ += " _com_interfaces_ = ['IEventListener']\n" 574 str_ += " _typelib_guid_ = tlb_guid\n" 575 str_ += " _typelib_version_ = tlb_major, tlb_minor\n" 576 str_ += " _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n" 513 577 # Maybe we'd better implement Dynamic invoke policy, to be more flexible here 514 str += " _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"578 str_ += " _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n" 515 579 516 580 # capitalized version of listener method 517 str += " HandleEvent=BaseClass.handleEvent\n"518 str += " def __init__(self): BaseClass.__init__(self, dArgs)\n"519 str += "result = win32com.server.util.wrap(ListenerImpl())\n"520 exec(str , d, d)581 str_ += " HandleEvent=BaseClass.handleEvent\n" 582 str_ += " def __init__(self): BaseClass.__init__(self, dArgs)\n" 583 str_ += "result = win32com.server.util.wrap(ListenerImpl())\n" 584 exec(str_, d, d) 521 585 return d['result'] 522 586 … … 525 589 from win32event import INFINITE 526 590 from win32event import MsgWaitForMultipleObjects, \ 527 QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0591 QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0 528 592 from pythoncom import PumpWaitingMessages 529 593 import types 530 594 531 if not isinstance(timeout, types.IntType):595 if not isinstance(timeout, int): 532 596 raise TypeError("The timeout argument is not an integer") 533 if (self.tid != GetCurrentThreadId()):597 if self.tid != GetCurrentThreadId(): 534 598 raise Exception("wait for events from the same thread you inited!") 535 599 … … 539 603 cMsTimeout = timeout 540 604 rc = MsgWaitForMultipleObjects(self.handles, 0, cMsTimeout, QS_ALLINPUT) 541 if rc >= WAIT_OBJECT_0 and rc < WAIT_OBJECT_0+len(self.handles):605 if WAIT_OBJECT_0 <= rc < WAIT_OBJECT_0 + len(self.handles): 542 606 # is it possible? 543 rc = 2 ;544 elif rc ==WAIT_OBJECT_0 + len(self.handles):607 rc = 2 608 elif rc == WAIT_OBJECT_0 + len(self.handles): 545 609 # Waiting messages 546 610 PumpWaitingMessages() 547 rc = 0 ;611 rc = 0 548 612 else: 549 613 # Timeout 550 rc = 1 ;614 rc = 1 551 615 552 616 # check for interruption … … 554 618 if self.fInterrupted: 555 619 self.fInterrupted = False 556 rc = 1 ;620 rc = 1 557 621 self.oIntCv.release() 558 622 559 return rc ;623 return rc 560 624 561 625 def interruptWaitEvents(self): … … 571 635 from win32api import PostThreadMessage 572 636 from win32con import WM_USER 637 573 638 self.oIntCv.acquire() 574 639 self.fInterrupted = True … … 577 642 PostThreadMessage(self.tid, WM_USER, None, 0xf241b819) 578 643 except: 579 return False ;580 return True ;644 return False 645 return True 581 646 582 647 def deinit(self): … … 585 650 586 651 for h in self.handles: 587 if h is not None:588 CloseHandle(h)652 if h is not None: 653 CloseHandle(h) 589 654 self.handles = None 590 655 pythoncom.CoUninitialize() … … 600 665 hrXcpt = oXcpt.hresult 601 666 if hrXcpt == self.winerror.DISP_E_EXCEPTION: 602 try: hrXcpt = oXcpt.excepinfo[5]; 603 except: pass; 604 return hrXcpt; 667 try: 668 hrXcpt = oXcpt.excepinfo[5] 669 except: 670 pass 671 return hrXcpt 605 672 606 673 def xcptIsDeadInterface(self, oXcpt): 607 674 return self.xcptGetStatus(oXcpt) in [ 608 0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE. 609 0x800706be, -2147023170, # RPC_S_CALL_FAILED. 610 0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE. 611 0x80010108, -2147417848, # RPC_E_DISCONNECTED. 612 0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF 613 ]; 614 675 0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE. 676 0x800706be, -2147023170, # RPC_S_CALL_FAILED. 677 0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE. 678 0x80010108, -2147417848, # RPC_E_DISCONNECTED. 679 0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF 680 ] 615 681 616 682 def xcptGetMessage(self, oXcpt): … … 618 684 try: 619 685 if len(oXcpt.excepinfo) >= 3: 620 sRet = oXcpt.excepinfo[2] ;686 sRet = oXcpt.excepinfo[2] 621 687 if len(sRet) > 0: 622 return sRet[0:] ;688 return sRet[0:] 623 689 except: 624 pass ;690 pass 625 691 if hasattr(oXcpt, 'strerror'): 626 692 try: 627 sRet = oXcpt.strerror ;693 sRet = oXcpt.strerror 628 694 if len(sRet) > 0: 629 return sRet ;695 return sRet 630 696 except: 631 pass ;632 return None ;697 pass 698 return None 633 699 634 700 def xcptGetBaseXcpt(self): 635 import pythoncom; 636 return pythoncom.com_error; 701 import pythoncom 702 703 return pythoncom.com_error 637 704 638 705 def xcptSetupConstants(self, oDst): 639 import winerror; 640 oDst = self.xcptCopyErrorConstants(oDst, winerror); 706 import winerror 707 708 oDst = self.xcptCopyErrorConstants(oDst, winerror) 641 709 642 710 # XPCOM compatability constants. 643 oDst.NS_OK = oDst.S_OK;644 oDst.NS_ERROR_FAILURE = oDst.E_FAIL;645 oDst.NS_ERROR_ABORT = oDst.E_ABORT;646 oDst.NS_ERROR_NULL_POINTER = oDst.E_POINTER;647 oDst.NS_ERROR_NO_INTERFACE = oDst.E_NOINTERFACE;648 oDst.NS_ERROR_INVALID_ARG = oDst.E_INVALIDARG;649 oDst.NS_ERROR_OUT_OF_MEMORY = oDst.E_OUTOFMEMORY;650 oDst.NS_ERROR_NOT_IMPLEMENTED = oDst.E_NOTIMPL ;651 oDst.NS_ERROR_UNEXPECTED = oDst.E_UNEXPECTED;652 return oDst ;711 oDst.NS_OK = oDst.S_OK 712 oDst.NS_ERROR_FAILURE = oDst.E_FAIL 713 oDst.NS_ERROR_ABORT = oDst.E_ABORT 714 oDst.NS_ERROR_NULL_POINTER = oDst.E_POINTER 715 oDst.NS_ERROR_NO_INTERFACE = oDst.E_NOINTERFACE 716 oDst.NS_ERROR_INVALID_ARG = oDst.E_INVALIDARG 717 oDst.NS_ERROR_OUT_OF_MEMORY = oDst.E_OUTOFMEMORY 718 oDst.NS_ERROR_NOT_IMPLEMENTED = oDst.E_NOTIMPL 719 oDst.NS_ERROR_UNEXPECTED = oDst.E_UNEXPECTED 720 return oDst 653 721 654 722 … … 659 727 660 728 def __init__(self, dParams): 661 PlatformBase.__init__(self, dParams) ;662 sys.path.append(VBoxSdkDir +'/bindings/xpcom/python/')729 PlatformBase.__init__(self, dParams) 730 sys.path.append(VBoxSdkDir + '/bindings/xpcom/python/') 663 731 import xpcom.vboxxpcom 664 732 import xpcom 665 733 import xpcom.components 666 _ = dParams ;734 _ = dParams 667 735 668 736 def getSessionObject(self, oIVBox): 669 _ = oIVBox ;737 _ = oIVBox 670 738 import xpcom.components 671 739 return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance() … … 679 747 680 748 def getArray(self, oInterface, sAttrib): 681 return oInterface.__getattr__('get' +ComifyName(sAttrib))()749 return oInterface.__getattr__('get' + ComifyName(sAttrib))() 682 750 683 751 def initPerThread(self): … … 692 760 d = {} 693 761 d['BaseClass'] = oImplClass 694 d['dArgs'] = dArgs762 d['dArgs'] = dArgs 695 763 str = "" 696 764 str += "import xpcom.components\n" … … 699 767 str += " def __init__(self): BaseClass.__init__(self, dArgs)\n" 700 768 str += "result = ListenerImpl()\n" 701 exec (str, d, d)769 exec(str, d, d) 702 770 return d['result'] 703 771 … … 719 787 720 788 def xcptGetStatus(self, oXcpt): 721 return oXcpt.errno ;789 return oXcpt.errno 722 790 723 791 def xcptIsDeadInterface(self, oXcpt): 724 792 return self.xcptGetStatus(oXcpt) in [ 725 0x80004004, -2147467260, # NS_ERROR_ABORT726 0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)727 ] ;793 0x80004004, -2147467260, # NS_ERROR_ABORT 794 0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED) 795 ] 728 796 729 797 def xcptGetMessage(self, oXcpt): 730 798 if hasattr(oXcpt, 'msg'): 731 799 try: 732 sRet = oXcpt.msg ;800 sRet = oXcpt.msg 733 801 if len(sRet) > 0: 734 return sRet ;802 return sRet 735 803 except: 736 pass ;737 return None ;804 pass 805 return None 738 806 739 807 def xcptGetBaseXcpt(self): 740 import xpcom ;741 return xpcom.Exception ;808 import xpcom 809 return xpcom.Exception 742 810 743 811 def xcptSetupConstants(self, oDst): 744 import xpcom ;745 oDst = self.xcptCopyErrorConstants(oDst, xpcom.nsError) ;812 import xpcom 813 oDst = self.xcptCopyErrorConstants(oDst, xpcom.nsError) 746 814 747 815 # COM compatability constants. 748 oDst.E_ACCESSDENIED = -2147024891;# see VBox/com/defs.h749 oDst.S_OK = oDst.NS_OK;750 oDst.E_FAIL = oDst.NS_ERROR_FAILURE;751 oDst.E_ABORT = oDst.NS_ERROR_ABORT;752 oDst.E_POINTER = oDst.NS_ERROR_NULL_POINTER;753 oDst.E_NOINTERFACE = oDst.NS_ERROR_NO_INTERFACE;754 oDst.E_INVALIDARG = oDst.NS_ERROR_INVALID_ARG;755 oDst.E_OUTOFMEMORY = oDst.NS_ERROR_OUT_OF_MEMORY;756 oDst.E_NOTIMPL = oDst.NS_ERROR_NOT_IMPLEMENTED;757 oDst.E_UNEXPECTED = oDst.NS_ERROR_UNEXPECTED;758 oDst.DISP_E_EXCEPTION = -2147352567;# For COM compatability only.759 return oDst ;816 oDst.E_ACCESSDENIED = -2147024891 # see VBox/com/defs.h 817 oDst.S_OK = oDst.NS_OK 818 oDst.E_FAIL = oDst.NS_ERROR_FAILURE 819 oDst.E_ABORT = oDst.NS_ERROR_ABORT 820 oDst.E_POINTER = oDst.NS_ERROR_NULL_POINTER 821 oDst.E_NOINTERFACE = oDst.NS_ERROR_NO_INTERFACE 822 oDst.E_INVALIDARG = oDst.NS_ERROR_INVALID_ARG 823 oDst.E_OUTOFMEMORY = oDst.NS_ERROR_OUT_OF_MEMORY 824 oDst.E_NOTIMPL = oDst.NS_ERROR_NOT_IMPLEMENTED 825 oDst.E_UNEXPECTED = oDst.NS_ERROR_UNEXPECTED 826 oDst.DISP_E_EXCEPTION = -2147352567 # For COM compatability only. 827 return oDst 760 828 761 829 … … 766 834 767 835 def __init__(self, dParams): 768 PlatformBase.__init__(self, dParams) ;836 PlatformBase.__init__(self, dParams) 769 837 # Import web services stuff. Fix the sys.path the first time. 770 sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib') ;838 sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib') 771 839 if sWebServLib not in sys.path: 772 sys.path.append(sWebServLib) ;840 sys.path.append(sWebServLib) 773 841 import VirtualBox_wrappers 774 842 from VirtualBox_wrappers import IWebsessionManager2 … … 776 844 # Initialize instance variables from parameters. 777 845 if dParams is not None: 778 self.user = dParams.get("user", "")846 self.user = dParams.get("user", "") 779 847 self.password = dParams.get("password", "") 780 self.url = dParams.get("url", "")848 self.url = dParams.get("url", "") 781 849 else: 782 self.user = ""850 self.user = "" 783 851 self.password = "" 784 self.url = None785 self.vbox = None786 self.wsmgr = None ;852 self.url = None 853 self.vbox = None 854 self.wsmgr = None 787 855 788 856 # … … 808 876 def waitForEvents(self, timeout): 809 877 # Webservices cannot do that yet 810 return 2 ;878 return 2 811 879 812 880 def interruptWaitEvents(self, timeout): 813 881 # Webservices cannot do that yet 814 return False ;882 return False 815 883 816 884 def deinit(self): 817 885 try: 818 disconnect()886 disconnect() 819 887 except: 820 pass888 pass 821 889 822 890 def queryInterface(self, oIUnknown, sClassName): … … 824 892 d['oIUnknown'] = oIUnknown 825 893 str = "" 826 str += "from VirtualBox_wrappers import " +sClassName+"\n"827 str += "result = " +sClassName+"(oIUnknown.mgr, oIUnknown.handle)\n"894 str += "from VirtualBox_wrappers import " + sClassName + "\n" 895 str += "result = " + sClassName + "(oIUnknown.mgr, oIUnknown.handle)\n" 828 896 # wrong, need to test if class indeed implements this interface 829 exec (str, d, d)897 exec(str, d, d) 830 898 return d['result'] 831 899 … … 836 904 def connect(self, url, user, passwd): 837 905 if self.vbox is not None: 838 self.disconnect()906 self.disconnect() 839 907 from VirtualBox_wrappers import IWebsessionManager2 908 840 909 if url is None: 841 910 url = "" … … 850 919 self.vbox = self.wsmgr.logon(self.user, self.password) 851 920 if not self.vbox.handle: 852 raise Exception("cannot connect to '" +self.url+"' as '"+self.user+"'")921 raise Exception("cannot connect to '" + self.url + "' as '" + self.user + "'") 853 922 return self.vbox 854 923 … … 856 925 if self.vbox is not None and self.wsmgr is not None: 857 926 self.wsmgr.logoff(self.vbox) 858 self.vbox = None927 self.vbox = None 859 928 self.wsmgr = None 860 929 … … 866 935 # platforms at the same time, so this should be sufficent for most uses and 867 936 # be way simpler to use than VirtualBoxManager::oXcptClass. 868 CurXctpClass = None ;937 CurXctpClass = None 869 938 870 939 … … 884 953 class Statuses(object): 885 954 def __init__(self): 886 pass ;887 888 def __init__(self, sStyle = None, dPlatformParams =None):955 pass 956 957 def __init__(self, sStyle=None, dPlatformParams=None): 889 958 if sStyle is None: 890 959 if sys.platform == 'win32': … … 893 962 sStyle = "XPCOM" 894 963 if sStyle == 'XPCOM': 895 self.platform = PlatformXPCOM(dPlatformParams) ;964 self.platform = PlatformXPCOM(dPlatformParams) 896 965 elif sStyle == 'MSCOM': 897 self.platform = PlatformMSCOM(dPlatformParams) ;966 self.platform = PlatformMSCOM(dPlatformParams) 898 967 elif sStyle == 'WEBSERVICE': 899 self.platform = PlatformWEBSERVICE(dPlatformParams) ;968 self.platform = PlatformWEBSERVICE(dPlatformParams) 900 969 else: 901 raise Exception('Unknown sStyle=%s' % (sStyle,)) ;902 self.style = sStyle903 self.type = self.platform.getType()904 self.remote = self.platform.isRemote()970 raise Exception('Unknown sStyle=%s' % (sStyle,)) 971 self.style = sStyle 972 self.type = self.platform.getType() 973 self.remote = self.platform.isRemote() 905 974 ## VirtualBox API constants (for webservices, enums are symbolic). 906 975 self.constants = VirtualBoxReflectionInfo(sStyle == "WEBSERVICE") 907 976 908 977 ## Status constants. 909 self.statuses = self.platform.xcptSetupConstants(VirtualBoxManager.Statuses());978 self.statuses = self.platform.xcptSetupConstants(VirtualBoxManager.Statuses()) 910 979 ## @todo Add VBOX_E_XXX to statuses? They're already in constants... 911 980 ## Dictionary for errToString, built on demand. 912 self._dErrorValToName = None ;981 self._dErrorValToName = None 913 982 914 983 ## The exception class for the selected platform. 915 self.oXcptClass = self.platform.xcptGetBaseXcpt() ;916 global CurXcptClass ;917 CurXcptClass = self.oXcptClass ;984 self.oXcptClass = self.platform.xcptGetBaseXcpt() 985 global CurXcptClass 986 CurXcptClass = self.oXcptClass 918 987 919 988 # Get the virtualbox singleton. 920 989 try: 921 990 self.vbox = self.platform.getVirtualBox() 922 except NameError , ne:923 print "Installation problem: check that appropriate libs in place"991 except NameError: 992 print_("Installation problem: check that appropriate libs in place") 924 993 traceback.print_exc() 925 raise ne 926 except Exception, e: 927 print "init exception: ", e 994 raise 995 except Exception: 996 _, e, _ = sys.exc_info() 997 print_("init exception: ", e) 928 998 traceback.print_exc() 929 999 if self.remote: … … 931 1001 else: 932 1002 raise e 1003 933 1004 ## @deprecated 934 1005 # This used to refer to a session manager class with only one method 935 1006 # called getSessionObject. The method has moved into this call. 936 self.mgr = self ;1007 self.mgr = self 937 1008 938 1009 def __del__(self): … … 944 1015 This will be incremented when features are added to this file. 945 1016 """ 946 return 3; 947 1017 return 3 948 1018 949 1019 # 950 1020 # Wrappers for self.platform methods. 951 1021 # 952 953 1022 def getVirtualBox(self): 954 1023 """ See PlatformBase::getVirtualBox(). """ … … 957 1026 def getSessionObject(self, oIVBox): 958 1027 """ See PlatformBase::getSessionObject(). """ 959 return self.platform.getSessionObject(oIVBox) ;1028 return self.platform.getSessionObject(oIVBox) 960 1029 961 1030 def getArray(self, oInterface, sAttrib): … … 963 1032 return self.platform.getArray(oInterface, sAttrib) 964 1033 965 def createListener(self, oImplClass, dArgs =None):1034 def createListener(self, oImplClass, dArgs=None): 966 1035 """ See PlatformBase::createListener(). """ 967 1036 return self.platform.createListener(oImplClass, dArgs) … … 979 1048 return self.platform.queryInterface(oIUnknown, sClassName) 980 1049 981 982 1050 # 983 1051 # Init and uninit. 984 1052 # 985 986 1053 def initPerThread(self): 987 1054 """ See PlatformBase::deinitPerThread(). """ … … 1003 1070 self.platform.deinit() 1004 1071 self.platform = None 1005 return True; 1006 1072 return True 1007 1073 1008 1074 # 1009 1075 # Utility methods. 1010 1076 # 1011 1012 def openMachineSession(self, oIMachine, fPermitSharing = True): 1077 def openMachineSession(self, oIMachine, fPermitSharing=True): 1013 1078 """ 1014 1079 Attemts to open the a session to the machine. … … 1016 1081 Raises exception on failure. 1017 1082 """ 1018 oSession = self.mgr.getSessionObject(self.vbox) ;1083 oSession = self.mgr.getSessionObject(self.vbox) 1019 1084 if fPermitSharing: 1020 type = self.constants.LockType_Shared;1085 type_ = self.constants.LockType_Shared 1021 1086 else: 1022 type = self.constants.LockType_Write;1023 oIMachine.lockMachine(oSession, type );1024 return oSession ;1087 type_ = self.constants.LockType_Write 1088 oIMachine.lockMachine(oSession, type_) 1089 return oSession 1025 1090 1026 1091 def closeMachineSession(self, oSession): … … 1031 1096 if oSession is not None: 1032 1097 oSession.unlockMachine() 1033 return True ;1098 return True 1034 1099 1035 1100 def getPerfCollector(self, oIVBox): … … 1054 1119 return VBoxSdkDir 1055 1120 1056 1057 1121 # 1058 1122 # Error code utilities. 1059 1123 # 1060 1061 1124 ## @todo port to webservices! 1062 1063 def xcptGetStatus(self, oXcpt = None): 1125 def xcptGetStatus(self, oXcpt=None): 1064 1126 """ 1065 1127 Gets the status code from an exception. If the exception parameter … … 1067 1129 """ 1068 1130 if oXcpt is None: 1069 oXcpt = sys.exc_info()[1] ;1070 return self.platform.xcptGetStatus(oXcpt) ;1071 1072 def xcptIsDeadInterface(self, oXcpt =None):1131 oXcpt = sys.exc_info()[1] 1132 return self.platform.xcptGetStatus(oXcpt) 1133 1134 def xcptIsDeadInterface(self, oXcpt=None): 1073 1135 """ 1074 1136 Returns True if the exception indicates that the interface is dead, … … 1077 1139 """ 1078 1140 if oXcpt is None: 1079 oXcpt = sys.exc_info()[1] ;1080 return self.platform.xcptIsDeadInterface(oXcpt) ;1081 1082 def xcptIsOurXcptKind(self, oXcpt =None):1141 oXcpt = sys.exc_info()[1] 1142 return self.platform.xcptIsDeadInterface(oXcpt) 1143 1144 def xcptIsOurXcptKind(self, oXcpt=None): 1083 1145 """ 1084 1146 Checks if the exception is one that could come from the VBox API. If … … 1086 1148 examined. 1087 1149 """ 1088 if self.oXcptClass is None: ## @todo find the exception class for web services!1089 return False ;1150 if self.oXcptClass is None: # @todo find the exception class for web services! 1151 return False 1090 1152 if oXcpt is None: 1091 oXcpt = sys.exc_info()[1] ;1092 return isinstance(oXcpt, self.oXcptClass) ;1153 oXcpt = sys.exc_info()[1] 1154 return isinstance(oXcpt, self.oXcptClass) 1093 1155 1094 1156 def xcptIsEqual(self, oXcpt, hrStatus): … … 1104 1166 """ 1105 1167 if oXcpt is None: 1106 oXcpt = sys.exc_info()[1] ;1107 return self.platform.xcptIsEqual(oXcpt, hrStatus) ;1168 oXcpt = sys.exc_info()[1] 1169 return self.platform.xcptIsEqual(oXcpt, hrStatus) 1108 1170 1109 1171 def xcptIsNotEqual(self, oXcpt, hrStatus): … … 1111 1173 Negated xcptIsEqual. 1112 1174 """ 1113 return not self.xcptIsEqual(oXcpt, hrStatus) ;1114 1115 def xcptToString(self, hrStatusOrXcpt =None):1175 return not self.xcptIsEqual(oXcpt, hrStatus) 1176 1177 def xcptToString(self, hrStatusOrXcpt=None): 1116 1178 """ 1117 1179 Converts the specified COM status code, or the status code of the … … 1121 1183 1122 1184 # Deal with exceptions. 1123 if hrStatusOrXcpt is None orself.xcptIsOurXcptKind(hrStatusOrXcpt):1124 hrStatus = self.xcptGetStatus(hrStatusOrXcpt) ;1185 if hrStatusOrXcpt is None or self.xcptIsOurXcptKind(hrStatusOrXcpt): 1186 hrStatus = self.xcptGetStatus(hrStatusOrXcpt) 1125 1187 else: 1126 hrStatus = hrStatusOrXcpt ;1188 hrStatus = hrStatusOrXcpt 1127 1189 1128 1190 # Build the dictionary on demand. 1129 1191 if self._dErrorValToName is None: 1130 dErrorValToName = dict() ;1192 dErrorValToName = dict() 1131 1193 for sKey in dir(self.statuses): 1132 1194 if sKey[0].isupper(): 1133 oValue = getattr(self.statuses, sKey) ;1195 oValue = getattr(self.statuses, sKey) 1134 1196 if type(oValue) is int: 1135 dErrorValToName[oValue] = sKey ;1136 self._dErrorValToName = dErrorValToName ;1197 dErrorValToName[oValue] = sKey 1198 self._dErrorValToName = dErrorValToName 1137 1199 1138 1200 # Do the lookup, falling back on formatting the status number. 1139 1201 try: 1140 sStr = self._dErrorValToName[int(hrStatus)] ;1202 sStr = self._dErrorValToName[int(hrStatus)] 1141 1203 except KeyError: 1142 hrLong = long(hrStatus) ;1143 sStr = '%#x (%d)' % (hrLong, hrLong) ;1144 return sStr ;1145 1146 def xcptGetMessage(self, oXcpt =None):1204 hrLong = long(hrStatus) 1205 sStr = '%#x (%d)' % (hrLong, hrLong) 1206 return sStr 1207 1208 def xcptGetMessage(self, oXcpt=None): 1147 1209 """ 1148 1210 Returns the best error message found in the COM-like exception. If the … … 1150 1212 """ 1151 1213 if oXcpt is None: 1152 oXcpt = sys.exc_info()[1] ;1153 sRet = self.platform.xcptGetMessage(oXcpt) ;1214 oXcpt = sys.exc_info()[1] 1215 sRet = self.platform.xcptGetMessage(oXcpt) 1154 1216 if sRet is None: 1155 sRet = self.xcptToString(oXcpt) ;1156 return sRet ;1217 sRet = self.xcptToString(oXcpt) 1218 return sRet 1157 1219 1158 1220 # Legacy, remove in a day or two. 1159 errGetStatus = xcptGetStatus1221 errGetStatus = xcptGetStatus 1160 1222 errIsDeadInterface = xcptIsDeadInterface 1161 errIsOurXcptKind = xcptIsOurXcptKind1162 errGetMessage = xcptGetMessage1163 1223 errIsOurXcptKind = xcptIsOurXcptKind 1224 errGetMessage = xcptGetMessage 1225
Note:
See TracChangeset
for help on using the changeset viewer.

