3 # Low-level QEMU shell on top of QMP.
5 # Copyright (C) 2009, 2010 Red Hat Inc.
8 # Luiz Capitulino <lcapitulino@redhat.com>
10 # This work is licensed under the terms of the GNU GPL, version 2. See
11 # the COPYING file in the top-level directory.
17 # # qemu [...] -qmp unix:./qmp-sock,server
21 # $ qmp-shell ./qmp-sock
23 # Commands have the following format:
25 # < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
29 # (QEMU) device_add driver=e1000 id=net1
40 class QMPCompleter(list):
41 def complete(self, text, state):
43 if cmd.startswith(text):
49 class QMPShellError(Exception):
52 class QMPShellBadPort(QMPShellError):
55 class FuzzyJSON(ast.NodeTransformer):
56 '''This extension of ast.NodeTransformer filters literal "true/false/null"
57 values in an AST and replaces them by proper "True/False/None" values that
58 Python can properly evaluate.'''
59 def visit_Name(self, node):
62 if node.id == 'false':
68 # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
69 # _execute_cmd()). Let's design a better one.
70 class QMPShell(qmp.QEMUMonitorProtocol):
71 def __init__(self, address, pp=None):
72 qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address))
74 self._completer = None
76 self._transmode = False
77 self._actions = list()
79 def __get_address(self, arg):
81 Figure out if the argument is in the port:host form, if it's not it's
90 return ( addr[0], port )
94 def _fill_completion(self):
95 for cmd in self.cmd('query-commands')['return']:
96 self._completer.append(cmd['name'])
98 def __completer_setup(self):
99 self._completer = QMPCompleter()
100 self._fill_completion()
101 readline.set_completer(self._completer.complete)
102 readline.parse_and_bind("tab: complete")
103 # XXX: default delimiters conflict with some command names (eg. query-),
104 # clearing everything as it doesn't seem to matter
105 readline.set_completer_delims('')
107 def __parse_value(self, val):
113 if val.lower() == 'true':
115 if val.lower() == 'false':
117 if val.startswith(('{', '[')):
118 # Try first as pure JSON:
120 return json.loads(val)
123 # Try once again as FuzzyJSON:
125 st = ast.parse(val, mode='eval')
126 return ast.literal_eval(FuzzyJSON().visit(st))
133 def __cli_expr(self, tokens, parent):
135 (key, _, val) = arg.partition('=')
137 raise QMPShellError("Expected a key=value pair, got '%s'" % arg)
139 value = self.__parse_value(val)
140 optpath = key.split('.')
142 for p in optpath[:-1]:
144 d = parent.get(p, {})
145 if type(d) is not dict:
146 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
149 if optpath[-1] in parent:
150 if type(parent[optpath[-1]]) is dict:
151 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
153 raise QMPShellError('Cannot set "%s" multiple times' % key)
154 parent[optpath[-1]] = value
156 def __build_cmd(self, cmdline):
158 Build a QMP input object from a user provided command-line in the
161 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
163 cmdargs = cmdline.split()
165 # Transactional CLI entry/exit:
166 if cmdargs[0] == 'transaction(':
167 self._transmode = True
169 elif cmdargs[0] == ')' and self._transmode:
170 self._transmode = False
172 raise QMPShellError("Unexpected input after close of Transaction sub-shell")
173 qmpcmd = { 'execute': 'transaction',
174 'arguments': { 'actions': self._actions } }
175 self._actions = list()
178 # Nothing to process?
182 # Parse and then cache this Transactional Action
185 action = { 'type': cmdargs[0], 'data': {} }
186 if cmdargs[-1] == ')':
189 self.__cli_expr(cmdargs[1:], action['data'])
190 self._actions.append(action)
191 return self.__build_cmd(')') if finalize else None
193 # Standard command: parse and return it to be executed.
194 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
195 self.__cli_expr(cmdargs[1:], qmpcmd['arguments'])
198 def _print(self, qmp):
199 jsobj = json.dumps(qmp)
200 if self._pp is not None:
201 self._pp.pprint(jsobj)
205 def _execute_cmd(self, cmdline):
207 qmpcmd = self.__build_cmd(cmdline)
209 print 'Error while parsing command line: %s' % e
210 print 'command format: <command-name> ',
211 print '[arg-name1=arg1] ... [arg-nameN=argN]'
213 # For transaction mode, we may have just cached the action:
218 resp = self.cmd_obj(qmpcmd)
226 self._greeting = qmp.QEMUMonitorProtocol.connect(self)
227 self.__completer_setup()
229 def show_banner(self, msg='Welcome to the QMP low-level shell!'):
231 version = self._greeting['QMP']['version']['qemu']
232 print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])
234 def get_prompt(self):
239 def read_exec_command(self, prompt):
241 Read and execute a command.
243 @return True if execution was ok, return False if disconnected.
246 cmdline = raw_input(prompt)
251 for ev in self.get_events():
256 return self._execute_cmd(cmdline)
258 def set_verbosity(self, verbose):
259 self._verbose = verbose
261 class HMPShell(QMPShell):
262 def __init__(self, address):
263 QMPShell.__init__(self, address)
266 def __cmd_completion(self):
267 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
268 if cmd and cmd[0] != '[' and cmd[0] != '\t':
269 name = cmd.split()[0] # drop help text
272 if name.find('|') != -1:
273 # Command in the form 'foobar|f' or 'f|foobar', take the
275 opt = name.split('|')
280 self._completer.append(name)
281 self._completer.append('help ' + name) # help completion
283 def __info_completion(self):
284 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
286 self._completer.append('info ' + cmd.split()[1])
288 def __other_completion(self):
290 self._completer.append('help info')
292 def _fill_completion(self):
293 self.__cmd_completion()
294 self.__info_completion()
295 self.__other_completion()
297 def __cmd_passthrough(self, cmdline, cpu_index = 0):
298 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
299 { 'command-line': cmdline,
300 'cpu-index': cpu_index } })
302 def _execute_cmd(self, cmdline):
303 if cmdline.split()[0] == "cpu":
304 # trap the cpu command, it requires special setting
306 idx = int(cmdline.split()[1])
307 if not 'return' in self.__cmd_passthrough('info version', idx):
308 print 'bad CPU index'
310 self.__cpu_index = idx
312 print 'cpu command takes an integer argument'
314 resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
318 assert 'return' in resp or 'error' in resp
321 if len(resp['return']) > 0:
322 print resp['return'],
325 print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
328 def show_banner(self):
329 QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
332 sys.stderr.write('ERROR: %s\n' % msg)
335 def fail_cmdline(option=None):
337 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
338 sys.stderr.write('qemu-shell [ -v ] [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
349 for arg in sys.argv[1:]:
357 pp = pprint.PrettyPrinter(indent=4)
366 qemu = QMPShell(arg, pp)
371 except QMPShellBadPort:
372 die('bad port number in command-line')
376 except qmp.QMPConnectError:
377 die('Didn\'t get QMP greeting message')
378 except qmp.QMPCapabilitiesError:
379 die('Could not negotiate capabilities')
381 die('Could not connect to %s' % addr)
384 qemu.set_verbosity(verbose)
385 while qemu.read_exec_command(qemu.get_prompt()):
389 if __name__ == '__main__':