VirtualBox

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

Last change on this file since 12403 was 12403, checked in by vboxsync, 17 years ago
  • stats related fixes in shell
  • Property svn:eol-style set to native
File size: 10.8 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 session.close()
89
90def getMachines(ctx):
91 return ctx['vb'].getMachines2()
92
93def asState(var):
94 if var:
95 return 'on'
96 else:
97 return 'off'
98
99def guestStats2(ctx,guest):
100 stats = {
101 'Guest statistics for sample': ctx['ifaces'].GuestStatisticType.SampleNumber,
102 'CPU Load Idle': ctx['ifaces'].GuestStatisticType.CPULoad_Idle,
103 'CPU Load User': ctx['ifaces'].GuestStatisticType.CPULoad_User,
104 'CPU Load Kernel': ctx['ifaces'].GuestStatisticType.CPULoad_Kernel,
105 'Threads': ctx['ifaces'].GuestStatisticType.Threads,
106 'Processes': ctx['ifaces'].GuestStatisticType.Processes,
107 'Handles': ctx['ifaces'].GuestStatisticType.Handles,
108 }
109 for (k,v) in stats.items():
110 try:
111 val = guest.getStatistic(0, v)
112 print "'%s' = '%s'" %(k,str(v))
113 except:
114 print "Cannot get value for '%s'" %(k)
115 pass
116
117def guestStats(ctx,mach):
118 collector = ctx['vb'].performanceCollector
119 collector.setupMetrics(['*'], [mach], 1, 15)
120
121 (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [mach])
122 for i in range(0,len(names)):
123 valsStr = '['
124 for j in range(0, lens[i]):
125 valsStr += str(vals[idxs[i]])+' '
126 valsStr += ']'
127 print "Name:",names[i],"Vals:",valsStr
128
129def cmdExistingVm(ctx,mach,cmd):
130 mgr=ctx['mgr']
131 vb=ctx['vb']
132 session = mgr.getSessionObject(vb)
133 uuid = mach.id
134 try:
135 progress = vb.openExistingSession(session, uuid)
136 except Exception,e:
137 print "Session to '%s' not open: %s" %(mach.name,e)
138 if g_verbose:
139 traceback.print_exc()
140 return
141 if session.state != ctx['ifaces'].SessionState.Open:
142 print "Session to '%s' in wrong state: %s" %(mach.name, session.state)
143 return
144 # unfortunately IGuest is suppressed, thus WebServices knows not about it
145 if ctx['remote'] and cmd == 'stats2':
146 print 'Trying to use local only functionality, ignored'
147 return
148 console=session.console
149 ops={'pause' : lambda: console.pause(),
150 'resume': lambda: console.resume(),
151 'powerdown': lambda: console.powerDown(),
152# Guest stats not yet implemented
153# 'stats2': lambda: guestStats2(ctx, console.guest),
154# 'stats': lambda: guestStats(ctx, mach),
155 }
156 ops[cmd]()
157 session.close()
158
159# can cache known machines, if needed
160def machById(ctx,id):
161 mach = None
162 for m in getMachines(ctx):
163 if m.name == id:
164 mach = m
165 break
166 mid = str(m.id)
167 if mid[0] == '{':
168 mid = mid[1:-1]
169 if mid == id:
170 mach = m
171 break
172 return mach
173
174def argsToMach(ctx,args):
175 if len(args) < 2:
176 print "usage: %s [vmname|uuid]" %(args[0])
177 return None
178 id = args[1]
179 m = machById(ctx, id)
180 if m == None:
181 print "Machine '%s' is unknown, use list command to find available machines" %(id)
182 return m
183
184def helpCmd(ctx, args):
185 if len(args) == 1:
186 print "Help page:"
187 for i in commands:
188 print " ",i,":", commands[i][0]
189 else:
190 c = commands.get(args[1], None)
191 if c == None:
192 print "Command '%s' not known" %(args[1])
193 else:
194 print " ",args[1],":", c[0]
195 return 0
196
197def listCmd(ctx, args):
198 for m in getMachines(ctx):
199 print "Machine '%s' [%s], state=%s" %(m.name,m.id,m.sessionState)
200 return 0
201
202def infoCmd(ctx,args):
203 if (len(args) < 2):
204 print "usage: info [vmname|uuid]"
205 return 0
206 mach = argsToMach(ctx,args)
207 if mach == None:
208 return 0
209 os = ctx['vb'].getGuestOSType(mach.OSTypeId)
210 print " Name: ",mach.name
211 print " ID: ",mach.id
212 print " OS Type: ",os.description
213 print " RAM: %dM" %(mach.memorySize)
214 print " VRAM: %dM" %(mach.VRAMSize)
215 print " Monitors: %d" %(mach.MonitorCount)
216 print " Clipboard mode: %d" %(mach.clipboardMode)
217 print " Machine status: " ,mach.sessionState
218 bios = mach.BIOSSettings
219 print " BIOS ACPI: ",bios.ACPIEnabled
220 print " PAE: ",mach.PAEEnabled
221 print " Hardware virtualization: ",asState(mach.HWVirtExEnabled)
222 print " Nested paging: ",asState(mach.HWVirtExNestedPagingEnabled)
223 print " Last changed: ",mach.lastStateChange
224
225 return 0
226
227def startCmd(ctx, args):
228 mach = argsToMach(ctx,args)
229 if mach == None:
230 return 0
231 if len(args) > 2:
232 type = args[2]
233 else:
234 type = "gui"
235 startVm(ctx['mgr'], ctx['vb'], mach, type)
236 return 0
237
238def pauseCmd(ctx, args):
239 mach = argsToMach(ctx,args)
240 if mach == None:
241 return 0
242 cmdExistingVm(ctx, mach, 'pause')
243 return 0
244
245def powerdownCmd(ctx, args):
246 mach = argsToMach(ctx,args)
247 if mach == None:
248 return 0
249 cmdExistingVm(ctx, mach, 'powerdown')
250 return 0
251
252def resumeCmd(ctx, args):
253 mach = argsToMach(ctx,args)
254 if mach == None:
255 return 0
256 cmdExistingVm(ctx, mach, 'resume')
257 return 0
258
259def statsCmd(ctx, args):
260 mach = argsToMach(ctx,args)
261 if mach == None:
262 return 0
263 cmdExistingVm(ctx, mach, 'stats')
264 return 0
265
266def setvarCmd(ctx, args):
267 if (len(args) < 4):
268 print "usage: setvar [vmname|uuid] expr value"
269 return 0
270 mach = argsToMach(ctx,args)
271 if mach == None:
272 return 0
273 vbox = ctx['vb']
274 session = ctx['mgr'].getSessionObject(vbox)
275 vbox.openSession(session, mach.id)
276 mach = session.machine
277 expr = 'mach.'+args[2]+' = '+args[3]
278 print "Executing",expr
279 try:
280 exec expr
281 except Exception, e:
282 print 'failed: ',e
283 if g_verbose:
284 traceback.print_exc()
285 mach.saveSettings()
286 session.close()
287 return 0
288
289def quitCmd(ctx, args):
290 return 1
291
292def aliasesCmd(ctx, args):
293 for (k,v) in aliases.items():
294 print "'%s' is an alias for '%s'" %(k,v)
295 return 0
296
297def verboseCmd(ctx, args):
298 global g_verbose
299 g_verbose = not g_verbose
300 return 0
301
302def hostCmd(ctx, args):
303 host = ctx['vb'].host
304 cnt = host.processorCount
305 print "Processor count:",cnt
306 for i in range(0,cnt):
307 print "Processor #%d speed: %dMHz" %(i,host.getProcessorSpeed(i))
308
309 collector = ctx['vb'].performanceCollector
310
311 (vals, names, objs, idxs, lens) = collector.queryMetricsData(["*"], [host])
312 for i in range(0,len(names)):
313 valsStr = '['
314 for j in range(0, lens[i]):
315 valsStr += str(vals[idxs[i]])+' '
316 valsStr += ']'
317 print "Name:",names[i],"Vals:",valsStr
318
319 return 0
320
321aliases = {'s':'start',
322 'i':'info',
323 'l':'list',
324 'h':'help',
325 'a':'aliases',
326 'q':'quit', 'exit':'quit',
327 'v':'verbose'}
328
329commands = {'help':['Prints help information', helpCmd],
330 'start':['Start virtual machine by name or uuid', startCmd],
331 'pause':['Pause virtual machine', pauseCmd],
332 'resume':['Resume virtual machine', resumeCmd],
333# stats not yet well implemented
334 'stats':['Stats for virtual machine', statsCmd],
335 'powerdown':['Power down virtual machine', powerdownCmd],
336 'list':['Shows known virtual machines', listCmd],
337 'info':['Shows info on machine', infoCmd],
338 'aliases':['Shows aliases', aliasesCmd],
339 'verbose':['Toggle verbosity', verboseCmd],
340 'setvar':['Set VMs variable: "setvar Fedora BIOSSettings.ACPIEnabled True"', setvarCmd],
341 'quit':['Exits', quitCmd],
342 'host':['Show host information', hostCmd]}
343
344def runCommand(ctx, cmd):
345 if len(cmd) == 0: return 0
346 args = split_no_quotes(cmd)
347 c = args[0]
348 if aliases.get(c, None) != None:
349 c = aliases[c]
350 ci = commands.get(c,None)
351 if ci == None:
352 print "Unknown command: '%s', type 'help' for list of known commands" %(c)
353 return 0
354 return ci[1](ctx, args)
355
356
357def interpret(ctx):
358 vbox = ctx['vb']
359 print "Running VirtualBox version %s" %(vbox.version)
360
361 autoCompletion(commands, ctx)
362
363 # to allow to print actual host information, we collect infor for
364 # last 150 secs maximum, (sample every 10 secs and keep up to 15 samples)
365 vbox.performanceCollector.setupMetrics(['*'], [vbox.host], 10, 15)
366
367 while True:
368 try:
369 cmd = raw_input("vbox> ")
370 done = runCommand(ctx, cmd)
371 if done != 0: break
372 except KeyboardInterrupt:
373 print '====== You can type quit or q to leave'
374 break
375 except EOFError:
376 break;
377 except Exception,e:
378 print e
379 if g_verbose:
380 traceback.print_exc()
381
382 vbox.performanceCollector.disableMetrics(['*'], [vbox.host])
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