xref: /openbmc/qemu/scripts/qmp/qmp-shell (revision 6598f0cd)
1#!/usr/bin/python
2#
3# Low-level QEMU shell on top of QMP.
4#
5# Copyright (C) 2009, 2010 Red Hat Inc.
6#
7# Authors:
8#  Luiz Capitulino <lcapitulino@redhat.com>
9#
10# This work is licensed under the terms of the GNU GPL, version 2.  See
11# the COPYING file in the top-level directory.
12#
13# Usage:
14#
15# Start QEMU with:
16#
17# # qemu [...] -qmp unix:./qmp-sock,server
18#
19# Run the shell:
20#
21# $ qmp-shell ./qmp-sock
22#
23# Commands have the following format:
24#
25#    < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
26#
27# For example:
28#
29# (QEMU) device_add driver=e1000 id=net1
30# {u'return': {}}
31# (QEMU)
32#
33# key=value pairs also support Python or JSON object literal subset notations,
34# without spaces. Dictionaries/objects {} are supported as are arrays [].
35#
36#    example-command arg-name1={'key':'value','obj'={'prop':"value"}}
37#
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.
41#
42#
43# Transactions have the following multi-line format:
44#
45#    transaction(
46#    action-name1 [ arg-name1=arg1 ] ... [arg-nameN=argN ]
47#    ...
48#    action-nameN [ arg-name1=arg1 ] ... [arg-nameN=argN ]
49#    )
50#
51# One line transactions are also supported:
52#
53#    transaction( action-name1 ... )
54#
55# For example:
56#
57#     (QEMU) transaction(
58#     TRANS> block-dirty-bitmap-add node=drive0 name=bitmap1
59#     TRANS> block-dirty-bitmap-clear node=drive0 name=bitmap0
60#     TRANS> )
61#     {"return": {}}
62#     (QEMU)
63#
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.
67
68from __future__ import print_function
69import qmp
70import json
71import ast
72import readline
73import sys
74import os
75import errno
76import atexit
77
78class QMPCompleter(list):
79    def complete(self, text, state):
80        for cmd in self:
81            if cmd.startswith(text):
82                if not state:
83                    return cmd
84                else:
85                    state -= 1
86
87class QMPShellError(Exception):
88    pass
89
90class QMPShellBadPort(QMPShellError):
91    pass
92
93class FuzzyJSON(ast.NodeTransformer):
94    '''This extension of ast.NodeTransformer filters literal "true/false/null"
95    values in an AST and replaces them by proper "True/False/None" values that
96    Python can properly evaluate.'''
97    def visit_Name(self, node):
98        if node.id == 'true':
99            node.id = 'True'
100        if node.id == 'false':
101            node.id = 'False'
102        if node.id == 'null':
103            node.id = 'None'
104        return node
105
106# TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
107#       _execute_cmd()). Let's design a better one.
108class QMPShell(qmp.QEMUMonitorProtocol):
109    def __init__(self, address, pretty=False):
110        super(QMPShell, self).__init__(self.__get_address(address))
111        self._greeting = None
112        self._completer = None
113        self._pretty = pretty
114        self._transmode = False
115        self._actions = list()
116        self._histfile = os.path.join(os.path.expanduser('~'),
117                                      '.qmp-shell_history')
118
119    def __get_address(self, arg):
120        """
121        Figure out if the argument is in the port:host form, if it's not it's
122        probably a file path.
123        """
124        addr = arg.split(':')
125        if len(addr) == 2:
126            try:
127                port = int(addr[1])
128            except ValueError:
129                raise QMPShellBadPort
130            return ( addr[0], port )
131        # socket path
132        return arg
133
134    def _fill_completion(self):
135        cmds = self.cmd('query-commands')
136        if 'error' in cmds:
137            return
138        for cmd in cmds['return']:
139            self._completer.append(cmd['name'])
140
141    def __completer_setup(self):
142        self._completer = QMPCompleter()
143        self._fill_completion()
144        readline.set_history_length(1024)
145        readline.set_completer(self._completer.complete)
146        readline.parse_and_bind("tab: complete")
147        # XXX: default delimiters conflict with some command names (eg. query-),
148        # clearing everything as it doesn't seem to matter
149        readline.set_completer_delims('')
150        try:
151            readline.read_history_file(self._histfile)
152        except Exception as e:
153            if isinstance(e, IOError) and e.errno == errno.ENOENT:
154                # File not found. No problem.
155                pass
156            else:
157                print("Failed to read history '%s'; %s" % (self._histfile, e))
158        atexit.register(self.__save_history)
159
160    def __save_history(self):
161        try:
162            readline.write_history_file(self._histfile)
163        except Exception as e:
164            print("Failed to save history file '%s'; %s" % (self._histfile, e))
165
166    def __parse_value(self, val):
167        try:
168            return int(val)
169        except ValueError:
170            pass
171
172        if val.lower() == 'true':
173            return True
174        if val.lower() == 'false':
175            return False
176        if val.startswith(('{', '[')):
177            # Try first as pure JSON:
178            try:
179                return json.loads(val)
180            except ValueError:
181                pass
182            # Try once again as FuzzyJSON:
183            try:
184                st = ast.parse(val, mode='eval')
185                return ast.literal_eval(FuzzyJSON().visit(st))
186            except SyntaxError:
187                pass
188            except ValueError:
189                pass
190        return val
191
192    def __cli_expr(self, tokens, parent):
193        for arg in tokens:
194            (key, sep, val) = arg.partition('=')
195            if sep != '=':
196                raise QMPShellError("Expected a key=value pair, got '%s'" % arg)
197
198            value = self.__parse_value(val)
199            optpath = key.split('.')
200            curpath = []
201            for p in optpath[:-1]:
202                curpath.append(p)
203                d = parent.get(p, {})
204                if type(d) is not dict:
205                    raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
206                parent[p] = d
207                parent = d
208            if optpath[-1] in parent:
209                if type(parent[optpath[-1]]) is dict:
210                    raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
211                else:
212                    raise QMPShellError('Cannot set "%s" multiple times' % key)
213            parent[optpath[-1]] = value
214
215    def __build_cmd(self, cmdline):
216        """
217        Build a QMP input object from a user provided command-line in the
218        following format:
219
220            < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
221        """
222        cmdargs = cmdline.split()
223
224        # Transactional CLI entry/exit:
225        if cmdargs[0] == 'transaction(':
226            self._transmode = True
227            cmdargs.pop(0)
228        elif cmdargs[0] == ')' and self._transmode:
229            self._transmode = False
230            if len(cmdargs) > 1:
231                raise QMPShellError("Unexpected input after close of Transaction sub-shell")
232            qmpcmd = { 'execute': 'transaction',
233                       'arguments': { 'actions': self._actions } }
234            self._actions = list()
235            return qmpcmd
236
237        # Nothing to process?
238        if not cmdargs:
239            return None
240
241        # Parse and then cache this Transactional Action
242        if self._transmode:
243            finalize = False
244            action = { 'type': cmdargs[0], 'data': {} }
245            if cmdargs[-1] == ')':
246                cmdargs.pop(-1)
247                finalize = True
248            self.__cli_expr(cmdargs[1:], action['data'])
249            self._actions.append(action)
250            return self.__build_cmd(')') if finalize else None
251
252        # Standard command: parse and return it to be executed.
253        qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
254        self.__cli_expr(cmdargs[1:], qmpcmd['arguments'])
255        return qmpcmd
256
257    def _print(self, qmp):
258        indent = None
259        if self._pretty:
260            indent = 4
261        jsobj = json.dumps(qmp, indent=indent)
262        print(str(jsobj))
263
264    def _execute_cmd(self, cmdline):
265        try:
266            qmpcmd = self.__build_cmd(cmdline)
267        except Exception as e:
268            print('Error while parsing command line: %s' % e)
269            print('command format: <command-name> ', end=' ')
270            print('[arg-name1=arg1] ... [arg-nameN=argN]')
271            return True
272        # For transaction mode, we may have just cached the action:
273        if qmpcmd is None:
274            return True
275        if self._verbose:
276            self._print(qmpcmd)
277        resp = self.cmd_obj(qmpcmd)
278        if resp is None:
279            print('Disconnected')
280            return False
281        self._print(resp)
282        return True
283
284    def connect(self, negotiate):
285        self._greeting = super(QMPShell, self).connect(negotiate)
286        self.__completer_setup()
287
288    def show_banner(self, msg='Welcome to the QMP low-level shell!'):
289        print(msg)
290        if not self._greeting:
291            print('Connected')
292            return
293        version = self._greeting['QMP']['version']['qemu']
294        print('Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro']))
295
296    def get_prompt(self):
297        if self._transmode:
298            return "TRANS> "
299        return "(QEMU) "
300
301    def read_exec_command(self, prompt):
302        """
303        Read and execute a command.
304
305        @return True if execution was ok, return False if disconnected.
306        """
307        try:
308            cmdline = raw_input(prompt)
309        except EOFError:
310            print()
311            return False
312        if cmdline == '':
313            for ev in self.get_events():
314                print(ev)
315            self.clear_events()
316            return True
317        else:
318            return self._execute_cmd(cmdline)
319
320    def set_verbosity(self, verbose):
321        self._verbose = verbose
322
323class HMPShell(QMPShell):
324    def __init__(self, address):
325        QMPShell.__init__(self, address)
326        self.__cpu_index = 0
327
328    def __cmd_completion(self):
329        for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
330            if cmd and cmd[0] != '[' and cmd[0] != '\t':
331                name = cmd.split()[0] # drop help text
332                if name == 'info':
333                    continue
334                if name.find('|') != -1:
335                    # Command in the form 'foobar|f' or 'f|foobar', take the
336                    # full name
337                    opt = name.split('|')
338                    if len(opt[0]) == 1:
339                        name = opt[1]
340                    else:
341                        name = opt[0]
342                self._completer.append(name)
343                self._completer.append('help ' + name) # help completion
344
345    def __info_completion(self):
346        for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
347            if cmd:
348                self._completer.append('info ' + cmd.split()[1])
349
350    def __other_completion(self):
351        # special cases
352        self._completer.append('help info')
353
354    def _fill_completion(self):
355        self.__cmd_completion()
356        self.__info_completion()
357        self.__other_completion()
358
359    def __cmd_passthrough(self, cmdline, cpu_index = 0):
360        return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
361                              { 'command-line': cmdline,
362                                'cpu-index': cpu_index } })
363
364    def _execute_cmd(self, cmdline):
365        if cmdline.split()[0] == "cpu":
366            # trap the cpu command, it requires special setting
367            try:
368                idx = int(cmdline.split()[1])
369                if not 'return' in self.__cmd_passthrough('info version', idx):
370                    print('bad CPU index')
371                    return True
372                self.__cpu_index = idx
373            except ValueError:
374                print('cpu command takes an integer argument')
375                return True
376        resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
377        if resp is None:
378            print('Disconnected')
379            return False
380        assert 'return' in resp or 'error' in resp
381        if 'return' in resp:
382            # Success
383            if len(resp['return']) > 0:
384                print(resp['return'], end=' ')
385        else:
386            # Error
387            print('%s: %s' % (resp['error']['class'], resp['error']['desc']))
388        return True
389
390    def show_banner(self):
391        QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
392
393def die(msg):
394    sys.stderr.write('ERROR: %s\n' % msg)
395    sys.exit(1)
396
397def fail_cmdline(option=None):
398    if option:
399        sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
400    sys.stderr.write('qmp-shell [ -v ] [ -p ] [ -H ] [ -N ] < UNIX socket path> | < TCP address:port >\n')
401    sys.stderr.write('    -v     Verbose (echo command sent and received)\n')
402    sys.stderr.write('    -p     Pretty-print JSON\n')
403    sys.stderr.write('    -H     Use HMP interface\n')
404    sys.stderr.write('    -N     Skip negotiate (for qemu-ga)\n')
405    sys.exit(1)
406
407def main():
408    addr = ''
409    qemu = None
410    hmp = False
411    pretty = False
412    verbose = False
413    negotiate = True
414
415    try:
416        for arg in sys.argv[1:]:
417            if arg == "-H":
418                if qemu is not None:
419                    fail_cmdline(arg)
420                hmp = True
421            elif arg == "-p":
422                pretty = True
423            elif arg == "-N":
424                negotiate = False
425            elif arg == "-v":
426                verbose = True
427            else:
428                if qemu is not None:
429                    fail_cmdline(arg)
430                if hmp:
431                    qemu = HMPShell(arg)
432                else:
433                    qemu = QMPShell(arg, pretty)
434                addr = arg
435
436        if qemu is None:
437            fail_cmdline()
438    except QMPShellBadPort:
439        die('bad port number in command-line')
440
441    try:
442        qemu.connect(negotiate)
443    except qmp.QMPConnectError:
444        die('Didn\'t get QMP greeting message')
445    except qmp.QMPCapabilitiesError:
446        die('Could not negotiate capabilities')
447    except qemu.error:
448        die('Could not connect to %s' % addr)
449
450    qemu.show_banner()
451    qemu.set_verbosity(verbose)
452    while qemu.read_exec_command(qemu.get_prompt()):
453        pass
454    qemu.close()
455
456if __name__ == '__main__':
457    main()
458