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
38 class QMPCompleter(list):
39 def complete(self
, text
, state
):
41 if cmd
.startswith(text
):
47 class QMPShellError(Exception):
50 class QMPShellBadPort(QMPShellError
):
53 # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
54 # _execute_cmd()). Let's design a better one.
55 class QMPShell(qmp
.QEMUMonitorProtocol
):
56 def __init__(self
, address
, pp
=None):
57 qmp
.QEMUMonitorProtocol
.__init
__(self
, self
.__get
_address
(address
))
59 self
._completer
= None
62 def __get_address(self
, arg
):
64 Figure out if the argument is in the port:host form, if it's not it's
73 return ( addr
[0], port
)
77 def _fill_completion(self
):
78 for cmd
in self
.cmd('query-commands')['return']:
79 self
._completer
.append(cmd
['name'])
81 def __completer_setup(self
):
82 self
._completer
= QMPCompleter()
83 self
._fill
_completion
()
84 readline
.set_completer(self
._completer
.complete
)
85 readline
.parse_and_bind("tab: complete")
86 # XXX: default delimiters conflict with some command names (eg. query-),
87 # clearing everything as it doesn't seem to matter
88 readline
.set_completer_delims('')
90 def __build_cmd(self
, cmdline
):
92 Build a QMP input object from a user provided command-line in the
95 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
97 cmdargs
= cmdline
.split()
98 qmpcmd
= { 'execute': cmdargs
[0], 'arguments': {} }
99 for arg
in cmdargs
[1:]:
103 opt
[1] = '='.join(opt
[1:])
108 elif opt
[1] == 'false':
112 qmpcmd
['arguments'][opt
[0]] = value
115 def _execute_cmd(self
, cmdline
):
117 qmpcmd
= self
.__build
_cmd
(cmdline
)
119 print 'command format: <command-name> ',
120 print '[arg-name1=arg1] ... [arg-nameN=argN]'
122 resp
= self
.cmd_obj(qmpcmd
)
127 if self
._pp
is not None:
128 self
._pp
.pprint(resp
)
134 self
._greeting
= qmp
.QEMUMonitorProtocol
.connect(self
)
135 self
.__completer
_setup
()
137 def show_banner(self
, msg
='Welcome to the QMP low-level shell!'):
139 version
= self
._greeting
['QMP']['version']['qemu']
140 print 'Connected to QEMU %d.%d.%d\n' % (version
['major'],version
['minor'],version
['micro'])
142 def read_exec_command(self
, prompt
):
144 Read and execute a command.
146 @return True if execution was ok, return False if disconnected.
149 cmdline
= raw_input(prompt
)
154 for ev
in self
.get_events():
159 return self
._execute
_cmd
(cmdline
)
161 class HMPShell(QMPShell
):
162 def __init__(self
, address
):
163 QMPShell
.__init
__(self
, address
)
166 def __cmd_completion(self
):
167 for cmd
in self
.__cmd
_passthrough
('help')['return'].split('\r\n'):
168 if cmd
and cmd
[0] != '[' and cmd
[0] != '\t':
169 name
= cmd
.split()[0] # drop help text
172 if name
.find('|') != -1:
173 # Command in the form 'foobar|f' or 'f|foobar', take the
175 opt
= name
.split('|')
180 self
._completer
.append(name
)
181 self
._completer
.append('help ' + name
) # help completion
183 def __info_completion(self
):
184 for cmd
in self
.__cmd
_passthrough
('info')['return'].split('\r\n'):
186 self
._completer
.append('info ' + cmd
.split()[1])
188 def __other_completion(self
):
190 self
._completer
.append('help info')
192 def _fill_completion(self
):
193 self
.__cmd
_completion
()
194 self
.__info
_completion
()
195 self
.__other
_completion
()
197 def __cmd_passthrough(self
, cmdline
, cpu_index
= 0):
198 return self
.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
199 { 'command-line': cmdline
,
200 'cpu-index': cpu_index
} })
202 def _execute_cmd(self
, cmdline
):
203 if cmdline
.split()[0] == "cpu":
204 # trap the cpu command, it requires special setting
206 idx
= int(cmdline
.split()[1])
207 if not 'return' in self
.__cmd
_passthrough
('info version', idx
):
208 print 'bad CPU index'
210 self
.__cpu
_index
= idx
212 print 'cpu command takes an integer argument'
214 resp
= self
.__cmd
_passthrough
(cmdline
, self
.__cpu
_index
)
218 assert 'return' in resp
or 'error' in resp
221 if len(resp
['return']) > 0:
222 print resp
['return'],
225 print '%s: %s' % (resp
['error']['class'], resp
['error']['desc'])
228 def show_banner(self
):
229 QMPShell
.show_banner(self
, msg
='Welcome to the HMP shell!')
232 sys
.stderr
.write('ERROR: %s\n' % msg
)
235 def fail_cmdline(option
=None):
237 sys
.stderr
.write('ERROR: bad command-line option \'%s\'\n' % option
)
238 sys
.stderr
.write('qemu-shell [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
248 for arg
in sys
.argv
[1:]:
256 pp
= pprint
.PrettyPrinter(indent
=4)
263 qemu
= QMPShell(arg
, pp
)
268 except QMPShellBadPort
:
269 die('bad port number in command-line')
273 except qmp
.QMPConnectError
:
274 die('Didn\'t get QMP greeting message')
275 except qmp
.QMPCapabilitiesError
:
276 die('Could not negotiate capabilities')
278 die('Could not connect to %s' % addr
)
281 while qemu
.read_exec_command('(QEMU) '):
285 if __name__
== '__main__':