]> git.proxmox.com Git - qemu.git/blame - QMP/qmp-shell
Merge remote-tracking branch 'stefanha/block' into staging
[qemu.git] / QMP / qmp-shell
CommitLineData
cedebdac
LC
1#!/usr/bin/python
2#
9bed0d0d 3# Low-level QEMU shell on top of QMP.
cedebdac 4#
9bed0d0d 5# Copyright (C) 2009, 2010 Red Hat Inc.
cedebdac
LC
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#
9bed0d0d 17# # qemu [...] -qmp unix:./qmp-sock,server
cedebdac
LC
18#
19# Run the shell:
20#
9bed0d0d 21# $ qmp-shell ./qmp-sock
cedebdac
LC
22#
23# Commands have the following format:
24#
9bed0d0d 25# < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
cedebdac
LC
26#
27# For example:
28#
9bed0d0d
LC
29# (QEMU) device_add driver=e1000 id=net1
30# {u'return': {}}
31# (QEMU)
cedebdac
LC
32
33import qmp
34import readline
9bed0d0d 35import sys
fa779b65 36import pprint
cedebdac 37
9bed0d0d
LC
38class QMPCompleter(list):
39 def complete(self, text, state):
40 for cmd in self:
41 if cmd.startswith(text):
42 if not state:
43 return cmd
44 else:
45 state -= 1
cedebdac 46
9bed0d0d
LC
47class QMPShellError(Exception):
48 pass
49
50class QMPShellBadPort(QMPShellError):
51 pass
52
53# TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and
54# _execute_cmd()). Let's design a better one.
55class QMPShell(qmp.QEMUMonitorProtocol):
fa779b65 56 def __init__(self, address, pp=None):
9bed0d0d
LC
57 qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address))
58 self._greeting = None
59 self._completer = None
fa779b65 60 self._pp = pp
9bed0d0d
LC
61
62 def __get_address(self, arg):
63 """
64 Figure out if the argument is in the port:host form, if it's not it's
65 probably a file path.
66 """
67 addr = arg.split(':')
68 if len(addr) == 2:
69 try:
70 port = int(addr[1])
71 except ValueError:
72 raise QMPShellBadPort
73 return ( addr[0], port )
74 # socket path
75 return arg
76
77 def _fill_completion(self):
78 for cmd in self.cmd('query-commands')['return']:
79 self._completer.append(cmd['name'])
80
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('')
89
90 def __build_cmd(self, cmdline):
91 """
92 Build a QMP input object from a user provided command-line in the
93 following format:
94
95 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
96 """
97 cmdargs = cmdline.split()
98 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
99 for arg in cmdargs[1:]:
100 opt = arg.split('=')
101 try:
102 value = int(opt[1])
103 except ValueError:
e5ecec7b
IM
104 if opt[1] == 'true':
105 value = True
106 elif opt[1] == 'false':
107 value = False
108 else:
109 value = opt[1]
9bed0d0d
LC
110 qmpcmd['arguments'][opt[0]] = value
111 return qmpcmd
112
113 def _execute_cmd(self, cmdline):
114 try:
115 qmpcmd = self.__build_cmd(cmdline)
116 except:
117 print 'command format: <command-name> ',
118 print '[arg-name1=arg1] ... [arg-nameN=argN]'
119 return True
120 resp = self.cmd_obj(qmpcmd)
121 if resp is None:
122 print 'Disconnected'
123 return False
fa779b65
DB
124
125 if self._pp is not None:
126 self._pp.pprint(resp)
127 else:
128 print resp
9bed0d0d
LC
129 return True
130
131 def connect(self):
132 self._greeting = qmp.QEMUMonitorProtocol.connect(self)
133 self.__completer_setup()
cedebdac 134
9bed0d0d
LC
135 def show_banner(self, msg='Welcome to the QMP low-level shell!'):
136 print msg
137 version = self._greeting['QMP']['version']['qemu']
138 print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])
cedebdac 139
9bed0d0d
LC
140 def read_exec_command(self, prompt):
141 """
142 Read and execute a command.
cedebdac 143
9bed0d0d
LC
144 @return True if execution was ok, return False if disconnected.
145 """
cedebdac 146 try:
9bed0d0d 147 cmdline = raw_input(prompt)
cedebdac
LC
148 except EOFError:
149 print
9bed0d0d
LC
150 return False
151 if cmdline == '':
152 for ev in self.get_events():
153 print ev
154 self.clear_events()
155 return True
cedebdac 156 else:
9bed0d0d
LC
157 return self._execute_cmd(cmdline)
158
11217a75
LC
159class HMPShell(QMPShell):
160 def __init__(self, address):
161 QMPShell.__init__(self, address)
162 self.__cpu_index = 0
163
164 def __cmd_completion(self):
165 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'):
166 if cmd and cmd[0] != '[' and cmd[0] != '\t':
167 name = cmd.split()[0] # drop help text
168 if name == 'info':
169 continue
170 if name.find('|') != -1:
171 # Command in the form 'foobar|f' or 'f|foobar', take the
172 # full name
173 opt = name.split('|')
174 if len(opt[0]) == 1:
175 name = opt[1]
176 else:
177 name = opt[0]
178 self._completer.append(name)
179 self._completer.append('help ' + name) # help completion
180
181 def __info_completion(self):
182 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'):
183 if cmd:
184 self._completer.append('info ' + cmd.split()[1])
185
186 def __other_completion(self):
187 # special cases
188 self._completer.append('help info')
189
190 def _fill_completion(self):
191 self.__cmd_completion()
192 self.__info_completion()
193 self.__other_completion()
194
195 def __cmd_passthrough(self, cmdline, cpu_index = 0):
196 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments':
197 { 'command-line': cmdline,
198 'cpu-index': cpu_index } })
199
200 def _execute_cmd(self, cmdline):
201 if cmdline.split()[0] == "cpu":
202 # trap the cpu command, it requires special setting
203 try:
204 idx = int(cmdline.split()[1])
205 if not 'return' in self.__cmd_passthrough('info version', idx):
206 print 'bad CPU index'
207 return True
208 self.__cpu_index = idx
209 except ValueError:
210 print 'cpu command takes an integer argument'
211 return True
212 resp = self.__cmd_passthrough(cmdline, self.__cpu_index)
213 if resp is None:
214 print 'Disconnected'
215 return False
216 assert 'return' in resp or 'error' in resp
217 if 'return' in resp:
218 # Success
219 if len(resp['return']) > 0:
220 print resp['return'],
221 else:
222 # Error
223 print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
224 return True
225
226 def show_banner(self):
227 QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
228
9bed0d0d
LC
229def die(msg):
230 sys.stderr.write('ERROR: %s\n' % msg)
231 sys.exit(1)
232
233def fail_cmdline(option=None):
234 if option:
235 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
fa779b65 236 sys.stderr.write('qemu-shell [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
9bed0d0d
LC
237 sys.exit(1)
238
239def main():
11217a75 240 addr = ''
fa779b65
DB
241 qemu = None
242 hmp = False
243 pp = None
244
9bed0d0d 245 try:
fa779b65
DB
246 for arg in sys.argv[1:]:
247 if arg == "-H":
248 if qemu is not None:
249 fail_cmdline(arg)
250 hmp = True
251 elif arg == "-p":
252 if pp is not None:
253 fail_cmdline(arg)
254 pp = pprint.PrettyPrinter(indent=4)
255 else:
256 if qemu is not None:
257 fail_cmdline(arg)
258 if hmp:
259 qemu = HMPShell(arg)
260 else:
261 qemu = QMPShell(arg, pp)
262 addr = arg
263
264 if qemu is None:
265 fail_cmdline()
9bed0d0d
LC
266 except QMPShellBadPort:
267 die('bad port number in command-line')
268
269 try:
270 qemu.connect()
271 except qmp.QMPConnectError:
272 die('Didn\'t get QMP greeting message')
273 except qmp.QMPCapabilitiesError:
274 die('Could not negotiate capabilities')
275 except qemu.error:
11217a75 276 die('Could not connect to %s' % addr)
9bed0d0d
LC
277
278 qemu.show_banner()
279 while qemu.read_exec_command('(QEMU) '):
280 pass
281 qemu.close()
cedebdac
LC
282
283if __name__ == '__main__':
284 main()