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 33import qmp 34import json 35import ast 36import readline 37import sys 38import pprint 39 40class QMPCompleter(list): 41 def complete(self, text, state): 42 for cmd in self: 43 if cmd.startswith(text): 44 if not state: 45 return cmd 46 else: 47 state -= 1 48 49class QMPShellError(Exception): 50 pass 51 52class QMPShellBadPort(QMPShellError): 53 pass 54 55class FuzzyJSON(ast.NodeTransformer): 56 '''This extension of ast.NodeTransformer filters literal "true/false/null" 57 values in an AST and replaces them by proper "True/False/None" values that 58 Python can properly evaluate.''' 59 def visit_Name(self, node): 60 if node.id == 'true': 61 node.id = 'True' 62 if node.id == 'false': 63 node.id = 'False' 64 if node.id == 'null': 65 node.id = 'None' 66 return node 67 68# TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and 69# _execute_cmd()). Let's design a better one. 70class QMPShell(qmp.QEMUMonitorProtocol): 71 def __init__(self, address, pp=None): 72 qmp.QEMUMonitorProtocol.__init__(self, self.__get_address(address)) 73 self._greeting = None 74 self._completer = None 75 self._pp = pp 76 self._transmode = False 77 self._actions = list() 78 79 def __get_address(self, arg): 80 """ 81 Figure out if the argument is in the port:host form, if it's not it's 82 probably a file path. 83 """ 84 addr = arg.split(':') 85 if len(addr) == 2: 86 try: 87 port = int(addr[1]) 88 except ValueError: 89 raise QMPShellBadPort 90 return ( addr[0], port ) 91 # socket path 92 return arg 93 94 def _fill_completion(self): 95 for cmd in self.cmd('query-commands')['return']: 96 self._completer.append(cmd['name']) 97 98 def __completer_setup(self): 99 self._completer = QMPCompleter() 100 self._fill_completion() 101 readline.set_completer(self._completer.complete) 102 readline.parse_and_bind("tab: complete") 103 # XXX: default delimiters conflict with some command names (eg. query-), 104 # clearing everything as it doesn't seem to matter 105 readline.set_completer_delims('') 106 107 def __parse_value(self, val): 108 try: 109 return int(val) 110 except ValueError: 111 pass 112 113 if val.lower() == 'true': 114 return True 115 if val.lower() == 'false': 116 return False 117 if val.startswith(('{', '[')): 118 # Try first as pure JSON: 119 try: 120 return json.loads(val) 121 except ValueError: 122 pass 123 # Try once again as FuzzyJSON: 124 try: 125 st = ast.parse(val, mode='eval') 126 return ast.literal_eval(FuzzyJSON().visit(st)) 127 except SyntaxError: 128 pass 129 except ValueError: 130 pass 131 return val 132 133 def __cli_expr(self, tokens, parent): 134 for arg in tokens: 135 (key, _, val) = arg.partition('=') 136 if not val: 137 raise QMPShellError("Expected a key=value pair, got '%s'" % arg) 138 139 value = self.__parse_value(val) 140 optpath = key.split('.') 141 curpath = [] 142 for p in optpath[:-1]: 143 curpath.append(p) 144 d = parent.get(p, {}) 145 if type(d) is not dict: 146 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath)) 147 parent[p] = d 148 parent = d 149 if optpath[-1] in parent: 150 if type(parent[optpath[-1]]) is dict: 151 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath)) 152 else: 153 raise QMPShellError('Cannot set "%s" multiple times' % key) 154 parent[optpath[-1]] = value 155 156 def __build_cmd(self, cmdline): 157 """ 158 Build a QMP input object from a user provided command-line in the 159 following format: 160 161 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ] 162 """ 163 cmdargs = cmdline.split() 164 165 # Transactional CLI entry/exit: 166 if cmdargs[0] == 'transaction(': 167 self._transmode = True 168 cmdargs.pop(0) 169 elif cmdargs[0] == ')' and self._transmode: 170 self._transmode = False 171 if len(cmdargs) > 1: 172 raise QMPShellError("Unexpected input after close of Transaction sub-shell") 173 qmpcmd = { 'execute': 'transaction', 174 'arguments': { 'actions': self._actions } } 175 self._actions = list() 176 return qmpcmd 177 178 # Nothing to process? 179 if not cmdargs: 180 return None 181 182 # Parse and then cache this Transactional Action 183 if self._transmode: 184 finalize = False 185 action = { 'type': cmdargs[0], 'data': {} } 186 if cmdargs[-1] == ')': 187 cmdargs.pop(-1) 188 finalize = True 189 self.__cli_expr(cmdargs[1:], action['data']) 190 self._actions.append(action) 191 return self.__build_cmd(')') if finalize else None 192 193 # Standard command: parse and return it to be executed. 194 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} } 195 self.__cli_expr(cmdargs[1:], qmpcmd['arguments']) 196 return qmpcmd 197 198 def _execute_cmd(self, cmdline): 199 try: 200 qmpcmd = self.__build_cmd(cmdline) 201 except Exception, e: 202 print 'Error while parsing command line: %s' % e 203 print 'command format: <command-name> ', 204 print '[arg-name1=arg1] ... [arg-nameN=argN]' 205 return True 206 # For transaction mode, we may have just cached the action: 207 if qmpcmd is None: 208 return True 209 resp = self.cmd_obj(qmpcmd) 210 if resp is None: 211 print 'Disconnected' 212 return False 213 214 if self._pp is not None: 215 self._pp.pprint(resp) 216 else: 217 print resp 218 return True 219 220 def connect(self): 221 self._greeting = qmp.QEMUMonitorProtocol.connect(self) 222 self.__completer_setup() 223 224 def show_banner(self, msg='Welcome to the QMP low-level shell!'): 225 print msg 226 version = self._greeting['QMP']['version']['qemu'] 227 print 'Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro']) 228 229 def get_prompt(self): 230 if self._transmode: 231 return "TRANS> " 232 return "(QEMU) " 233 234 def read_exec_command(self, prompt): 235 """ 236 Read and execute a command. 237 238 @return True if execution was ok, return False if disconnected. 239 """ 240 try: 241 cmdline = raw_input(prompt) 242 except EOFError: 243 print 244 return False 245 if cmdline == '': 246 for ev in self.get_events(): 247 print ev 248 self.clear_events() 249 return True 250 else: 251 return self._execute_cmd(cmdline) 252 253class HMPShell(QMPShell): 254 def __init__(self, address): 255 QMPShell.__init__(self, address) 256 self.__cpu_index = 0 257 258 def __cmd_completion(self): 259 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'): 260 if cmd and cmd[0] != '[' and cmd[0] != '\t': 261 name = cmd.split()[0] # drop help text 262 if name == 'info': 263 continue 264 if name.find('|') != -1: 265 # Command in the form 'foobar|f' or 'f|foobar', take the 266 # full name 267 opt = name.split('|') 268 if len(opt[0]) == 1: 269 name = opt[1] 270 else: 271 name = opt[0] 272 self._completer.append(name) 273 self._completer.append('help ' + name) # help completion 274 275 def __info_completion(self): 276 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'): 277 if cmd: 278 self._completer.append('info ' + cmd.split()[1]) 279 280 def __other_completion(self): 281 # special cases 282 self._completer.append('help info') 283 284 def _fill_completion(self): 285 self.__cmd_completion() 286 self.__info_completion() 287 self.__other_completion() 288 289 def __cmd_passthrough(self, cmdline, cpu_index = 0): 290 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments': 291 { 'command-line': cmdline, 292 'cpu-index': cpu_index } }) 293 294 def _execute_cmd(self, cmdline): 295 if cmdline.split()[0] == "cpu": 296 # trap the cpu command, it requires special setting 297 try: 298 idx = int(cmdline.split()[1]) 299 if not 'return' in self.__cmd_passthrough('info version', idx): 300 print 'bad CPU index' 301 return True 302 self.__cpu_index = idx 303 except ValueError: 304 print 'cpu command takes an integer argument' 305 return True 306 resp = self.__cmd_passthrough(cmdline, self.__cpu_index) 307 if resp is None: 308 print 'Disconnected' 309 return False 310 assert 'return' in resp or 'error' in resp 311 if 'return' in resp: 312 # Success 313 if len(resp['return']) > 0: 314 print resp['return'], 315 else: 316 # Error 317 print '%s: %s' % (resp['error']['class'], resp['error']['desc']) 318 return True 319 320 def show_banner(self): 321 QMPShell.show_banner(self, msg='Welcome to the HMP shell!') 322 323def die(msg): 324 sys.stderr.write('ERROR: %s\n' % msg) 325 sys.exit(1) 326 327def fail_cmdline(option=None): 328 if option: 329 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option) 330 sys.stderr.write('qemu-shell [ -p ] [ -H ] < UNIX socket path> | < TCP address:port >\n') 331 sys.exit(1) 332 333def main(): 334 addr = '' 335 qemu = None 336 hmp = False 337 pp = None 338 339 try: 340 for arg in sys.argv[1:]: 341 if arg == "-H": 342 if qemu is not None: 343 fail_cmdline(arg) 344 hmp = True 345 elif arg == "-p": 346 if pp is not None: 347 fail_cmdline(arg) 348 pp = pprint.PrettyPrinter(indent=4) 349 else: 350 if qemu is not None: 351 fail_cmdline(arg) 352 if hmp: 353 qemu = HMPShell(arg) 354 else: 355 qemu = QMPShell(arg, pp) 356 addr = arg 357 358 if qemu is None: 359 fail_cmdline() 360 except QMPShellBadPort: 361 die('bad port number in command-line') 362 363 try: 364 qemu.connect() 365 except qmp.QMPConnectError: 366 die('Didn\'t get QMP greeting message') 367 except qmp.QMPCapabilitiesError: 368 die('Could not negotiate capabilities') 369 except qemu.error: 370 die('Could not connect to %s' % addr) 371 372 qemu.show_banner() 373 while qemu.read_exec_command(qemu.get_prompt()): 374 pass 375 qemu.close() 376 377if __name__ == '__main__': 378 main() 379