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
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.
74 class QMPCompleter(list):
75 def complete(self
, text
, state
):
77 if cmd
.startswith(text
):
83 class QMPShellError(Exception):
86 class QMPShellBadPort(QMPShellError
):
89 class FuzzyJSON(ast
.NodeTransformer
):
90 '''This extension of ast.NodeTransformer filters literal "true/false/null"
91 values in an AST and replaces them by proper "True/False/None" values that
92 Python can properly evaluate.'''
93 def visit_Name(self
, node
):
96 if node
.id == 'false':
102 # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
103 # _execute_cmd()). Let's design a better one.
104 class QMPShell(qmp
.QEMUMonitorProtocol
):
105 def __init__(self
, address
, pretty
=False):
106 qmp
.QEMUMonitorProtocol
.__init
__(self
, self
.__get
_address
(address
))
107 self
._greeting
= None
108 self
._completer
= None
109 self
._pretty
= pretty
110 self
._transmode
= False
111 self
._actions
= list()
113 def __get_address(self
, arg
):
115 Figure out if the argument is in the port:host form, if it's not it's
116 probably a file path.
118 addr
= arg
.split(':')
123 raise QMPShellBadPort
124 return ( addr
[0], port
)
128 def _fill_completion(self
):
129 for cmd
in self
.cmd('query-commands')['return']:
130 self
._completer
.append(cmd
['name'])
132 def __completer_setup(self
):
133 self
._completer
= QMPCompleter()
134 self
._fill
_completion
()
135 readline
.set_completer(self
._completer
.complete
)
136 readline
.parse_and_bind("tab: complete")
137 # XXX: default delimiters conflict with some command names (eg. query-),
138 # clearing everything as it doesn't seem to matter
139 readline
.set_completer_delims('')
141 def __parse_value(self
, val
):
147 if val
.lower() == 'true':
149 if val
.lower() == 'false':
151 if val
.startswith(('{', '[')):
152 # Try first as pure JSON:
154 return json
.loads(val
)
157 # Try once again as FuzzyJSON:
159 st
= ast
.parse(val
, mode
='eval')
160 return ast
.literal_eval(FuzzyJSON().visit(st
))
167 def __cli_expr(self
, tokens
, parent
):
169 (key
, _
, val
) = arg
.partition('=')
171 raise QMPShellError("Expected a key=value pair, got '%s'" % arg
)
173 value
= self
.__parse
_value
(val
)
174 optpath
= key
.split('.')
176 for p
in optpath
[:-1]:
178 d
= parent
.get(p
, {})
179 if type(d
) is not dict:
180 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath
))
183 if optpath
[-1] in parent
:
184 if type(parent
[optpath
[-1]]) is dict:
185 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath
))
187 raise QMPShellError('Cannot set "%s" multiple times' % key
)
188 parent
[optpath
[-1]] = value
190 def __build_cmd(self
, cmdline
):
192 Build a QMP input object from a user provided command-line in the
195 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
197 cmdargs
= cmdline
.split()
199 # Transactional CLI entry/exit:
200 if cmdargs
[0] == 'transaction(':
201 self
._transmode
= True
203 elif cmdargs
[0] == ')' and self
._transmode
:
204 self
._transmode
= False
206 raise QMPShellError("Unexpected input after close of Transaction sub-shell")
207 qmpcmd
= { 'execute': 'transaction',
208 'arguments': { 'actions': self
._actions
} }
209 self
._actions
= list()
212 # Nothing to process?
216 # Parse and then cache this Transactional Action
219 action
= { 'type': cmdargs
[0], 'data': {} }
220 if cmdargs
[-1] == ')':
223 self
.__cli
_expr
(cmdargs
[1:], action
['data'])
224 self
._actions
.append(action
)
225 return self
.__build
_cmd
(')') if finalize
else None
227 # Standard command: parse and return it to be executed.
228 qmpcmd
= { 'execute': cmdargs
[0], 'arguments': {} }
229 self
.__cli
_expr
(cmdargs
[1:], qmpcmd
['arguments'])
232 def _print(self
, qmp
):
236 jsobj
= json
.dumps(qmp
, indent
=indent
)
239 def _execute_cmd(self
, cmdline
):
241 qmpcmd
= self
.__build
_cmd
(cmdline
)
242 except Exception as e
:
243 print 'Error while parsing command line: %s' % e
244 print 'command format: <command-name> ',
245 print '[arg-name1=arg1] ... [arg-nameN=argN]'
247 # For transaction mode, we may have just cached the action:
252 resp
= self
.cmd_obj(qmpcmd
)
260 self
._greeting
= qmp
.QEMUMonitorProtocol
.connect(self
)
261 self
.__completer
_setup
()
263 def show_banner(self
, msg
='Welcome to the QMP low-level shell!'):
265 version
= self
._greeting
['QMP']['version']['qemu']
266 print 'Connected to QEMU %d.%d.%d\n' % (version
['major'],version
['minor'],version
['micro'])
268 def get_prompt(self
):
273 def read_exec_command(self
, prompt
):
275 Read and execute a command.
277 @return True if execution was ok, return False if disconnected.
280 cmdline
= raw_input(prompt
)
285 for ev
in self
.get_events():
290 return self
._execute
_cmd
(cmdline
)
292 def set_verbosity(self
, verbose
):
293 self
._verbose
= verbose
295 class HMPShell(QMPShell
):
296 def __init__(self
, address
):
297 QMPShell
.__init
__(self
, address
)
300 def __cmd_completion(self
):
301 for cmd
in self
.__cmd
_passthrough
('help')['return'].split('\r\n'):
302 if cmd
and cmd
[0] != '[' and cmd
[0] != '\t':
303 name
= cmd
.split()[0] # drop help text
306 if name
.find('|') != -1:
307 # Command in the form 'foobar|f' or 'f|foobar', take the
309 opt
= name
.split('|')
314 self
._completer
.append(name
)
315 self
._completer
.append('help ' + name
) # help completion
317 def __info_completion(self
):
318 for cmd
in self
.__cmd
_passthrough
('info')['return'].split('\r\n'):
320 self
._completer
.append('info ' + cmd
.split()[1])
322 def __other_completion(self
):
324 self
._completer
.append('help info')
326 def _fill_completion(self
):
327 self
.__cmd
_completion
()
328 self
.__info
_completion
()
329 self
.__other
_completion
()
331 def __cmd_passthrough(self
, cmdline
, cpu_index
= 0):
332 return self
.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
333 { 'command-line': cmdline
,
334 'cpu-index': cpu_index
} })
336 def _execute_cmd(self
, cmdline
):
337 if cmdline
.split()[0] == "cpu":
338 # trap the cpu command, it requires special setting
340 idx
= int(cmdline
.split()[1])
341 if not 'return' in self
.__cmd
_passthrough
('info version', idx
):
342 print 'bad CPU index'
344 self
.__cpu
_index
= idx
346 print 'cpu command takes an integer argument'
348 resp
= self
.__cmd
_passthrough
(cmdline
, self
.__cpu
_index
)
352 assert 'return' in resp
or 'error' in resp
355 if len(resp
['return']) > 0:
356 print resp
['return'],
359 print '%s: %s' % (resp
['error']['class'], resp
['error']['desc'])
362 def show_banner(self
):
363 QMPShell
.show_banner(self
, msg
='Welcome to the HMP shell!')
366 sys
.stderr
.write('ERROR: %s\n' % msg
)
369 def fail_cmdline(option
=None):
371 sys
.stderr
.write('ERROR: bad command-line option \'%s\'\n' % option
)
372 sys
.stderr
.write('qemu-shell [ -v ] [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
383 for arg
in sys
.argv
[1:]:
398 qemu
= QMPShell(arg
, pretty
)
403 except QMPShellBadPort
:
404 die('bad port number in command-line')
408 except qmp
.QMPConnectError
:
409 die('Didn\'t get QMP greeting message')
410 except qmp
.QMPCapabilitiesError
:
411 die('Could not negotiate capabilities')
413 die('Could not connect to %s' % addr
)
416 qemu
.set_verbosity(verbose
)
417 while qemu
.read_exec_command(qemu
.get_prompt()):
421 if __name__
== '__main__':