]> git.proxmox.com Git - qemu.git/blob - QMP/qmp-shell
qemu-iotests: exclude vmdk and qcow from 043
[qemu.git] / QMP / qmp-shell
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 import qmp
34 import readline
35 import sys
36 import pprint
37
38 class 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
46
47 class QMPShellError(Exception):
48 pass
49
50 class 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.
55 class QMPShell(qmp.QEMUMonitorProtocol):
56 def __init__(self, address, pp=None):
57 qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address))
58 self._greeting = None
59 self._completer = None
60 self._pp = pp
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:
104 if opt[1] == 'true':
105 value = True
106 elif opt[1] == 'false':
107 value = False
108 else:
109 value = opt[1]
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
124
125 if self._pp is not None:
126 self._pp.pprint(resp)
127 else:
128 print resp
129 return True
130
131 def connect(self):
132 self._greeting = qmp.QEMUMonitorProtocol.connect(self)
133 self.__completer_setup()
134
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'])
139
140 def read_exec_command(self, prompt):
141 """
142 Read and execute a command.
143
144 @return True if execution was ok, return False if disconnected.
145 """
146 try:
147 cmdline = raw_input(prompt)
148 except EOFError:
149 print
150 return False
151 if cmdline == '':
152 for ev in self.get_events():
153 print ev
154 self.clear_events()
155 return True
156 else:
157 return self._execute_cmd(cmdline)
158
159 class 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
229 def die(msg):
230 sys.stderr.write('ERROR: %s\n' % msg)
231 sys.exit(1)
232
233 def fail_cmdline(option=None):
234 if option:
235 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
236 sys.stderr.write('qemu-shell [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n')
237 sys.exit(1)
238
239 def main():
240 addr = ''
241 qemu = None
242 hmp = False
243 pp = None
244
245 try:
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()
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:
276 die('Could not connect to %s' % addr)
277
278 qemu.show_banner()
279 while qemu.read_exec_command('(QEMU) '):
280 pass
281 qemu.close()
282
283 if __name__ == '__main__':
284 main()