VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/python/sample/shellcommon.py@ 12752

Last change on this file since 12752 was 12752, checked in by vboxsync, 17 years ago

implemented much better error reporting for Python bindings

  • Property svn:eol-style set to native
File size: 10.5 KB
Line 
1import traceback
2import sys
3import pdb
4
5g_hasreadline = 1
6try:
7 import readline
8 import rlcompleter
9except:
10 g_hasreadline = 0
11
12
13if g_hasreadline:
14 class CompleterNG(rlcompleter.Completer):
15 def __init__(self, dic, ctx):
16 self.ctx = ctx
17 return rlcompleter.Completer.__init__(self,dic)
18
19 def complete(self, text, state):
20 """
21 taken from:
22 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496812
23 """
24 if text == "":
25 return ['\t',None][state]
26 else:
27 return rlcompleter.Completer.complete(self,text,state)
28
29 def global_matches(self, text):
30 """
31 Compute matches when text is a simple name.
32 Return a list of all names currently defined
33 in self.namespace that match.
34 """
35
36 matches = []
37 n = len(text)
38
39 for list in [ self.namespace ]:
40 for word in list:
41 if word[:n] == text:
42 matches.append(word)
43
44
45 try:
46 for m in getMachines(self.ctx):
47 # although it has autoconversion, we need to cast
48 # explicitly for subscripts to work
49 word = str(m.name)
50 if word[:n] == text:
51 matches.append(word)
52 word = str(m.id)
53 if word[0] == '{':
54 word = word[1:-1]
55 if word[:n] == text:
56 matches.append(word)
57 except Exception,e:
58 traceback.print_exc()
59 print e
60
61 return matches
62
63
64def autoCompletion(commands, ctx):
65 if not g_hasreadline:
66 return
67
68 comps = {}
69 for (k,v) in commands.items():
70 comps[k] = None
71 completer = CompleterNG(comps, ctx)
72 readline.set_completer(completer.complete)
73 readline.parse_and_bind("tab: complete")
74
75g_verbose = True
76
77def split_no_quotes(s):
78 return s.split()
79
80def startVm(mgr,vb,mach,type):
81 session = mgr.getSessionObject(vb)
82 uuid = mach.id
83 progress = vb.openRemoteSession(session, uuid, type, "")
84 progress.waitForCompletion(-1)
85 completed = progress.completed
86 rc = progress.resultCode
87 print "Completed:", completed, "rc:",rc
88 if rc == 0:
89 try:
90 vb.performanceCollector.setupMetrics(['*'], [mach], 10, 15)
91 except:
92 pass
93 session.close()
94
95def getMachines(ctx):
96 return ctx['vb'].getMachines2()
97
98def asState(var):
99 if var:
100 return 'on'
101 else:
102 return 'off'
103
104def guestStats(ctx,mach):
105 collector = ctx['vb'].performanceCollector
106 (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [mach])
107 for i in range(0,len(names)):
108 valsStr = '[ '
109 for j in range(0, lens[i]):
110 valsStr += str(vals[idxs[i]])+' '
111 valsStr += ']'
112 print names[i],valsStr
113
114def cmdExistingVm(ctx,mach,cmd):
115 mgr=ctx['mgr']
116 vb=ctx['vb']
117 session = mgr.getSessionObject(vb)
118 uuid = mach.id
119 try:
120 progress = vb.openExistingSession(session, uuid)
121 except Exception,e:
122 print "Session to '%s' not open: %s" %(mach.name,e)
123 if g_verbose:
124 traceback.print_exc()
125 return
126 if session.state != ctx['ifaces'].SessionState.Open:
127 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
128 return
129 # unfortunately IGuest is suppressed, thus WebServices knows not about it
130 # this is an example how to handle local only functionality
131 if ctx['remote'] and cmd == 'stats2':
132 print 'Trying to use local only functionality, ignored'
133 return
134 console=session.console
135 ops={'pause' : lambda: console.pause(),
136 'resume': lambda: console.resume(),
137 'powerdown': lambda: console.powerDown(),
138 'stats': lambda: guestStats(ctx, mach),
139 }
140 ops[cmd]()
141 session.close()
142
143# can cache known machines, if needed
144def machById(ctx,id):
145 mach = None
146 for m in getMachines(ctx):
147 if m.name == id:
148 mach = m
149 break
150 mid = str(m.id)
151 if mid[0] == '{':
152 mid = mid[1:-1]
153 if mid == id:
154 mach = m
155 break
156 return mach
157
158def argsToMach(ctx,args):
159 if len(args) < 2:
160 print "usage: %s [vmname|uuid]" %(args[0])
161 return None
162 id = args[1]
163 m = machById(ctx, id)
164 if m == None:
165 print "Machine '%s' is unknown, use list command to find available machines" %(id)
166 return m
167
168def helpCmd(ctx, args):
169 if len(args) == 1:
170 print "Help page:"
171 for i in commands:
172 print " ",i,":", commands[i][0]
173 else:
174 c = commands.get(args[1], None)
175 if c == None:
176 print "Command '%s' not known" %(args[1])
177 else:
178 print " ",args[1],":", c[0]
179 return 0
180
181def listCmd(ctx, args):
182 for m in getMachines(ctx):
183 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
184 return 0
185
186def infoCmd(ctx,args):
187 if (len(args) < 2):
188 print "usage: info [vmname|uuid]"
189 return 0
190 mach = argsToMach(ctx,args)
191 if mach == None:
192 return 0
193 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
194 print " Name: ",mach.name
195 print " ID: ",mach.id
196 print " OS Type: ",os.description
197 print " RAM: %dM" %(mach.memorySize)
198 print " VRAM: %dM" %(mach.VRAMSize)
199 print " Monitors: %d" %(mach.MonitorCount)
200 print " Clipboard mode: %d" %(mach.clipboardMode)
201 print " Machine status: " ,mach.sessionState
202 bios = mach.BIOSSettings
203 print " BIOS ACPI: ",bios.ACPIEnabled
204 print " PAE: ",mach.PAEEnabled
205 print " Hardware virtualization: ",asState(mach.HWVirtExEnabled)
206 print " Nested paging: ",asState(mach.HWVirtExNestedPagingEnabled)
207 print " Last changed: ",mach.lastStateChange
208
209 return 0
210
211def startCmd(ctx, args):
212 mach = argsToMach(ctx,args)
213 if mach == None:
214 return 0
215 if len(args) > 2:
216 type = args[2]
217 else:
218 type = "gui"
219 startVm(ctx['mgr'], ctx['vb'], mach, type)
220 return 0
221
222def pauseCmd(ctx, args):
223 mach = argsToMach(ctx,args)
224 if mach == None:
225 return 0
226 cmdExistingVm(ctx, mach, 'pause')
227 return 0
228
229def powerdownCmd(ctx, args):
230 mach = argsToMach(ctx,args)
231 if mach == None:
232 return 0
233 cmdExistingVm(ctx, mach, 'powerdown')
234 return 0
235
236def resumeCmd(ctx, args):
237 mach = argsToMach(ctx,args)
238 if mach == None:
239 return 0
240 cmdExistingVm(ctx, mach, 'resume')
241 return 0
242
243def statsCmd(ctx, args):
244 mach = argsToMach(ctx,args)
245 if mach == None:
246 return 0
247 cmdExistingVm(ctx, mach, 'stats')
248 return 0
249
250def setvarCmd(ctx, args):
251 if (len(args) < 4):
252 print "usage: setvar [vmname|uuid] expr value"
253 return 0
254 mach = argsToMach(ctx,args)
255 if mach == None:
256 return 0
257 vbox = ctx['vb']
258 session = ctx['mgr'].getSessionObject(vbox)
259 vbox.openSession(session, mach.id)
260 mach = session.machine
261 expr = 'mach.'+args[2]+' = '+args[3]
262 print "Executing",expr
263 try:
264 exec expr
265 except Exception, e:
266 print 'failed: ',e
267 if g_verbose:
268 traceback.print_exc()
269 mach.saveSettings()
270 session.close()
271 return 0
272
273def quitCmd(ctx, args):
274 return 1
275
276def aliasesCmd(ctx, args):
277 for (k,v) in aliases.items():
278 print "'%s' is an alias for '%s'" %(k,v)
279 return 0
280
281def verboseCmd(ctx, args):
282 global g_verbose
283 g_verbose = not g_verbose
284 return 0
285
286def hostCmd(ctx, args):
287 host = ctx['vb'].host
288 cnt = host.processorCount
289 print "Processor count:",cnt
290 for i in range(0,cnt):
291 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
292
293 collector = ctx['vb'].performanceCollector
294
295 (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [host])
296 for i in range(0,len(names)):
297 valsStr = '[ '
298 for j in range(0, lens[i]):
299 valsStr += str(vals[idxs[i]])+' '
300 valsStr += ']'
301 print names[i],valsStr
302
303 return 0
304
305
306def evalCmd(ctx, args):
307 expr = ' '.join(args[1:])
308 try:
309 exec expr
310 except Exception, e:
311 print 'failed: ',e
312 if g_verbose:
313 traceback.print_exc()
314 return 0
315
316aliases = {'s':'start',
317 'i':'info',
318 'l':'list',
319 'h':'help',
320 'a':'aliases',
321 'q':'quit', 'exit':'quit',
322 'v':'verbose'}
323
324commands = {'help':['Prints help information', helpCmd],
325 'start':['Start virtual machine by name or uuid', startCmd],
326 'pause':['Pause virtual machine', pauseCmd],
327 'resume':['Resume virtual machine', resumeCmd],
328 'stats':['Stats for virtual machine', statsCmd],
329 'powerdown':['Power down virtual machine', powerdownCmd],
330 'list':['Shows known virtual machines', listCmd],
331 'info':['Shows info on machine', infoCmd],
332 'aliases':['Shows aliases', aliasesCmd],
333 'verbose':['Toggle verbosity', verboseCmd],
334 'setvar':['Set VMs variable: setvar Fedora BIOSSettings.ACPIEnabled True', setvarCmd],
335 'eval':['Evaluate arbitrary Python construction: eval for m in getMachines(ctx): print m.name,"has",m.memorySize,"M"', evalCmd],
336 'quit':['Exits', quitCmd],
337 'host':['Show host information', hostCmd]}
338
339def runCommand(ctx, cmd):
340 if len(cmd) == 0: return 0
341 args = split_no_quotes(cmd)
342 if len(args) == 0: return 0
343 c = args[0]
344 if aliases.get(c, None) != None:
345 c = aliases[c]
346 ci = commands.get(c,None)
347 if ci == None:
348 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
349 return 0
350 return ci[1](ctx, args)
351
352
353def interpret(ctx):
354 vbox = ctx['vb']
355 print "Running VirtualBox version %s" %(vbox.version)
356
357 autoCompletion(commands, ctx)
358
359 # to allow to print actual host information, we collect info for
360 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
361 try:
362 vbox.performanceCollector.setupMetrics(['*'], [vbox.host], 10, 15)
363 except:
364 pass
365
366 while True:
367 try:
368 cmd = raw_input("vbox> ")
369 done = runCommand(ctx, cmd)
370 if done != 0: break
371 except KeyboardInterrupt:
372 print '====== You can type quit or q to leave'
373 break
374 except EOFError:
375 break;
376 except Exception,e:
377 print e
378 if g_verbose:
379 traceback.print_exc()
380
381 try:
382 vbox.performanceCollector.disableMetrics(['*'], [vbox.host])
383 except:
384 pass
Note: See TracBrowser for help on using the repository browser.

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