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
39 class QMPCompleter(list):
40 def complete(self, text, state):
42 if cmd.startswith(text):
48 class QMPShellError(Exception):
51 class QMPShellBadPort(QMPShellError):
54 # TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
55 # _execute_cmd()). Let's design a better one.
56 class QMPShell(qmp.QEMUMonitorProtocol):
57 def __init__(self, address, pp=None):
58 qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address))
60 self._completer = None
63 def __get_address(self, arg):
65 Figure out if the argument is in the port:host form, if it's not it's
74 return ( addr[0], port )
78 def _fill_completion(self):
79 for cmd in self.cmd('query-commands')['return']:
80 self._completer.append(cmd['name'])
82 def __completer_setup(self):
83 self._completer = QMPCompleter()
84 self._fill_completion()
85 readline.set_completer(self._completer.complete)
86 readline.parse_and_bind("tab: complete")
87 # XXX: default delimiters conflict with some command names (eg. query-),
88 # clearing everything as it doesn't seem to matter
89 readline.set_completer_delims('')
91 def __build_cmd(self, cmdline):
93 Build a QMP input object from a user provided command-line in the
96 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
98 cmdargs = cmdline.split()
99 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
100 for arg in cmdargs[1:]:
104 opt[1] = '='.join(opt[1:])
109 elif opt[1] == 'false':
111 elif opt[1].startswith('{'):
112 value = json.loads(opt[1])
115 optpath = opt[0].split('.')
116 parent = qmpcmd['arguments']
118 for p in optpath[:-1]:
120 d = parent.get(p, {})
121 if type(d) is not dict:
122 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
125 if optpath[-1] in parent:
126 if type(parent[optpath[-1]]) is dict:
127 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath))
129 raise QMPShellError('Cannot set "%s" multiple times' % opt[0])
130 parent[optpath[-1]] = value
133 def _execute_cmd(self, cmdline):
135 qmpcmd = self.__build_cmd(cmdline)
137 print 'Error while parsing command line: %s' % e
138 print 'command format: <command-name> ',
139 print '[arg-name1=arg1] ... [arg-nameN=argN]'
141 resp = self.cmd_obj(qmpcmd)
146 if self._pp is not None:
147 self._pp.pprint(resp)
153 self._greeting = qmp.QEMUMonitorProtocol.connect(self)
154 self.__completer_setup()
156 def show_banner(self, msg='Welcome to the QMP low-level shell!'):
158 version = self._greeting['QMP']['version']['qemu']
159 print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])
161 def read_exec_command(self, prompt):
163 Read and execute a command.
165 @return True if execution was ok, return False if disconnected.
168 cmdline = raw_input(prompt)
173 for ev in self.get_events():
178 return self._execute_cmd(cmdline)
180 class HMPShell(QMPShell):
181 def __init__(self, address):
182 QMPShell.__init__(self, address)
185 def __cmd_completion(self):
186 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
187 if cmd and cmd[0] != '[' and cmd[0] != '\t':
188 name = cmd.split()[0] # drop help text
191 if name.find('|') != -1:
192 # Command in the form 'foobar|f' or 'f|foobar', take the
194 opt = name.split('|')
199 self._completer.append(name)
200 self._completer.append('help ' + name) # help completion
202 def __info_completion(self):
203 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
205 self._completer.append('info ' + cmd.split()[1])
207 def __other_completion(self):
209 self._completer.append('help info')
211 def _fill_completion(self):
212 self.__cmd_completion()
213 self.__info_completion()
214 self.__other_completion()
216 def __cmd_passthrough(self, cmdline, cpu_index = 0):
217 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
218 { 'command-line': cmdline,
219 'cpu-index': cpu_index } })
221 def _execute_cmd(self, cmdline):
222 if cmdline.split()[0] == "cpu":
223 # trap the cpu command, it requires special setting
225 idx = int(cmdline.split()[1])
226 if not 'return' in self.__cmd_passthrough('info version', idx):
227 print 'bad CPU index'
229 self.__cpu_index = idx
231 print 'cpu command takes an integer argument'
233 resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
237 assert 'return' in resp or 'error' in resp
240 if len(resp['return']) > 0:
241 print resp['return'],
244 print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
247 def show_banner(self):
248 QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
251 sys.stderr.write('ERROR: %s\n' % msg)
254 def fail_cmdline(option=None):
256 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
257 sys.stderr.write('qemu-shell [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
267 for arg in sys.argv[1:]:
275 pp = pprint.PrettyPrinter(indent=4)
282 qemu = QMPShell(arg, pp)
287 except QMPShellBadPort:
288 die('bad port number in command-line')
292 except qmp.QMPConnectError:
293 die('Didn\'t get QMP greeting message')
294 except qmp.QMPCapabilitiesError:
295 die('Could not negotiate capabilities')
297 die('Could not connect to %s' % addr)
300 while qemu.read_exec_command('(QEMU) '):
304 if __name__ == '__main__':