3 # Low-level QEMU shell on top of QMP.
5 # Copyright (C) 2009, 2010 Red Hat Inc.
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
33 # key=value pairs also support Python or JSON object literal subset notations,
34 # without spaces. Dictionaries/objects {} are supported as are arrays [].
36 # example-command arg-name1={'key':'value','obj'={'prop':"value"}}
38 # Both JSON and Python formatting should work, including both styles of
39 # string literal quotes. Both paradigms of literal values should work,
40 # including null/true/false for JSON and None/True/False for Python.
43 # Transactions have the following multi-line format:
46 # action-name1 [ arg-name1=arg1 ] ... [arg-nameN=argN ]
48 # action-nameN [ arg-name1=arg1 ] ... [arg-nameN=argN ]
51 # One line transactions are also supported:
53 # transaction( action-name1 ... )
58 # TRANS> block-dirty-bitmap-add node=drive0 name=bitmap1
59 # TRANS> block-dirty-bitmap-clear node=drive0 name=bitmap0
64 # Use the -v and -p options to activate the verbose and pretty-print options,
65 # which will echo back the properly formatted JSON-compliant QMP that is being
66 # sent to QEMU, which is useful for debugging and documentation generation.
68 from __future__ import print_function
78 sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python'))
81 class QMPCompleter(list):
82 def complete(self, text, state):
84 if cmd.startswith(text):
90 class QMPShellError(Exception):
93 class QMPShellBadPort(QMPShellError):
96 class FuzzyJSON(ast.NodeTransformer):
97 '''This extension of ast.NodeTransformer filters literal "true/false/null"
98 values in an AST and replaces them by proper "True/False/None" values that
99 Python can properly evaluate.'''
100 def visit_Name(self, node):
101 if node.id == 'true':
103 if node.id == 'false':
105 if node.id == 'null':
109 # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
110 # _execute_cmd()). Let's design a better one.
111 class QMPShell(qmp.QEMUMonitorProtocol):
112 def __init__(self, address, pretty=False):
113 super(QMPShell, self).__init__(self.__get_address(address))
114 self._greeting = None
115 self._completer = None
116 self._pretty = pretty
117 self._transmode = False
118 self._actions = list()
119 self._histfile = os.path.join(os.path.expanduser('~'),
120 '.qmp-shell_history')
122 def __get_address(self, arg):
124 Figure out if the argument is in the port:host form, if it's not it's
125 probably a file path.
127 addr = arg.split(':')
132 raise QMPShellBadPort
133 return ( addr[0], port )
137 def _fill_completion(self):
138 cmds = self.cmd('query-commands')
141 for cmd in cmds['return']:
142 self._completer.append(cmd['name'])
144 def __completer_setup(self):
145 self._completer = QMPCompleter()
146 self._fill_completion()
147 readline.set_history_length(1024)
148 readline.set_completer(self._completer.complete)
149 readline.parse_and_bind("tab: complete")
150 # XXX: default delimiters conflict with some command names (eg. query-),
151 # clearing everything as it doesn't seem to matter
152 readline.set_completer_delims('')
154 readline.read_history_file(self._histfile)
155 except Exception as e:
156 if isinstance(e, IOError) and e.errno == errno.ENOENT:
157 # File not found. No problem.
160 print("Failed to read history '%s'; %s" % (self._histfile, e))
161 atexit.register(self.__save_history)
163 def __save_history(self):
165 readline.write_history_file(self._histfile)
166 except Exception as e:
167 print("Failed to save history file '%s'; %s" % (self._histfile, e))
169 def __parse_value(self, val):
175 if val.lower() == 'true':
177 if val.lower() == 'false':
179 if val.startswith(('{', '[')):
180 # Try first as pure JSON:
182 return json.loads(val)
185 # Try once again as FuzzyJSON:
187 st = ast.parse(val, mode='eval')
188 return ast.literal_eval(FuzzyJSON().visit(st))
195 def __cli_expr(self, tokens, parent):
197 (key, sep, val) = arg.partition('=')
199 raise QMPShellError("Expected a key=value pair, got '%s'" % arg)
201 value = self.__parse_value(val)
202 optpath = key.split('.')
204 for p in optpath[:-1]:
206 d = parent.get(p, {})
207 if type(d) is not dict:
208 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
211 if optpath[-1] in parent:
212 if type(parent[optpath[-1]]) is dict:
213 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
215 raise QMPShellError('Cannot set "%s" multiple times' % key)
216 parent[optpath[-1]] = value
218 def __build_cmd(self, cmdline):
220 Build a QMP input object from a user provided command-line in the
223 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
225 cmdargs = re.findall(r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+''', cmdline)
227 # Transactional CLI entry/exit:
228 if cmdargs[0] == 'transaction(':
229 self._transmode = True
231 elif cmdargs[0] == ')' and self._transmode:
232 self._transmode = False
234 raise QMPShellError("Unexpected input after close of Transaction sub-shell")
235 qmpcmd = { 'execute': 'transaction',
236 'arguments': { 'actions': self._actions } }
237 self._actions = list()
240 # Nothing to process?
244 # Parse and then cache this Transactional Action
247 action = { 'type': cmdargs[0], 'data': {} }
248 if cmdargs[-1] == ')':
251 self.__cli_expr(cmdargs[1:], action['data'])
252 self._actions.append(action)
253 return self.__build_cmd(')') if finalize else None
255 # Standard command: parse and return it to be executed.
256 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
257 self.__cli_expr(cmdargs[1:], qmpcmd['arguments'])
260 def _print(self, qmp):
264 jsobj = json.dumps(qmp, indent=indent)
267 def _execute_cmd(self, cmdline):
269 qmpcmd = self.__build_cmd(cmdline)
270 except Exception as e:
271 print('Error while parsing command line: %s' % e)
272 print('command format: <command-name> ', end=' ')
273 print('[arg-name1=arg1] ... [arg-nameN=argN]')
275 # For transaction mode, we may have just cached the action:
280 resp = self.cmd_obj(qmpcmd)
282 print('Disconnected')
287 def connect(self, negotiate):
288 self._greeting = super(QMPShell, self).connect(negotiate)
289 self.__completer_setup()
291 def show_banner(self, msg='Welcome to the QMP low-level shell!'):
293 if not self._greeting:
296 version = self._greeting['QMP']['version']['qemu']
297 print('Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro']))
299 def get_prompt(self):
304 def read_exec_command(self, prompt):
306 Read and execute a command.
308 @return True if execution was ok, return False if disconnected.
311 cmdline = raw_input(prompt)
316 for ev in self.get_events():
321 return self._execute_cmd(cmdline)
323 def set_verbosity(self, verbose):
324 self._verbose = verbose
326 class HMPShell(QMPShell):
327 def __init__(self, address):
328 QMPShell.__init__(self, address)
331 def __cmd_completion(self):
332 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
333 if cmd and cmd[0] != '[' and cmd[0] != '\t':
334 name = cmd.split()[0] # drop help text
337 if name.find('|') != -1:
338 # Command in the form 'foobar|f' or 'f|foobar', take the
340 opt = name.split('|')
345 self._completer.append(name)
346 self._completer.append('help ' + name) # help completion
348 def __info_completion(self):
349 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
351 self._completer.append('info ' + cmd.split()[1])
353 def __other_completion(self):
355 self._completer.append('help info')
357 def _fill_completion(self):
358 self.__cmd_completion()
359 self.__info_completion()
360 self.__other_completion()
362 def __cmd_passthrough(self, cmdline, cpu_index = 0):
363 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
364 { 'command-line': cmdline,
365 'cpu-index': cpu_index } })
367 def _execute_cmd(self, cmdline):
368 if cmdline.split()[0] == "cpu":
369 # trap the cpu command, it requires special setting
371 idx = int(cmdline.split()[1])
372 if not 'return' in self.__cmd_passthrough('info version', idx):
373 print('bad CPU index')
375 self.__cpu_index = idx
377 print('cpu command takes an integer argument')
379 resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
381 print('Disconnected')
383 assert 'return' in resp or 'error' in resp
386 if len(resp['return']) > 0:
387 print(resp['return'], end=' ')
390 print('%s: %s' % (resp['error']['class'], resp['error']['desc']))
393 def show_banner(self):
394 QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
397 sys.stderr.write('ERROR: %s\n' % msg)
400 def fail_cmdline(option=None):
402 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
403 sys.stderr.write('qmp-shell [ -v ] [ -p ] [ -H ] [ -N ] < UNIX socket path> | < TCP address:port >\n')
404 sys.stderr.write(' -v Verbose (echo command sent and received)\n')
405 sys.stderr.write(' -p Pretty-print JSON\n')
406 sys.stderr.write(' -H Use HMP interface\n')
407 sys.stderr.write(' -N Skip negotiate (for qemu-ga)\n')
419 for arg in sys.argv[1:]:
436 qemu = QMPShell(arg, pretty)
441 except QMPShellBadPort:
442 die('bad port number in command-line')
445 qemu.connect(negotiate)
446 except qmp.QMPConnectError:
447 die('Didn\'t get QMP greeting message')
448 except qmp.QMPCapabilitiesError:
449 die('Could not negotiate capabilities')
451 die('Could not connect to %s' % addr)
454 qemu.set_verbosity(verbose)
455 while qemu.read_exec_command(qemu.get_prompt()):
459 if __name__ == '__main__':