VirtualBox

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

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

updated Python to make better setters, improved shell to allow variable setting

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