1 | # -*- coding: utf-8 -*-
|
---|
2 | # $Id: vboxapi.py 69556 2017-11-03 00:10:29Z vboxsync $
|
---|
3 | """
|
---|
4 | VirtualBox Python API Glue.
|
---|
5 | """
|
---|
6 |
|
---|
7 | __copyright__ = \
|
---|
8 | """
|
---|
9 | Copyright (C) 2009-2017 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 | The contents of this file may alternatively be used under the terms
|
---|
20 | of the Common Development and Distribution License Version 1.0
|
---|
21 | (CDDL) only, as it comes in the "COPYING.CDDL" file of the
|
---|
22 | VirtualBox OSE distribution, in which case the provisions of the
|
---|
23 | CDDL are applicable instead of those of the GPL.
|
---|
24 |
|
---|
25 | You may elect to license modified versions of this file under the
|
---|
26 | terms and conditions of either the GPL or the CDDL or both.
|
---|
27 | """
|
---|
28 | __version__ = "$Revision: 69556 $"
|
---|
29 |
|
---|
30 |
|
---|
31 | # Note! To set Python bitness on OSX use 'export VERSIONER_PYTHON_PREFER_32_BIT=yes'
|
---|
32 |
|
---|
33 |
|
---|
34 | # Standard Python imports.
|
---|
35 | import os
|
---|
36 | import sys
|
---|
37 | import traceback
|
---|
38 |
|
---|
39 |
|
---|
40 | if sys.version_info >= (3, 0):
|
---|
41 | xrange = range
|
---|
42 | long = int
|
---|
43 |
|
---|
44 | #
|
---|
45 | # Globals, environment and sys.path changes.
|
---|
46 | #
|
---|
47 | import platform
|
---|
48 | VBoxBinDir = os.environ.get("VBOX_PROGRAM_PATH", None)
|
---|
49 | VBoxSdkDir = os.environ.get("VBOX_SDK_PATH", None)
|
---|
50 |
|
---|
51 | if VBoxBinDir is None:
|
---|
52 | if platform.system() == 'Darwin':
|
---|
53 | VBoxBinDir = '/Applications/VirtualBox.app/Contents/MacOS'
|
---|
54 | else: # Will be set by the installer
|
---|
55 | VBoxBinDir = "%VBOX_INSTALL_PATH%"
|
---|
56 | else:
|
---|
57 | VBoxBinDir = os.path.abspath(VBoxBinDir)
|
---|
58 |
|
---|
59 | if VBoxSdkDir is None:
|
---|
60 | if platform.system() == 'Darwin':
|
---|
61 | VBoxSdkDir = '/Applications/VirtualBox.app/Contents/MacOS/sdk'
|
---|
62 | else: # Will be set by the installer
|
---|
63 | VBoxSdkDir = "%VBOX_SDK_PATH%"
|
---|
64 | else:
|
---|
65 | VBoxSdkDir = os.path.abspath(VBoxSdkDir)
|
---|
66 |
|
---|
67 | os.environ["VBOX_PROGRAM_PATH"] = VBoxBinDir
|
---|
68 | os.environ["VBOX_SDK_PATH"] = VBoxSdkDir
|
---|
69 | sys.path.append(VBoxBinDir)
|
---|
70 |
|
---|
71 |
|
---|
72 | #
|
---|
73 | # Import the generated VirtualBox constants.
|
---|
74 | #
|
---|
75 | from .VirtualBox_constants import VirtualBoxReflectionInfo
|
---|
76 |
|
---|
77 |
|
---|
78 | class PerfCollector(object):
|
---|
79 | """ This class provides a wrapper over IPerformanceCollector in order to
|
---|
80 | get more 'pythonic' interface.
|
---|
81 |
|
---|
82 | To begin collection of metrics use setup() method.
|
---|
83 |
|
---|
84 | To get collected data use query() method.
|
---|
85 |
|
---|
86 | It is possible to disable metric collection without changing collection
|
---|
87 | parameters with disable() method. The enable() method resumes metric
|
---|
88 | collection.
|
---|
89 | """
|
---|
90 |
|
---|
91 | def __init__(self, mgr, vbox):
|
---|
92 | """ Initializes the instance.
|
---|
93 |
|
---|
94 | """
|
---|
95 | self.mgr = mgr
|
---|
96 | self.isMscom = (mgr.type == 'MSCOM')
|
---|
97 | self.collector = vbox.performanceCollector
|
---|
98 |
|
---|
99 | def setup(self, names, objects, period, nsamples):
|
---|
100 | """ Discards all previously collected values for the specified
|
---|
101 | metrics, sets the period of collection and the number of retained
|
---|
102 | samples, enables collection.
|
---|
103 | """
|
---|
104 | self.collector.setupMetrics(names, objects, period, nsamples)
|
---|
105 |
|
---|
106 | def enable(self, names, objects):
|
---|
107 | """ Resumes metric collection for the specified metrics.
|
---|
108 | """
|
---|
109 | self.collector.enableMetrics(names, objects)
|
---|
110 |
|
---|
111 | def disable(self, names, objects):
|
---|
112 | """ Suspends metric collection for the specified metrics.
|
---|
113 | """
|
---|
114 | self.collector.disableMetrics(names, objects)
|
---|
115 |
|
---|
116 | def query(self, names, objects):
|
---|
117 | """ Retrieves collected metric values as well as some auxiliary
|
---|
118 | information. Returns an array of dictionaries, one dictionary per
|
---|
119 | metric. Each dictionary contains the following entries:
|
---|
120 | 'name': metric name
|
---|
121 | 'object': managed object this metric associated with
|
---|
122 | 'unit': unit of measurement
|
---|
123 | 'scale': divide 'values' by this number to get float numbers
|
---|
124 | 'values': collected data
|
---|
125 | 'values_as_string': pre-processed values ready for 'print' statement
|
---|
126 | """
|
---|
127 | # Get around the problem with input arrays returned in output
|
---|
128 | # parameters (see #3953) for MSCOM.
|
---|
129 | if self.isMscom:
|
---|
130 | (values, names, objects, names_out, objects_out, units, scales, sequence_numbers,
|
---|
131 | indices, lengths) = self.collector.queryMetricsData(names, objects)
|
---|
132 | else:
|
---|
133 | (values, names_out, objects_out, units, scales, sequence_numbers,
|
---|
134 | indices, lengths) = self.collector.queryMetricsData(names, objects)
|
---|
135 | out = []
|
---|
136 | for i in xrange(0, len(names_out)):
|
---|
137 | scale = int(scales[i])
|
---|
138 | if scale != 1:
|
---|
139 | fmt = '%.2f%s'
|
---|
140 | else:
|
---|
141 | fmt = '%d %s'
|
---|
142 | out.append({
|
---|
143 | 'name': str(names_out[i]),
|
---|
144 | 'object': str(objects_out[i]),
|
---|
145 | 'unit': str(units[i]),
|
---|
146 | 'scale': scale,
|
---|
147 | 'values': [int(values[j]) for j in xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))],
|
---|
148 | 'values_as_string': '[' + ', '.join([fmt % (int(values[j]) / scale, units[i]) for j in
|
---|
149 | xrange(int(indices[i]), int(indices[i]) + int(lengths[i]))]) + ']'
|
---|
150 | })
|
---|
151 | return out
|
---|
152 |
|
---|
153 |
|
---|
154 | #
|
---|
155 | # Attribute hacks.
|
---|
156 | #
|
---|
157 | def ComifyName(name):
|
---|
158 | return name[0].capitalize() + name[1:]
|
---|
159 |
|
---|
160 |
|
---|
161 | ## This is for saving the original DispatchBaseClass __getattr__ and __setattr__
|
---|
162 | # method references.
|
---|
163 | _g_dCOMForward = {
|
---|
164 | 'getattr': None,
|
---|
165 | 'setattr': None,
|
---|
166 | }
|
---|
167 |
|
---|
168 |
|
---|
169 | def _CustomGetAttr(self, sAttr):
|
---|
170 | """ Our getattr replacement for DispatchBaseClass. """
|
---|
171 | # Fastpath.
|
---|
172 | oRet = self.__class__.__dict__.get(sAttr)
|
---|
173 | if oRet is not None:
|
---|
174 | return oRet
|
---|
175 |
|
---|
176 | # Try case-insensitivity workaround for class attributes (COM methods).
|
---|
177 | sAttrLower = sAttr.lower()
|
---|
178 | for k in list(self.__class__.__dict__.keys()):
|
---|
179 | if k.lower() == sAttrLower:
|
---|
180 | setattr(self.__class__, sAttr, self.__class__.__dict__[k])
|
---|
181 | return getattr(self, k)
|
---|
182 |
|
---|
183 | # Slow path.
|
---|
184 | try:
|
---|
185 | return _g_dCOMForward['getattr'](self, ComifyName(sAttr))
|
---|
186 | except AttributeError:
|
---|
187 | return _g_dCOMForward['getattr'](self, sAttr)
|
---|
188 |
|
---|
189 |
|
---|
190 | def _CustomSetAttr(self, sAttr, oValue):
|
---|
191 | """ Our setattr replacement for DispatchBaseClass. """
|
---|
192 | try:
|
---|
193 | return _g_dCOMForward['setattr'](self, ComifyName(sAttr), oValue)
|
---|
194 | except AttributeError:
|
---|
195 | return _g_dCOMForward['setattr'](self, sAttr, oValue)
|
---|
196 |
|
---|
197 |
|
---|
198 | class PlatformBase(object):
|
---|
199 | """
|
---|
200 | Base class for the platform specific code.
|
---|
201 | """
|
---|
202 |
|
---|
203 | def __init__(self, aoParams):
|
---|
204 | _ = aoParams
|
---|
205 |
|
---|
206 | def getVirtualBox(self):
|
---|
207 | """
|
---|
208 | Gets a the IVirtualBox singleton.
|
---|
209 | """
|
---|
210 | return None
|
---|
211 |
|
---|
212 | def getSessionObject(self):
|
---|
213 | """
|
---|
214 | Get a session object that can be used for opening machine sessions.
|
---|
215 |
|
---|
216 | The oIVBox parameter is an getVirtualBox() return value, i.e. an
|
---|
217 | IVirtualBox reference.
|
---|
218 |
|
---|
219 | See also openMachineSession.
|
---|
220 | """
|
---|
221 | return None
|
---|
222 |
|
---|
223 | def getType(self):
|
---|
224 | """ Returns the platform type (class name sans 'Platform'). """
|
---|
225 | return None
|
---|
226 |
|
---|
227 | def isRemote(self):
|
---|
228 | """
|
---|
229 | Returns True if remote (web services) and False if local (COM/XPCOM).
|
---|
230 | """
|
---|
231 | return False
|
---|
232 |
|
---|
233 | def getArray(self, oInterface, sAttrib):
|
---|
234 | """
|
---|
235 | Retrives the value of the array attribute 'sAttrib' from
|
---|
236 | interface 'oInterface'.
|
---|
237 |
|
---|
238 | This is for hiding platform specific differences in attributes
|
---|
239 | returning arrays.
|
---|
240 | """
|
---|
241 | _ = oInterface
|
---|
242 | _ = sAttrib
|
---|
243 | return None
|
---|
244 |
|
---|
245 | def setArray(self, oInterface, sAttrib, aoArray):
|
---|
246 | """
|
---|
247 | Sets the value (aoArray) of the array attribute 'sAttrib' in
|
---|
248 | interface 'oInterface'.
|
---|
249 |
|
---|
250 | This is for hiding platform specific differences in attributes
|
---|
251 | setting arrays.
|
---|
252 | """
|
---|
253 | _ = oInterface
|
---|
254 | _ = sAttrib
|
---|
255 | _ = aoArray
|
---|
256 | return None
|
---|
257 |
|
---|
258 | def initPerThread(self):
|
---|
259 | """
|
---|
260 | Does backend specific initialization for the calling thread.
|
---|
261 | """
|
---|
262 | return True
|
---|
263 |
|
---|
264 | def deinitPerThread(self):
|
---|
265 | """
|
---|
266 | Does backend specific uninitialization for the calling thread.
|
---|
267 | """
|
---|
268 | return True
|
---|
269 |
|
---|
270 | def createListener(self, oImplClass, dArgs):
|
---|
271 | """
|
---|
272 | Instantiates and wraps an active event listener class so it can be
|
---|
273 | passed to an event source for registration.
|
---|
274 |
|
---|
275 | oImplClass is a class (type, not instance) which implements
|
---|
276 | IEventListener.
|
---|
277 |
|
---|
278 | dArgs is a dictionary with string indexed variables. This may be
|
---|
279 | modified by the method to pass platform specific parameters. Can
|
---|
280 | be None.
|
---|
281 |
|
---|
282 | This currently only works on XPCOM. COM support is not possible due to
|
---|
283 | shortcuts taken in the COM bridge code, which is not under our control.
|
---|
284 | Use passive listeners for COM and web services.
|
---|
285 | """
|
---|
286 | _ = oImplClass
|
---|
287 | _ = dArgs
|
---|
288 | raise Exception("No active listeners for this platform")
|
---|
289 |
|
---|
290 | def waitForEvents(self, cMsTimeout):
|
---|
291 | """
|
---|
292 | Wait for events to arrive and process them.
|
---|
293 |
|
---|
294 | The timeout (cMsTimeout) is in milliseconds for how long to wait for
|
---|
295 | events to arrive. A negative value means waiting for ever, while 0
|
---|
296 | does not wait at all.
|
---|
297 |
|
---|
298 | Returns 0 if events was processed.
|
---|
299 | Returns 1 if timed out or interrupted in some way.
|
---|
300 | Returns 2 on error (like not supported for web services).
|
---|
301 |
|
---|
302 | Raises an exception if the calling thread is not the main thread (the one
|
---|
303 | that initialized VirtualBoxManager) or if the time isn't an integer.
|
---|
304 | """
|
---|
305 | _ = cMsTimeout
|
---|
306 | return 2
|
---|
307 |
|
---|
308 | def interruptWaitEvents(self):
|
---|
309 | """
|
---|
310 | Interrupt a waitForEvents call.
|
---|
311 | This is normally called from a worker thread to wake up the main thread.
|
---|
312 |
|
---|
313 | Returns True on success, False on failure.
|
---|
314 | """
|
---|
315 | return False
|
---|
316 |
|
---|
317 | def deinit(self):
|
---|
318 | """
|
---|
319 | Unitializes the platform specific backend.
|
---|
320 | """
|
---|
321 | return None
|
---|
322 |
|
---|
323 | def queryInterface(self, oIUnknown, sClassName):
|
---|
324 | """
|
---|
325 | IUnknown::QueryInterface wrapper.
|
---|
326 |
|
---|
327 | oIUnknown is who to ask.
|
---|
328 | sClassName is the name of the interface we're asking for.
|
---|
329 | """
|
---|
330 | return None
|
---|
331 |
|
---|
332 | #
|
---|
333 | # Error (exception) access methods.
|
---|
334 | #
|
---|
335 |
|
---|
336 | def xcptGetStatus(self, oXcpt):
|
---|
337 | """
|
---|
338 | Returns the COM status code from the VBox API given exception.
|
---|
339 | """
|
---|
340 | return None
|
---|
341 |
|
---|
342 | def xcptIsDeadInterface(self, oXcpt):
|
---|
343 | """
|
---|
344 | Returns True if the exception indicates that the interface is dead, False if not.
|
---|
345 | """
|
---|
346 | return False
|
---|
347 |
|
---|
348 | def xcptIsEqual(self, oXcpt, hrStatus):
|
---|
349 | """
|
---|
350 | Checks if the exception oXcpt is equal to the COM/XPCOM status code
|
---|
351 | hrStatus.
|
---|
352 |
|
---|
353 | The oXcpt parameter can be any kind of object, we'll just return True
|
---|
354 | if it doesn't behave like a our exception class.
|
---|
355 |
|
---|
356 | Will not raise any exception as long as hrStatus and self are not bad.
|
---|
357 | """
|
---|
358 | try:
|
---|
359 | hrXcpt = self.xcptGetStatus(oXcpt)
|
---|
360 | except AttributeError:
|
---|
361 | return False
|
---|
362 | if hrXcpt == hrStatus:
|
---|
363 | return True
|
---|
364 |
|
---|
365 | # Fudge for 32-bit signed int conversion.
|
---|
366 | if 0x7fffffff < hrStatus <= 0xffffffff and hrXcpt < 0:
|
---|
367 | if (hrStatus - 0x100000000) == hrXcpt:
|
---|
368 | return True
|
---|
369 | return False
|
---|
370 |
|
---|
371 | def xcptGetMessage(self, oXcpt):
|
---|
372 | """
|
---|
373 | Returns the best error message found in the COM-like exception.
|
---|
374 | Returns None to fall back on xcptToString.
|
---|
375 | Raises exception if oXcpt isn't our kind of exception object.
|
---|
376 | """
|
---|
377 | return None
|
---|
378 |
|
---|
379 | def xcptGetBaseXcpt(self):
|
---|
380 | """
|
---|
381 | Returns the base exception class.
|
---|
382 | """
|
---|
383 | return None
|
---|
384 |
|
---|
385 | def xcptSetupConstants(self, oDst):
|
---|
386 | """
|
---|
387 | Copy/whatever all error constants onto oDst.
|
---|
388 | """
|
---|
389 | return oDst
|
---|
390 |
|
---|
391 | @staticmethod
|
---|
392 | def xcptCopyErrorConstants(oDst, oSrc):
|
---|
393 | """
|
---|
394 | Copy everything that looks like error constants from oDst to oSrc.
|
---|
395 | """
|
---|
396 | for sAttr in dir(oSrc):
|
---|
397 | if sAttr[0].isupper() and (sAttr[1].isupper() or sAttr[1] == '_'):
|
---|
398 | oAttr = getattr(oSrc, sAttr)
|
---|
399 | if type(oAttr) is int:
|
---|
400 | setattr(oDst, sAttr, oAttr)
|
---|
401 | return oDst
|
---|
402 |
|
---|
403 |
|
---|
404 | class PlatformMSCOM(PlatformBase):
|
---|
405 | """
|
---|
406 | Platform specific code for MS COM.
|
---|
407 | """
|
---|
408 |
|
---|
409 | ## @name VirtualBox COM Typelib definitions (should be generate)
|
---|
410 | #
|
---|
411 | # @remarks Must be updated when the corresponding VirtualBox.xidl bits
|
---|
412 | # are changed. Fortunately this isn't very often.
|
---|
413 | # @{
|
---|
414 | VBOX_TLB_GUID = '{D7569351-1750-46F0-936E-BD127D5BC264}'
|
---|
415 | VBOX_TLB_LCID = 0
|
---|
416 | VBOX_TLB_MAJOR = 1
|
---|
417 | VBOX_TLB_MINOR = 3
|
---|
418 | ## @}
|
---|
419 |
|
---|
420 | def __init__(self, dParams):
|
---|
421 | PlatformBase.__init__(self, dParams)
|
---|
422 |
|
---|
423 | #
|
---|
424 | # Since the code runs on all platforms, we have to do a lot of
|
---|
425 | # importing here instead of at the top of the file where it's normally located.
|
---|
426 | #
|
---|
427 | from win32com import universal
|
---|
428 | from win32com.client import gencache, DispatchBaseClass
|
---|
429 | from win32com.client import constants, getevents
|
---|
430 | import win32com
|
---|
431 | import pythoncom
|
---|
432 | import win32api
|
---|
433 | import winerror
|
---|
434 | from win32con import DUPLICATE_SAME_ACCESS
|
---|
435 | from win32api import GetCurrentThread, GetCurrentThreadId, DuplicateHandle, GetCurrentProcess
|
---|
436 | import threading
|
---|
437 |
|
---|
438 | self.winerror = winerror
|
---|
439 |
|
---|
440 | # Setup client impersonation in COM calls.
|
---|
441 | try:
|
---|
442 | pythoncom.CoInitializeSecurity(None,
|
---|
443 | None,
|
---|
444 | None,
|
---|
445 | pythoncom.RPC_C_AUTHN_LEVEL_DEFAULT,
|
---|
446 | pythoncom.RPC_C_IMP_LEVEL_IMPERSONATE,
|
---|
447 | None,
|
---|
448 | pythoncom.EOAC_NONE,
|
---|
449 | None)
|
---|
450 | except:
|
---|
451 | _, oXcpt, _ = sys.exc_info();
|
---|
452 | if isinstance(oXcpt, pythoncom.com_error) and self.xcptGetStatus(oXcpt) == -2147417831: # RPC_E_TOO_LATE
|
---|
453 | print("Warning: CoInitializeSecurity was already called");
|
---|
454 | else:
|
---|
455 | print("Warning: CoInitializeSecurity failed: ", oXctp);
|
---|
456 |
|
---|
457 | # Remember this thread ID and get its handle so we can wait on it in waitForEvents().
|
---|
458 | self.tid = GetCurrentThreadId()
|
---|
459 | pid = GetCurrentProcess()
|
---|
460 | self.aoHandles = [DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS),]; # type: list[PyHANDLE]
|
---|
461 |
|
---|
462 | # Hack the COM dispatcher base class so we can modify method and
|
---|
463 | # attribute names to match those in xpcom.
|
---|
464 | if _g_dCOMForward['setattr'] is None:
|
---|
465 | _g_dCOMForward['getattr'] = DispatchBaseClass.__dict__['__getattr__']
|
---|
466 | _g_dCOMForward['setattr'] = DispatchBaseClass.__dict__['__setattr__']
|
---|
467 | setattr(DispatchBaseClass, '__getattr__', _CustomGetAttr)
|
---|
468 | setattr(DispatchBaseClass, '__setattr__', _CustomSetAttr)
|
---|
469 |
|
---|
470 | # Hack the exception base class so the users doesn't need to check for
|
---|
471 | # XPCOM or COM and do different things.
|
---|
472 | ## @todo
|
---|
473 |
|
---|
474 | #
|
---|
475 | # Make sure the gencache is correct (we don't quite follow the COM
|
---|
476 | # versioning rules).
|
---|
477 | #
|
---|
478 | self.flushGenPyCache(win32com.client.gencache)
|
---|
479 | win32com.client.gencache.EnsureDispatch('VirtualBox.Session')
|
---|
480 | win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBox')
|
---|
481 | win32com.client.gencache.EnsureDispatch('VirtualBox.VirtualBoxClient')
|
---|
482 |
|
---|
483 | self.oClient = None ##< instance of client used to support lifetime of VBoxSDS
|
---|
484 | self.oIntCv = threading.Condition()
|
---|
485 | self.fInterrupted = False
|
---|
486 |
|
---|
487 | _ = dParams
|
---|
488 |
|
---|
489 | def flushGenPyCache(self, oGenCache):
|
---|
490 | """
|
---|
491 | Flushes VBox related files in the win32com gen_py cache.
|
---|
492 |
|
---|
493 | This is necessary since we don't follow the typelib versioning rules
|
---|
494 | that everyeone else seems to subscribe to.
|
---|
495 | """
|
---|
496 | #
|
---|
497 | # The EnsureModule method have broken validation code, it doesn't take
|
---|
498 | # typelib module directories into account. So we brute force them here.
|
---|
499 | # (It's possible the directory approach is from some older pywin
|
---|
500 | # version or the result of runnig makepy or gencache manually, but we
|
---|
501 | # need to cover it as well.)
|
---|
502 | #
|
---|
503 | sName = oGenCache.GetGeneratedFileName(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID,
|
---|
504 | self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR)
|
---|
505 | sGenPath = oGenCache.GetGeneratePath()
|
---|
506 | if len(sName) > 36 and len(sGenPath) > 5:
|
---|
507 | sTypelibPath = os.path.join(sGenPath, sName)
|
---|
508 | if os.path.isdir(sTypelibPath):
|
---|
509 | import shutil
|
---|
510 | shutil.rmtree(sTypelibPath, ignore_errors=True)
|
---|
511 |
|
---|
512 | #
|
---|
513 | # Ensure that our typelib is valid.
|
---|
514 | #
|
---|
515 | return oGenCache.EnsureModule(self.VBOX_TLB_GUID, self.VBOX_TLB_LCID, self.VBOX_TLB_MAJOR, self.VBOX_TLB_MINOR)
|
---|
516 |
|
---|
517 | def getSessionObject(self):
|
---|
518 | import win32com
|
---|
519 | from win32com.client import Dispatch
|
---|
520 | return win32com.client.Dispatch("VirtualBox.Session")
|
---|
521 |
|
---|
522 | def getVirtualBox(self):
|
---|
523 | # Caching self.oClient is the trick for SDS. It allows to keep the
|
---|
524 | # VBoxSDS in the memory until the end of PlatformMSCOM lifetme.
|
---|
525 | if self.oClient is None:
|
---|
526 | import win32com
|
---|
527 | from win32com.client import Dispatch
|
---|
528 | self.oClient = win32com.client.Dispatch("VirtualBox.VirtualBoxClient")
|
---|
529 | return self.oClient.virtualBox
|
---|
530 |
|
---|
531 | def getType(self):
|
---|
532 | return 'MSCOM'
|
---|
533 |
|
---|
534 | def getArray(self, oInterface, sAttrib):
|
---|
535 | return oInterface.__getattr__(sAttrib)
|
---|
536 |
|
---|
537 | def setArray(self, oInterface, sAttrib, aoArray):
|
---|
538 | #
|
---|
539 | # HACK ALERT!
|
---|
540 | #
|
---|
541 | # With pywin32 build 218, we're seeing type mismatch errors here for
|
---|
542 | # IGuestSession::environmentChanges (safearray of BSTRs). The Dispatch
|
---|
543 | # object (_oleobj_) seems to get some type conversion wrong and COM
|
---|
544 | # gets upset. So, we redo some of the dispatcher work here, picking
|
---|
545 | # the missing type information from the getter.
|
---|
546 | #
|
---|
547 | oOleObj = getattr(oInterface, '_oleobj_')
|
---|
548 | aPropMapGet = getattr(oInterface, '_prop_map_get_')
|
---|
549 | aPropMapPut = getattr(oInterface, '_prop_map_put_')
|
---|
550 | sComAttrib = sAttrib if sAttrib in aPropMapGet else ComifyName(sAttrib)
|
---|
551 | try:
|
---|
552 | aArgs, aDefaultArgs = aPropMapPut[sComAttrib]
|
---|
553 | aGetArgs = aPropMapGet[sComAttrib]
|
---|
554 | except KeyError: # fallback.
|
---|
555 | return oInterface.__setattr__(sAttrib, aoArray)
|
---|
556 |
|
---|
557 | import pythoncom
|
---|
558 | oOleObj.InvokeTypes(aArgs[0], # dispid
|
---|
559 | aArgs[1], # LCID
|
---|
560 | aArgs[2], # DISPATCH_PROPERTYPUT
|
---|
561 | (pythoncom.VT_HRESULT, 0), # retType - or void?
|
---|
562 | (aGetArgs[2],), # argTypes - trick: we get the type from the getter.
|
---|
563 | aoArray,) # The array
|
---|
564 |
|
---|
565 | def initPerThread(self):
|
---|
566 | import pythoncom
|
---|
567 | pythoncom.CoInitializeEx(0)
|
---|
568 |
|
---|
569 | def deinitPerThread(self):
|
---|
570 | import pythoncom
|
---|
571 | pythoncom.CoUninitialize()
|
---|
572 |
|
---|
573 | def createListener(self, oImplClass, dArgs):
|
---|
574 | if True:
|
---|
575 | raise Exception('no active listeners on Windows as PyGatewayBase::QueryInterface() '
|
---|
576 | 'returns new gateway objects all the time, thus breaking EventQueue '
|
---|
577 | 'assumptions about the listener interface pointer being constants between calls ')
|
---|
578 | # Did this code ever really work?
|
---|
579 | d = {}
|
---|
580 | d['BaseClass'] = oImplClass
|
---|
581 | d['dArgs'] = dArgs
|
---|
582 | d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID
|
---|
583 | d['tlb_major'] = PlatformMSCOM.VBOX_TLB_MAJOR
|
---|
584 | d['tlb_minor'] = PlatformMSCOM.VBOX_TLB_MINOR
|
---|
585 | str_ = ""
|
---|
586 | str_ += "import win32com.server.util\n"
|
---|
587 | str_ += "import pythoncom\n"
|
---|
588 |
|
---|
589 | str_ += "class ListenerImpl(BaseClass):\n"
|
---|
590 | str_ += " _com_interfaces_ = ['IEventListener']\n"
|
---|
591 | str_ += " _typelib_guid_ = tlb_guid\n"
|
---|
592 | str_ += " _typelib_version_ = tlb_major, tlb_minor\n"
|
---|
593 | str_ += " _reg_clsctx_ = pythoncom.CLSCTX_INPROC_SERVER\n"
|
---|
594 | # Maybe we'd better implement Dynamic invoke policy, to be more flexible here
|
---|
595 | str_ += " _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"
|
---|
596 |
|
---|
597 | # capitalized version of listener method
|
---|
598 | str_ += " HandleEvent=BaseClass.handleEvent\n"
|
---|
599 | str_ += " def __init__(self): BaseClass.__init__(self, dArgs)\n"
|
---|
600 | str_ += "result = win32com.server.util.wrap(ListenerImpl())\n"
|
---|
601 | exec(str_, d, d)
|
---|
602 | return d['result']
|
---|
603 |
|
---|
604 | def waitForEvents(self, timeout):
|
---|
605 | from win32api import GetCurrentThreadId
|
---|
606 | from win32event import INFINITE
|
---|
607 | from win32event import MsgWaitForMultipleObjects, QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0
|
---|
608 | from pythoncom import PumpWaitingMessages
|
---|
609 | import types
|
---|
610 |
|
---|
611 | if not isinstance(timeout, int):
|
---|
612 | raise TypeError("The timeout argument is not an integer")
|
---|
613 | if self.tid != GetCurrentThreadId():
|
---|
614 | raise Exception("wait for events from the same thread you inited!")
|
---|
615 |
|
---|
616 | if timeout < 0:
|
---|
617 | cMsTimeout = INFINITE
|
---|
618 | else:
|
---|
619 | cMsTimeout = timeout
|
---|
620 | rc = MsgWaitForMultipleObjects(self.aoHandles, 0, cMsTimeout, QS_ALLINPUT)
|
---|
621 | if WAIT_OBJECT_0 <= rc < WAIT_OBJECT_0 + len(self.aoHandles):
|
---|
622 | # is it possible?
|
---|
623 | rc = 2
|
---|
624 | elif rc == WAIT_OBJECT_0 + len(self.aoHandles):
|
---|
625 | # Waiting messages
|
---|
626 | PumpWaitingMessages()
|
---|
627 | rc = 0
|
---|
628 | else:
|
---|
629 | # Timeout
|
---|
630 | rc = 1
|
---|
631 |
|
---|
632 | # check for interruption
|
---|
633 | self.oIntCv.acquire()
|
---|
634 | if self.fInterrupted:
|
---|
635 | self.fInterrupted = False
|
---|
636 | rc = 1
|
---|
637 | self.oIntCv.release()
|
---|
638 |
|
---|
639 | return rc
|
---|
640 |
|
---|
641 | def interruptWaitEvents(self):
|
---|
642 | """
|
---|
643 | Basically a python implementation of NativeEventQueue::postEvent().
|
---|
644 |
|
---|
645 | The magic value must be in sync with the C++ implementation or this
|
---|
646 | won't work.
|
---|
647 |
|
---|
648 | Note that because of this method we cannot easily make use of a
|
---|
649 | non-visible Window to handle the message like we would like to do.
|
---|
650 | """
|
---|
651 | from win32api import PostThreadMessage
|
---|
652 | from win32con import WM_USER
|
---|
653 |
|
---|
654 | self.oIntCv.acquire()
|
---|
655 | self.fInterrupted = True
|
---|
656 | self.oIntCv.release()
|
---|
657 | try:
|
---|
658 | PostThreadMessage(self.tid, WM_USER, None, 0xf241b819)
|
---|
659 | except:
|
---|
660 | return False
|
---|
661 | return True
|
---|
662 |
|
---|
663 | def deinit(self):
|
---|
664 | import pythoncom
|
---|
665 |
|
---|
666 | for oHandle in self.aoHandles:
|
---|
667 | if oHandle is not None:
|
---|
668 | oHandle.Close();
|
---|
669 | self.oHandle = None;
|
---|
670 |
|
---|
671 | del self.oClient;
|
---|
672 | self.oClient = None;
|
---|
673 |
|
---|
674 | pythoncom.CoUninitialize()
|
---|
675 |
|
---|
676 | def queryInterface(self, oIUnknown, sClassName):
|
---|
677 | from win32com.client import CastTo
|
---|
678 | return CastTo(oIUnknown, sClassName)
|
---|
679 |
|
---|
680 | def xcptGetStatus(self, oXcpt):
|
---|
681 | # The DISP_E_EXCEPTION + excptinfo fun needs checking up, only
|
---|
682 | # empirical info on it so far.
|
---|
683 | hrXcpt = oXcpt.hresult
|
---|
684 | if hrXcpt == self.winerror.DISP_E_EXCEPTION:
|
---|
685 | try:
|
---|
686 | hrXcpt = oXcpt.excepinfo[5]
|
---|
687 | except:
|
---|
688 | pass
|
---|
689 | return hrXcpt
|
---|
690 |
|
---|
691 | def xcptIsDeadInterface(self, oXcpt):
|
---|
692 | return self.xcptGetStatus(oXcpt) in [
|
---|
693 | 0x800706ba, -2147023174, # RPC_S_SERVER_UNAVAILABLE.
|
---|
694 | 0x800706be, -2147023170, # RPC_S_CALL_FAILED.
|
---|
695 | 0x800706bf, -2147023169, # RPC_S_CALL_FAILED_DNE.
|
---|
696 | 0x80010108, -2147417848, # RPC_E_DISCONNECTED.
|
---|
697 | 0x800706b5, -2147023179, # RPC_S_UNKNOWN_IF
|
---|
698 | ]
|
---|
699 |
|
---|
700 | def xcptGetMessage(self, oXcpt):
|
---|
701 | if hasattr(oXcpt, 'excepinfo'):
|
---|
702 | try:
|
---|
703 | if len(oXcpt.excepinfo) >= 3:
|
---|
704 | sRet = oXcpt.excepinfo[2]
|
---|
705 | if len(sRet) > 0:
|
---|
706 | return sRet[0:]
|
---|
707 | except:
|
---|
708 | pass
|
---|
709 | if hasattr(oXcpt, 'strerror'):
|
---|
710 | try:
|
---|
711 | sRet = oXcpt.strerror
|
---|
712 | if len(sRet) > 0:
|
---|
713 | return sRet
|
---|
714 | except:
|
---|
715 | pass
|
---|
716 | return None
|
---|
717 |
|
---|
718 | def xcptGetBaseXcpt(self):
|
---|
719 | import pythoncom
|
---|
720 |
|
---|
721 | return pythoncom.com_error
|
---|
722 |
|
---|
723 | def xcptSetupConstants(self, oDst):
|
---|
724 | import winerror
|
---|
725 |
|
---|
726 | oDst = self.xcptCopyErrorConstants(oDst, winerror)
|
---|
727 |
|
---|
728 | # XPCOM compatability constants.
|
---|
729 | oDst.NS_OK = oDst.S_OK
|
---|
730 | oDst.NS_ERROR_FAILURE = oDst.E_FAIL
|
---|
731 | oDst.NS_ERROR_ABORT = oDst.E_ABORT
|
---|
732 | oDst.NS_ERROR_NULL_POINTER = oDst.E_POINTER
|
---|
733 | oDst.NS_ERROR_NO_INTERFACE = oDst.E_NOINTERFACE
|
---|
734 | oDst.NS_ERROR_INVALID_ARG = oDst.E_INVALIDARG
|
---|
735 | oDst.NS_ERROR_OUT_OF_MEMORY = oDst.E_OUTOFMEMORY
|
---|
736 | oDst.NS_ERROR_NOT_IMPLEMENTED = oDst.E_NOTIMPL
|
---|
737 | oDst.NS_ERROR_UNEXPECTED = oDst.E_UNEXPECTED
|
---|
738 | return oDst
|
---|
739 |
|
---|
740 |
|
---|
741 | class PlatformXPCOM(PlatformBase):
|
---|
742 | """
|
---|
743 | Platform specific code for XPCOM.
|
---|
744 | """
|
---|
745 |
|
---|
746 | def __init__(self, dParams):
|
---|
747 | PlatformBase.__init__(self, dParams)
|
---|
748 | sys.path.append(VBoxSdkDir + '/bindings/xpcom/python/')
|
---|
749 | import xpcom.vboxxpcom
|
---|
750 | import xpcom
|
---|
751 | import xpcom.components
|
---|
752 | _ = dParams
|
---|
753 |
|
---|
754 | def getSessionObject(self):
|
---|
755 | import xpcom.components
|
---|
756 | return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
|
---|
757 |
|
---|
758 | def getVirtualBox(self):
|
---|
759 | import xpcom.components
|
---|
760 | client = xpcom.components.classes["@virtualbox.org/VirtualBoxClient;1"].createInstance()
|
---|
761 | return client.virtualBox
|
---|
762 |
|
---|
763 | def getType(self):
|
---|
764 | return 'XPCOM'
|
---|
765 |
|
---|
766 | def getArray(self, oInterface, sAttrib):
|
---|
767 | return oInterface.__getattr__('get' + ComifyName(sAttrib))()
|
---|
768 |
|
---|
769 | def setArray(self, oInterface, sAttrib, aoArray):
|
---|
770 | return oInterface.__getattr__('set' + ComifyName(sAttrib))(aoArray)
|
---|
771 |
|
---|
772 | def initPerThread(self):
|
---|
773 | import xpcom
|
---|
774 | xpcom._xpcom.AttachThread()
|
---|
775 |
|
---|
776 | def deinitPerThread(self):
|
---|
777 | import xpcom
|
---|
778 | xpcom._xpcom.DetachThread()
|
---|
779 |
|
---|
780 | def createListener(self, oImplClass, dArgs):
|
---|
781 | d = {}
|
---|
782 | d['BaseClass'] = oImplClass
|
---|
783 | d['dArgs'] = dArgs
|
---|
784 | str = ""
|
---|
785 | str += "import xpcom.components\n"
|
---|
786 | str += "class ListenerImpl(BaseClass):\n"
|
---|
787 | str += " _com_interfaces_ = xpcom.components.interfaces.IEventListener\n"
|
---|
788 | str += " def __init__(self): BaseClass.__init__(self, dArgs)\n"
|
---|
789 | str += "result = ListenerImpl()\n"
|
---|
790 | exec(str, d, d)
|
---|
791 | return d['result']
|
---|
792 |
|
---|
793 | def waitForEvents(self, timeout):
|
---|
794 | import xpcom
|
---|
795 | return xpcom._xpcom.WaitForEvents(timeout)
|
---|
796 |
|
---|
797 | def interruptWaitEvents(self):
|
---|
798 | import xpcom
|
---|
799 | return xpcom._xpcom.InterruptWait()
|
---|
800 |
|
---|
801 | def deinit(self):
|
---|
802 | import xpcom
|
---|
803 | xpcom._xpcom.DeinitCOM()
|
---|
804 |
|
---|
805 | def queryInterface(self, oIUnknown, sClassName):
|
---|
806 | import xpcom.components
|
---|
807 | return oIUnknown.queryInterface(getattr(xpcom.components.interfaces, sClassName))
|
---|
808 |
|
---|
809 | def xcptGetStatus(self, oXcpt):
|
---|
810 | return oXcpt.errno
|
---|
811 |
|
---|
812 | def xcptIsDeadInterface(self, oXcpt):
|
---|
813 | return self.xcptGetStatus(oXcpt) in [
|
---|
814 | 0x80004004, -2147467260, # NS_ERROR_ABORT
|
---|
815 | 0x800706be, -2147023170, # NS_ERROR_CALL_FAILED (RPC_S_CALL_FAILED)
|
---|
816 | ]
|
---|
817 |
|
---|
818 | def xcptGetMessage(self, oXcpt):
|
---|
819 | if hasattr(oXcpt, 'msg'):
|
---|
820 | try:
|
---|
821 | sRet = oXcpt.msg
|
---|
822 | if len(sRet) > 0:
|
---|
823 | return sRet
|
---|
824 | except:
|
---|
825 | pass
|
---|
826 | return None
|
---|
827 |
|
---|
828 | def xcptGetBaseXcpt(self):
|
---|
829 | import xpcom
|
---|
830 | return xpcom.Exception
|
---|
831 |
|
---|
832 | def xcptSetupConstants(self, oDst):
|
---|
833 | import xpcom
|
---|
834 | oDst = self.xcptCopyErrorConstants(oDst, xpcom.nsError)
|
---|
835 |
|
---|
836 | # COM compatability constants.
|
---|
837 | oDst.E_ACCESSDENIED = -2147024891 # see VBox/com/defs.h
|
---|
838 | oDst.S_OK = oDst.NS_OK
|
---|
839 | oDst.E_FAIL = oDst.NS_ERROR_FAILURE
|
---|
840 | oDst.E_ABORT = oDst.NS_ERROR_ABORT
|
---|
841 | oDst.E_POINTER = oDst.NS_ERROR_NULL_POINTER
|
---|
842 | oDst.E_NOINTERFACE = oDst.NS_ERROR_NO_INTERFACE
|
---|
843 | oDst.E_INVALIDARG = oDst.NS_ERROR_INVALID_ARG
|
---|
844 | oDst.E_OUTOFMEMORY = oDst.NS_ERROR_OUT_OF_MEMORY
|
---|
845 | oDst.E_NOTIMPL = oDst.NS_ERROR_NOT_IMPLEMENTED
|
---|
846 | oDst.E_UNEXPECTED = oDst.NS_ERROR_UNEXPECTED
|
---|
847 | oDst.DISP_E_EXCEPTION = -2147352567 # For COM compatability only.
|
---|
848 | return oDst
|
---|
849 |
|
---|
850 |
|
---|
851 | class PlatformWEBSERVICE(PlatformBase):
|
---|
852 | """
|
---|
853 | VirtualBox Web Services API specific code.
|
---|
854 | """
|
---|
855 |
|
---|
856 | def __init__(self, dParams):
|
---|
857 | PlatformBase.__init__(self, dParams)
|
---|
858 | # Import web services stuff. Fix the sys.path the first time.
|
---|
859 | sWebServLib = os.path.join(VBoxSdkDir, 'bindings', 'webservice', 'python', 'lib')
|
---|
860 | if sWebServLib not in sys.path:
|
---|
861 | sys.path.append(sWebServLib)
|
---|
862 | import VirtualBox_wrappers
|
---|
863 | from VirtualBox_wrappers import IWebsessionManager2
|
---|
864 |
|
---|
865 | # Initialize instance variables from parameters.
|
---|
866 | if dParams is not None:
|
---|
867 | self.user = dParams.get("user", "")
|
---|
868 | self.password = dParams.get("password", "")
|
---|
869 | self.url = dParams.get("url", "")
|
---|
870 | else:
|
---|
871 | self.user = ""
|
---|
872 | self.password = ""
|
---|
873 | self.url = None
|
---|
874 | self.vbox = None
|
---|
875 | self.wsmgr = None
|
---|
876 |
|
---|
877 | #
|
---|
878 | # Base class overrides.
|
---|
879 | #
|
---|
880 |
|
---|
881 | def getSessionObject(self):
|
---|
882 | return self.wsmgr.getSessionObject(self.vbox)
|
---|
883 |
|
---|
884 | def getVirtualBox(self):
|
---|
885 | return self.connect(self.url, self.user, self.password)
|
---|
886 |
|
---|
887 | def getType(self):
|
---|
888 | return 'WEBSERVICE'
|
---|
889 |
|
---|
890 | def isRemote(self):
|
---|
891 | """ Returns True if remote VBox host, False if local. """
|
---|
892 | return True
|
---|
893 |
|
---|
894 | def getArray(self, oInterface, sAttrib):
|
---|
895 | return oInterface.__getattr__(sAttrib)
|
---|
896 |
|
---|
897 | def setArray(self, oInterface, sAttrib, aoArray):
|
---|
898 | return oInterface.__setattr__(sAttrib, aoArray)
|
---|
899 |
|
---|
900 | def waitForEvents(self, timeout):
|
---|
901 | # Webservices cannot do that yet
|
---|
902 | return 2
|
---|
903 |
|
---|
904 | def interruptWaitEvents(self, timeout):
|
---|
905 | # Webservices cannot do that yet
|
---|
906 | return False
|
---|
907 |
|
---|
908 | def deinit(self):
|
---|
909 | try:
|
---|
910 | self.disconnect()
|
---|
911 | except:
|
---|
912 | pass
|
---|
913 |
|
---|
914 | def queryInterface(self, oIUnknown, sClassName):
|
---|
915 | d = {}
|
---|
916 | d['oIUnknown'] = oIUnknown
|
---|
917 | str = ""
|
---|
918 | str += "from VirtualBox_wrappers import " + sClassName + "\n"
|
---|
919 | str += "result = " + sClassName + "(oIUnknown.mgr, oIUnknown.handle)\n"
|
---|
920 | # wrong, need to test if class indeed implements this interface
|
---|
921 | exec(str, d, d)
|
---|
922 | return d['result']
|
---|
923 |
|
---|
924 | #
|
---|
925 | # Web service specific methods.
|
---|
926 | #
|
---|
927 |
|
---|
928 | def connect(self, url, user, passwd):
|
---|
929 | if self.vbox is not None:
|
---|
930 | self.disconnect()
|
---|
931 | from VirtualBox_wrappers import IWebsessionManager2
|
---|
932 |
|
---|
933 | if url is None:
|
---|
934 | url = ""
|
---|
935 | self.url = url
|
---|
936 | if user is None:
|
---|
937 | user = ""
|
---|
938 | self.user = user
|
---|
939 | if passwd is None:
|
---|
940 | passwd = ""
|
---|
941 | self.password = passwd
|
---|
942 | self.wsmgr = IWebsessionManager2(self.url)
|
---|
943 | self.vbox = self.wsmgr.logon(self.user, self.password)
|
---|
944 | if not self.vbox.handle:
|
---|
945 | raise Exception("cannot connect to '" + self.url + "' as '" + self.user + "'")
|
---|
946 | return self.vbox
|
---|
947 |
|
---|
948 | def disconnect(self):
|
---|
949 | if self.vbox is not None and self.wsmgr is not None:
|
---|
950 | self.wsmgr.logoff(self.vbox)
|
---|
951 | self.vbox = None
|
---|
952 | self.wsmgr = None
|
---|
953 |
|
---|
954 |
|
---|
955 | ## The current (last) exception class.
|
---|
956 | # This is reinitalized whenever VirtualBoxManager is called, so it will hold
|
---|
957 | # the reference to the error exception class for the last platform/style that
|
---|
958 | # was used. Most clients does talk to multiple VBox instance on different
|
---|
959 | # platforms at the same time, so this should be sufficent for most uses and
|
---|
960 | # be way simpler to use than VirtualBoxManager::oXcptClass.
|
---|
961 | CurXctpClass = None
|
---|
962 |
|
---|
963 |
|
---|
964 | class VirtualBoxManager(object):
|
---|
965 | """
|
---|
966 | VirtualBox API manager class.
|
---|
967 |
|
---|
968 | The API users will have to instantiate this. If no parameters are given,
|
---|
969 | it will default to interface with the VirtualBox running on the local
|
---|
970 | machine. sStyle can be None (default), MSCOM, XPCOM or WEBSERVICES. Most
|
---|
971 | users will either be specifying None or WEBSERVICES.
|
---|
972 |
|
---|
973 | The dPlatformParams is an optional dictionary for passing parameters to the
|
---|
974 | WEBSERVICE backend.
|
---|
975 | """
|
---|
976 |
|
---|
977 | class Statuses(object):
|
---|
978 | def __init__(self):
|
---|
979 | pass
|
---|
980 |
|
---|
981 | def __init__(self, sStyle=None, dPlatformParams=None):
|
---|
982 | if sStyle is None:
|
---|
983 | if sys.platform == 'win32':
|
---|
984 | sStyle = "MSCOM"
|
---|
985 | else:
|
---|
986 | sStyle = "XPCOM"
|
---|
987 | if sStyle == 'XPCOM':
|
---|
988 | self.platform = PlatformXPCOM(dPlatformParams)
|
---|
989 | elif sStyle == 'MSCOM':
|
---|
990 | self.platform = PlatformMSCOM(dPlatformParams)
|
---|
991 | elif sStyle == 'WEBSERVICE':
|
---|
992 | self.platform = PlatformWEBSERVICE(dPlatformParams)
|
---|
993 | else:
|
---|
994 | raise Exception('Unknown sStyle=%s' % (sStyle,))
|
---|
995 | self.style = sStyle
|
---|
996 | self.type = self.platform.getType()
|
---|
997 | self.remote = self.platform.isRemote()
|
---|
998 | ## VirtualBox API constants (for webservices, enums are symbolic).
|
---|
999 | self.constants = VirtualBoxReflectionInfo(sStyle == "WEBSERVICE")
|
---|
1000 |
|
---|
1001 | ## Status constants.
|
---|
1002 | self.statuses = self.platform.xcptSetupConstants(VirtualBoxManager.Statuses())
|
---|
1003 | ## @todo Add VBOX_E_XXX to statuses? They're already in constants...
|
---|
1004 | ## Dictionary for errToString, built on demand.
|
---|
1005 | self._dErrorValToName = None
|
---|
1006 |
|
---|
1007 | ## The exception class for the selected platform.
|
---|
1008 | self.oXcptClass = self.platform.xcptGetBaseXcpt()
|
---|
1009 | global CurXcptClass
|
---|
1010 | CurXcptClass = self.oXcptClass
|
---|
1011 |
|
---|
1012 | # Get the virtualbox singleton.
|
---|
1013 | try:
|
---|
1014 | vbox = self.platform.getVirtualBox()
|
---|
1015 | except NameError:
|
---|
1016 | print("Installation problem: check that appropriate libs in place")
|
---|
1017 | traceback.print_exc()
|
---|
1018 | raise
|
---|
1019 | except Exception:
|
---|
1020 | _, e, _ = sys.exc_info()
|
---|
1021 | print("init exception: ", e)
|
---|
1022 | traceback.print_exc()
|
---|
1023 |
|
---|
1024 | def __del__(self):
|
---|
1025 | self.deinit()
|
---|
1026 |
|
---|
1027 | def getPythonApiRevision(self):
|
---|
1028 | """
|
---|
1029 | Returns a Python API revision number.
|
---|
1030 | This will be incremented when features are added to this file.
|
---|
1031 | """
|
---|
1032 | return 3
|
---|
1033 |
|
---|
1034 | @property
|
---|
1035 | def mgr(self):
|
---|
1036 | """
|
---|
1037 | This used to be an attribute referring to a session manager class with
|
---|
1038 | only one method called getSessionObject. It moved into this class.
|
---|
1039 | """
|
---|
1040 | return self
|
---|
1041 |
|
---|
1042 | #
|
---|
1043 | # Wrappers for self.platform methods.
|
---|
1044 | #
|
---|
1045 | def getVirtualBox(self):
|
---|
1046 | """ See PlatformBase::getVirtualBox(). """
|
---|
1047 | return self.platform.getVirtualBox()
|
---|
1048 |
|
---|
1049 | def getSessionObject(self, oIVBox = None):
|
---|
1050 | """ See PlatformBase::getSessionObject(). """
|
---|
1051 | # ignore parameter which was never needed
|
---|
1052 | _ = oIVBox
|
---|
1053 | return self.platform.getSessionObject()
|
---|
1054 |
|
---|
1055 | def getArray(self, oInterface, sAttrib):
|
---|
1056 | """ See PlatformBase::getArray(). """
|
---|
1057 | return self.platform.getArray(oInterface, sAttrib)
|
---|
1058 |
|
---|
1059 | def setArray(self, oInterface, sAttrib, aoArray):
|
---|
1060 | """ See PlatformBase::setArray(). """
|
---|
1061 | return self.platform.setArray(oInterface, sAttrib, aoArray)
|
---|
1062 |
|
---|
1063 | def createListener(self, oImplClass, dArgs=None):
|
---|
1064 | """ See PlatformBase::createListener(). """
|
---|
1065 | return self.platform.createListener(oImplClass, dArgs)
|
---|
1066 |
|
---|
1067 | def waitForEvents(self, cMsTimeout):
|
---|
1068 | """ See PlatformBase::waitForEvents(). """
|
---|
1069 | return self.platform.waitForEvents(cMsTimeout)
|
---|
1070 |
|
---|
1071 | def interruptWaitEvents(self):
|
---|
1072 | """ See PlatformBase::interruptWaitEvents(). """
|
---|
1073 | return self.platform.interruptWaitEvents()
|
---|
1074 |
|
---|
1075 | def queryInterface(self, oIUnknown, sClassName):
|
---|
1076 | """ See PlatformBase::queryInterface(). """
|
---|
1077 | return self.platform.queryInterface(oIUnknown, sClassName)
|
---|
1078 |
|
---|
1079 | #
|
---|
1080 | # Init and uninit.
|
---|
1081 | #
|
---|
1082 | def initPerThread(self):
|
---|
1083 | """ See PlatformBase::deinitPerThread(). """
|
---|
1084 | self.platform.initPerThread()
|
---|
1085 |
|
---|
1086 | def deinitPerThread(self):
|
---|
1087 | """ See PlatformBase::deinitPerThread(). """
|
---|
1088 | return self.platform.deinitPerThread()
|
---|
1089 |
|
---|
1090 | def deinit(self):
|
---|
1091 | """
|
---|
1092 | For unitializing the manager.
|
---|
1093 | Do not access it after calling this method.
|
---|
1094 | """
|
---|
1095 | if hasattr(self, "platform") and self.platform is not None:
|
---|
1096 | self.platform.deinit()
|
---|
1097 | self.platform = None
|
---|
1098 | return True
|
---|
1099 |
|
---|
1100 | #
|
---|
1101 | # Utility methods.
|
---|
1102 | #
|
---|
1103 | def openMachineSession(self, oIMachine, fPermitSharing=True):
|
---|
1104 | """
|
---|
1105 | Attempts to open the a session to the machine.
|
---|
1106 | Returns a session object on success.
|
---|
1107 | Raises exception on failure.
|
---|
1108 | """
|
---|
1109 | oSession = self.getSessionObject()
|
---|
1110 | if fPermitSharing:
|
---|
1111 | eType = self.constants.LockType_Shared
|
---|
1112 | else:
|
---|
1113 | eType = self.constants.LockType_Write
|
---|
1114 | oIMachine.lockMachine(oSession, eType)
|
---|
1115 | return oSession
|
---|
1116 |
|
---|
1117 | def closeMachineSession(self, oSession):
|
---|
1118 | """
|
---|
1119 | Closes a session opened by openMachineSession.
|
---|
1120 | Ignores None parameters.
|
---|
1121 | """
|
---|
1122 | if oSession is not None:
|
---|
1123 | oSession.unlockMachine()
|
---|
1124 | return True
|
---|
1125 |
|
---|
1126 | def getPerfCollector(self, oIVBox):
|
---|
1127 | """
|
---|
1128 | Returns a helper class (PerfCollector) for accessing performance
|
---|
1129 | collector goodies. See PerfCollector for details.
|
---|
1130 | """
|
---|
1131 | return PerfCollector(self, oIVBox)
|
---|
1132 |
|
---|
1133 | def getBinDir(self):
|
---|
1134 | """
|
---|
1135 | Returns the VirtualBox binary directory.
|
---|
1136 | """
|
---|
1137 | global VBoxBinDir
|
---|
1138 | return VBoxBinDir
|
---|
1139 |
|
---|
1140 | def getSdkDir(self):
|
---|
1141 | """
|
---|
1142 | Returns the VirtualBox SDK directory.
|
---|
1143 | """
|
---|
1144 | global VBoxSdkDir
|
---|
1145 | return VBoxSdkDir
|
---|
1146 |
|
---|
1147 | #
|
---|
1148 | # Error code utilities.
|
---|
1149 | #
|
---|
1150 | ## @todo port to webservices!
|
---|
1151 | def xcptGetStatus(self, oXcpt=None):
|
---|
1152 | """
|
---|
1153 | Gets the status code from an exception. If the exception parameter
|
---|
1154 | isn't specified, the current exception is examined.
|
---|
1155 | """
|
---|
1156 | if oXcpt is None:
|
---|
1157 | oXcpt = sys.exc_info()[1]
|
---|
1158 | return self.platform.xcptGetStatus(oXcpt)
|
---|
1159 |
|
---|
1160 | def xcptIsDeadInterface(self, oXcpt=None):
|
---|
1161 | """
|
---|
1162 | Returns True if the exception indicates that the interface is dead,
|
---|
1163 | False if not. If the exception parameter isn't specified, the current
|
---|
1164 | exception is examined.
|
---|
1165 | """
|
---|
1166 | if oXcpt is None:
|
---|
1167 | oXcpt = sys.exc_info()[1]
|
---|
1168 | return self.platform.xcptIsDeadInterface(oXcpt)
|
---|
1169 |
|
---|
1170 | def xcptIsOurXcptKind(self, oXcpt=None):
|
---|
1171 | """
|
---|
1172 | Checks if the exception is one that could come from the VBox API. If
|
---|
1173 | the exception parameter isn't specified, the current exception is
|
---|
1174 | examined.
|
---|
1175 | """
|
---|
1176 | if self.oXcptClass is None: # @todo find the exception class for web services!
|
---|
1177 | return False
|
---|
1178 | if oXcpt is None:
|
---|
1179 | oXcpt = sys.exc_info()[1]
|
---|
1180 | return isinstance(oXcpt, self.oXcptClass)
|
---|
1181 |
|
---|
1182 | def xcptIsEqual(self, oXcpt, hrStatus):
|
---|
1183 | """
|
---|
1184 | Checks if the exception oXcpt is equal to the COM/XPCOM status code
|
---|
1185 | hrStatus.
|
---|
1186 |
|
---|
1187 | The oXcpt parameter can be any kind of object, we'll just return True
|
---|
1188 | if it doesn't behave like a our exception class. If it's None, we'll
|
---|
1189 | query the current exception and examine that.
|
---|
1190 |
|
---|
1191 | Will not raise any exception as long as hrStatus and self are not bad.
|
---|
1192 | """
|
---|
1193 | if oXcpt is None:
|
---|
1194 | oXcpt = sys.exc_info()[1]
|
---|
1195 | return self.platform.xcptIsEqual(oXcpt, hrStatus)
|
---|
1196 |
|
---|
1197 | def xcptIsNotEqual(self, oXcpt, hrStatus):
|
---|
1198 | """
|
---|
1199 | Negated xcptIsEqual.
|
---|
1200 | """
|
---|
1201 | return not self.xcptIsEqual(oXcpt, hrStatus)
|
---|
1202 |
|
---|
1203 | def xcptToString(self, hrStatusOrXcpt=None):
|
---|
1204 | """
|
---|
1205 | Converts the specified COM status code, or the status code of the
|
---|
1206 | specified exception, to a C constant string. If the parameter isn't
|
---|
1207 | specified (is None), the current exception is examined.
|
---|
1208 | """
|
---|
1209 |
|
---|
1210 | # Deal with exceptions.
|
---|
1211 | if hrStatusOrXcpt is None or self.xcptIsOurXcptKind(hrStatusOrXcpt):
|
---|
1212 | hrStatus = self.xcptGetStatus(hrStatusOrXcpt)
|
---|
1213 | else:
|
---|
1214 | hrStatus = hrStatusOrXcpt
|
---|
1215 |
|
---|
1216 | # Build the dictionary on demand.
|
---|
1217 | if self._dErrorValToName is None:
|
---|
1218 | dErrorValToName = dict()
|
---|
1219 | for sKey in dir(self.statuses):
|
---|
1220 | if sKey[0].isupper():
|
---|
1221 | oValue = getattr(self.statuses, sKey)
|
---|
1222 | if type(oValue) is int:
|
---|
1223 | dErrorValToName[oValue] = sKey
|
---|
1224 | self._dErrorValToName = dErrorValToName
|
---|
1225 |
|
---|
1226 | # Do the lookup, falling back on formatting the status number.
|
---|
1227 | try:
|
---|
1228 | sStr = self._dErrorValToName[int(hrStatus)]
|
---|
1229 | except KeyError:
|
---|
1230 | hrLong = long(hrStatus)
|
---|
1231 | sStr = '%#x (%d)' % (hrLong, hrLong)
|
---|
1232 | return sStr
|
---|
1233 |
|
---|
1234 | def xcptGetMessage(self, oXcpt=None):
|
---|
1235 | """
|
---|
1236 | Returns the best error message found in the COM-like exception. If the
|
---|
1237 | exception parameter isn't specified, the current exception is examined.
|
---|
1238 | """
|
---|
1239 | if oXcpt is None:
|
---|
1240 | oXcpt = sys.exc_info()[1]
|
---|
1241 | sRet = self.platform.xcptGetMessage(oXcpt)
|
---|
1242 | if sRet is None:
|
---|
1243 | sRet = self.xcptToString(oXcpt)
|
---|
1244 | return sRet
|
---|
1245 |
|
---|
1246 | # Legacy, remove in a day or two.
|
---|
1247 | errGetStatus = xcptGetStatus
|
---|
1248 | errIsDeadInterface = xcptIsDeadInterface
|
---|
1249 | errIsOurXcptKind = xcptIsOurXcptKind
|
---|
1250 | errGetMessage = xcptGetMessage
|
---|
1251 |
|
---|