VirtualBox

source: vbox/trunk/src/VBox/Main/glue/vboxapi.py@ 21087

Last change on this file since 21087 was 20926, checked in by vboxsync, 16 years ago

Python: fixed typo, improvments for the shell

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.0 KB
Line 
1#
2# Copyright (C) 2009 Sun Microsystems, Inc.
3#
4# This file is part of VirtualBox Open Source Edition (OSE), as
5# available from http://www.virtualbox.org. This file is free software;
6# you can redistribute it and/or modify it under the terms of the GNU
7# General Public License (GPL) as published by the Free Software
8# Foundation, in version 2 as it comes in the "COPYING" file of the
9# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
10# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
11#
12# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
13# Clara, CA 95054 USA or visit http://www.sun.com if you need
14# additional information or have any questions.
15#
16import sys,os
17import traceback
18
19VboxBinDir = os.environ.get("VBOX_PROGRAM_PATH", None)
20VboxSdkDir = os.environ.get("VBOX_SDK_PATH", None)
21
22if VboxBinDir is None:
23 # Will be set by the installer
24 VboxBinDir = "%VBOX_INSTALL_PATH%"
25
26if VboxSdkDir is None:
27 VboxSdkDir = VboxBinDir+"/sdk"
28
29os.environ["VBOX_PROGRAM_PATH"] = VboxBinDir
30os.environ["VBOX_SDK_PATH"] = VboxSdkDir
31sys.path.append(VboxBinDir)
32
33from VirtualBox_constants import VirtualBoxReflectionInfo
34
35class PerfCollector:
36 """ This class provides a wrapper over IPerformanceCollector in order to
37 get more 'pythonic' interface.
38
39 To begin collection of metrics use setup() method.
40
41 To get collected data use query() method.
42
43 It is possible to disable metric collection without changing collection
44 parameters with disable() method. The enable() method resumes metric
45 collection.
46 """
47
48 def __init__(self, vb):
49 """ Initializes the instance.
50
51 Pass an instance of IVirtualBox as parameter.
52 """
53 self.collector = vb.performanceCollector
54
55 def setup(self, names, objects, period, nsamples):
56 """ Discards all previously collected values for the specified
57 metrics, sets the period of collection and the number of retained
58 samples, enables collection.
59 """
60 self.collector.setupMetrics(names, objects, period, nsamples)
61
62 def enable(self, names, objects):
63 """ Resumes metric collection for the specified metrics.
64 """
65 self.collector.enableMetrics(names, objects)
66
67 def disable(self, names, objects):
68 """ Suspends metric collection for the specified metrics.
69 """
70 self.collector.disableMetrics(names, objects)
71
72 def query(self, names, objects):
73 """ Retrieves collected metric values as well as some auxiliary
74 information. Returns an array of dictionaries, one dictionary per
75 metric. Each dictionary contains the following entries:
76 'name': metric name
77 'object': managed object this metric associated with
78 'unit': unit of measurement
79 'scale': divide 'values' by this number to get float numbers
80 'values': collected data
81 'values_as_string': pre-processed values ready for 'print' statement
82 """
83 (values, names_out, objects_out, units, scales, sequence_numbers,
84 indices, lengths) = self.collector.queryMetricsData(names, objects)
85 out = []
86 for i in xrange(0, len(names_out)):
87 scale = int(scales[i])
88 if scale != 1:
89 fmt = '%.2f%s'
90 else:
91 fmt = '%d %s'
92 out.append({
93 'name':str(names_out[i]),
94 'object':str(objects_out[i]),
95 'unit':str(units[i]),
96 'scale':scale,
97 'values':[int(values[j]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))],
98 'values_as_string':'['+', '.join([fmt % (int(values[j])/scale, units[i]) for j in xrange(int(indices[i]), int(indices[i])+int(lengths[i]))])+']'
99 })
100 return out
101
102class PlatformMSCOM:
103 # Class to fake access to constants in style of foo.bar.boo
104 class ConstantFake:
105 def __init__(self, parent, name):
106 self.__dict__['_parent'] = parent
107 self.__dict__['_name'] = name
108 self.__dict__['_consts'] = {}
109 try:
110 self.__dict__['_depth']=parent.__dict__['_depth']+1
111 except:
112 self.__dict__['_depth']=0
113 if self.__dict__['_depth'] > 4:
114 raise AttributeError
115
116 def __getattr__(self, attr):
117 import win32com
118 from win32com.client import constants
119
120 if attr.startswith("__"):
121 raise AttributeError
122
123 consts = self.__dict__['_consts']
124
125 fake = consts.get(attr, None)
126 if fake != None:
127 return fake
128 try:
129 name = self.__dict__['_name']
130 parent = self.__dict__['_parent']
131 while parent != None:
132 if parent._name is not None:
133 name = parent._name+'_'+name
134 parent = parent._parent
135
136 if name is not None:
137 name += "_" + attr
138 else:
139 name = attr
140 return win32com.client.constants.__getattr__(name)
141 except AttributeError,e:
142 fake = PlatformMSCOM.ConstantFake(self, attr)
143 consts[attr] = fake
144 return fake
145
146
147 class InterfacesWrapper:
148 def __init__(self):
149 self.__dict__['_rootFake'] = PlatformMSCOM.ConstantFake(None, None)
150
151 def __getattr__(self, a):
152 import win32com
153 from win32com.client import constants
154 if a.startswith("__"):
155 raise AttributeError
156 try:
157 return win32com.client.constants.__getattr__(a)
158 except AttributeError,e:
159 return self.__dict__['_rootFake'].__getattr__(a)
160
161 VBOX_TLB_GUID = '{46137EEC-703B-4FE5-AFD4-7C9BBBBA0259}'
162 VBOX_TLB_LCID = 0
163 VBOX_TLB_MAJOR = 1
164 VBOX_TLB_MINOR = 0
165
166 def __init__(self, params):
167 from win32com import universal
168 from win32com.client import gencache, DispatchWithEvents, Dispatch
169 from win32com.client import constants, getevents
170 import win32com
171 import pythoncom
172 import win32api
173 self.constants = PlatformMSCOM.InterfacesWrapper()
174 from win32con import DUPLICATE_SAME_ACCESS
175 from win32api import GetCurrentThread,GetCurrentThreadId,DuplicateHandle,GetCurrentProcess
176 pid = GetCurrentProcess()
177 self.tid = GetCurrentThreadId()
178 handle = DuplicateHandle(pid, GetCurrentThread(), pid, 0, 0, DUPLICATE_SAME_ACCESS)
179 self.handles = []
180 self.handles.append(handle)
181
182
183 def getSessionObject(self, vbox):
184 import win32com
185 from win32com.client import Dispatch
186 return win32com.client.Dispatch("VirtualBox.Session")
187
188 def getVirtualBox(self):
189 import win32com
190 from win32com.client import Dispatch
191 return win32com.client.Dispatch("VirtualBox.VirtualBox")
192
193 def getConstants(self):
194 return self.constants
195
196 def getType(self):
197 return 'MSCOM'
198
199 def getRemote(self):
200 return False
201
202 def getArray(self, obj, field):
203 return obj.__getattr__(field)
204
205 def initPerThread(self):
206 import pythoncom
207 pythoncom.CoInitializeEx(0)
208
209 def deinitPerThread(self):
210 import pythoncom
211 pythoncom.CoUninitialize()
212
213 def createCallback(self, iface, impl, arg):
214 d = {}
215 d['BaseClass'] = impl
216 d['arg'] = arg
217 d['tlb_guid'] = PlatformMSCOM.VBOX_TLB_GUID
218 str = ""
219 str += "import win32com.server.util\n"
220 #str += "import win32com.server.register\n"
221 #str += "from win32com import universal\n"
222 str += "import pythoncom\n"
223 #str += "universal.RegisterInterfaces(tlb_guid, 0, 1, 0, ['"+iface+"'])\n"
224
225 str += "class "+iface+"Impl(BaseClass):\n"
226 str += " _com_interfaces_ = ['"+iface+"']\n"
227 str += " _typelib_guid_ = tlb_guid\n"
228 str += " _typelib_version_ = 1, 0\n"
229 #str += " _reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER\n"
230 #str += " _reg_clsid_ = '{F21202A2-959A-4149-B1C3-68B9013F3335}'\n"
231 #str += " _reg_progid_ = 'VirtualBox."+iface+"Impl'\n"
232 #str += " _reg_desc_ = 'Generated callback implementation class'\n"
233 #str += " _reg_policy_spec_ = 'win32com.server.policy.EventHandlerPolicy'\n"
234
235 # generate capitalized version of callbacks - that's how Python COM
236 # looks them up on Windows
237 for m in dir(impl):
238 if m.startswith("on"):
239 str += " "+m[0].capitalize()+m[1:]+"=BaseClass."+m+"\n"
240
241 str += " def __init__(self): BaseClass.__init__(self, arg)\n"
242 #str += "win32com.server.register.UseCommandLine("+iface+"Impl)\n"
243
244 str += "result = win32com.server.util.wrap("+iface+"Impl())\n"
245 exec (str,d,d)
246 return d['result']
247
248 def waitForEvents(self, timeout):
249 from win32api import GetCurrentThreadId
250 from win32event import MsgWaitForMultipleObjects, \
251 QS_ALLINPUT, WAIT_TIMEOUT, WAIT_OBJECT_0
252 from pythoncom import PumpWaitingMessages
253
254 if (self.tid != GetCurrentThreadId()):
255 raise Exception("wait for events from the same thread you inited!")
256
257 rc = MsgWaitForMultipleObjects(self.handles, 0, timeout, QS_ALLINPUT)
258 if rc >= WAIT_OBJECT_0 and rc < WAIT_OBJECT_0+len(self.handles):
259 # is it possible?
260 pass
261 elif rc==WAIT_OBJECT_0 + len(self.handles):
262 # Waiting messages
263 PumpWaitingMessages()
264 else:
265 # Timeout
266 pass
267
268 def deinit(self):
269 import pythoncom
270 from win32file import CloseHandle
271
272 for h in self.handles:
273 if h is not None:
274 CloseHandle(h)
275 self.handles = None
276 pythoncom.CoUninitialize()
277 pass
278
279 def getPerfCollector(self, vbox):
280 # MS COM cannot invoke performance collector methods yet
281 return None
282
283
284class PlatformXPCOM:
285 def __init__(self, params):
286 sys.path.append(VboxSdkDir+'/bindings/xpcom/python/')
287 import xpcom.vboxxpcom
288 import xpcom
289 import xpcom.components
290
291 def getSessionObject(self, vbox):
292 import xpcom.components
293 return xpcom.components.classes["@virtualbox.org/Session;1"].createInstance()
294
295 def getVirtualBox(self):
296 import xpcom.components
297 return xpcom.components.classes["@virtualbox.org/VirtualBox;1"].createInstance()
298
299 def getConstants(self):
300 import xpcom.components
301 return xpcom.components.interfaces
302
303 def getType(self):
304 return 'XPCOM'
305
306 def getRemote(self):
307 return False
308
309 def getArray(self, obj, field):
310 return obj.__getattr__('get'+field.capitalize())()
311
312 def initPerThread(self):
313 pass
314
315 def deinitPerThread(self):
316 pass
317
318 def createCallback(self, iface, impl, arg):
319 d = {}
320 d['BaseClass'] = impl
321 d['arg'] = arg
322 str = ""
323 str += "import xpcom.components\n"
324 str += "class "+iface+"Impl(BaseClass):\n"
325 str += " _com_interfaces_ = xpcom.components.interfaces."+iface+"\n"
326 str += " def __init__(self): BaseClass.__init__(self, arg)\n"
327 str += "result = "+iface+"Impl()\n"
328 exec (str,d,d)
329 return d['result']
330
331 def waitForEvents(self, timeout):
332 import xpcom
333 xpcom._xpcom.WaitForEvents(timeout)
334
335 def deinit(self):
336 import xpcom
337 xpcom._xpcom.DeinitCOM()
338
339 def getPerfCollector(self, vbox):
340 return PerfCollector(vbox)
341
342class PlatformWEBSERVICE:
343 def __init__(self, params):
344 sys.path.append(VboxSdkDir+'/bindings/webservice/python/lib')
345 import VirtualBox_services
346 import VirtualBox_wrappers
347 from VirtualBox_wrappers import IWebsessionManager2
348 if params is not None:
349 self.user = params.get("user", "")
350 self.password = params.get("password", "")
351 self.url = params.get("url", "")
352 else:
353 self.user = ""
354 self.password = ""
355 self.url = None
356 self.wsmgr = IWebsessionManager2(self.url)
357
358 def getSessionObject(self, vbox):
359 return self.wsmgr.getSessionObject(vbox)
360
361 def getVirtualBox(self):
362 self.vbox = self.wsmgr.logon(self.user, self.password)
363
364 def getConstants(self):
365 return None
366
367 def getType(self):
368 return 'WEBSERVICE'
369
370 def getRemote(self):
371 return True
372
373 def getArray(self, obj, field):
374 return obj.__getattr__(field)
375
376 def initPerThread(self):
377 pass
378
379 def deinitPerThread(self):
380 pass
381
382 def createCallback(self, iface, impl, arg):
383 raise Exception("no callbacks for webservices")
384
385 def waitForEvents(self, timeout):
386 # Webservices cannot do that yet
387 pass
388
389 def deinit(self):
390 try:
391 if self.vbox is not None:
392 self.wsmg.logoff(self.vbox)
393 self.vbox = None
394 except:
395 pass
396
397 def getPerfCollector(self, vbox):
398 return PerfCollector(vbox)
399
400class SessionManager:
401 def __init__(self, mgr):
402 self.mgr = mgr
403
404 def getSessionObject(self, vbox):
405 return self.mgr.platform.getSessionObject(vbox)
406
407class VirtualBoxManager:
408 def __init__(self, style, platparams):
409 if style is None:
410 if sys.platform == 'win32':
411 style = "MSCOM"
412 else:
413 style = "XPCOM"
414 try:
415 exec "self.platform = Platform"+style+"(platparams)"
416 self.vbox = self.platform.getVirtualBox()
417 self.mgr = SessionManager(self)
418 self.constants = VirtualBoxReflectionInfo()
419 self.type = self.platform.getType()
420 self.remote = self.platform.getRemote()
421 self.style = style
422 except Exception,e:
423 print "init exception: ",e
424 traceback.print_exc()
425 raise e
426
427 def getArray(self, obj, field):
428 return self.platform.getArray(obj, field)
429
430 def getVirtualBox(self):
431 return self.platform.getVirtualBox()
432
433 def __del__(self):
434 self.deinit()
435
436 def deinit(self):
437 if hasattr(self, "vbox"):
438 del self.vbox
439 self.vbox = None
440 if hasattr(self, "platform"):
441 self.platform.deinit()
442 self.platform = None
443
444 def initPerThread(self):
445 self.platform.initPerThread()
446
447 def openMachineSession(self, machineId):
448 session = self.mgr.getSessionObject(self.vbox)
449 self.vbox.openSession(session, machineId)
450 return session
451
452 def closeMachineSession(self, session):
453 session.close()
454
455 def deinitPerThread(self):
456 self.platform.deinitPerThread()
457
458 def createCallback(self, iface, impl, arg):
459 return self.platform.createCallback(iface, impl, arg)
460
461 def waitForEvents(self, timeout):
462 return self.platform.waitForEvents(timeout)
463
464 def getPerfCollector(self, vbox):
465 return self.platform.getPerfCollector(vbox)
Note: See TracBrowser for help on using the repository browser.

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