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