1#!/usr/bin/env python3 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# key=value pairs also support Python or JSON object literal subset notations, 34# without spaces. Dictionaries/objects {} are supported as are arrays []. 35# 36# example-command arg-name1={'key':'value','obj'={'prop':"value"}} 37# 38# Both JSON and Python formatting should work, including both styles of 39# string literal quotes. Both paradigms of literal values should work, 40# including null/true/false for JSON and None/True/False for Python. 41# 42# 43# Transactions have the following multi-line format: 44# 45# transaction( 46# action-name1 [ arg-name1=arg1 ] ... [arg-nameN=argN ] 47# ... 48# action-nameN [ arg-name1=arg1 ] ... [arg-nameN=argN ] 49# ) 50# 51# One line transactions are also supported: 52# 53# transaction( action-name1 ... ) 54# 55# For example: 56# 57# (QEMU) transaction( 58# TRANS> block-dirty-bitmap-add node=drive0 name=bitmap1 59# TRANS> block-dirty-bitmap-clear node=drive0 name=bitmap0 60# TRANS> ) 61# {"return": {}} 62# (QEMU) 63# 64# Use the -v and -p options to activate the verbose and pretty-print options, 65# which will echo back the properly formatted JSON-compliant QMP that is being 66# sent to QEMU, which is useful for debugging and documentation generation. 67 68import json 69import ast 70import readline 71import sys 72import os 73import errno 74import atexit 75import re 76 77sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python')) 78from qemu import qmp 79 80class QMPCompleter(list): 81 def complete(self, text, state): 82 for cmd in self: 83 if cmd.startswith(text): 84 if not state: 85 return cmd 86 else: 87 state -= 1 88 89class QMPShellError(Exception): 90 pass 91 92 93class FuzzyJSON(ast.NodeTransformer): 94 '''This extension of ast.NodeTransformer filters literal "true/false/null" 95 values in an AST and replaces them by proper "True/False/None" values that 96 Python can properly evaluate.''' 97 def visit_Name(self, node): 98 if node.id == 'true': 99 node.id = 'True' 100 if node.id == 'false': 101 node.id = 'False' 102 if node.id == 'null': 103 node.id = 'None' 104 return node 105 106# TODO: QMPShell's interface is a bit ugly (eg. _fill_completion() and 107# _execute_cmd()). Let's design a better one. 108class QMPShell(qmp.QEMUMonitorProtocol): 109 def __init__(self, address, pretty=False): 110 super(QMPShell, self).__init__(self.parse_address(address)) 111 self._greeting = None 112 self._completer = None 113 self._pretty = pretty 114 self._transmode = False 115 self._actions = list() 116 self._histfile = os.path.join(os.path.expanduser('~'), 117 '.qmp-shell_history') 118 119 def _fill_completion(self): 120 cmds = self.cmd('query-commands') 121 if 'error' in cmds: 122 return 123 for cmd in cmds['return']: 124 self._completer.append(cmd['name']) 125 126 def __completer_setup(self): 127 self._completer = QMPCompleter() 128 self._fill_completion() 129 readline.set_history_length(1024) 130 readline.set_completer(self._completer.complete) 131 readline.parse_and_bind("tab: complete") 132 # XXX: default delimiters conflict with some command names (eg. query-), 133 # clearing everything as it doesn't seem to matter 134 readline.set_completer_delims('') 135 try: 136 readline.read_history_file(self._histfile) 137 except Exception as e: 138 if isinstance(e, IOError) and e.errno == errno.ENOENT: 139 # File not found. No problem. 140 pass 141 else: 142 print("Failed to read history '%s'; %s" % (self._histfile, e)) 143 atexit.register(self.__save_history) 144 145 def __save_history(self): 146 try: 147 readline.write_history_file(self._histfile) 148 except Exception as e: 149 print("Failed to save history file '%s'; %s" % (self._histfile, e)) 150 151 def __parse_value(self, val): 152 try: 153 return int(val) 154 except ValueError: 155 pass 156 157 if val.lower() == 'true': 158 return True 159 if val.lower() == 'false': 160 return False 161 if val.startswith(('{', '[')): 162 # Try first as pure JSON: 163 try: 164 return json.loads(val) 165 except ValueError: 166 pass 167 # Try once again as FuzzyJSON: 168 try: 169 st = ast.parse(val, mode='eval') 170 return ast.literal_eval(FuzzyJSON().visit(st)) 171 except SyntaxError: 172 pass 173 except ValueError: 174 pass 175 return val 176 177 def __cli_expr(self, tokens, parent): 178 for arg in tokens: 179 (key, sep, val) = arg.partition('=') 180 if sep != '=': 181 raise QMPShellError("Expected a key=value pair, got '%s'" % arg) 182 183 value = self.__parse_value(val) 184 optpath = key.split('.') 185 curpath = [] 186 for p in optpath[:-1]: 187 curpath.append(p) 188 d = parent.get(p, {}) 189 if type(d) is not dict: 190 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath)) 191 parent[p] = d 192 parent = d 193 if optpath[-1] in parent: 194 if type(parent[optpath[-1]]) is dict: 195 raise QMPShellError('Cannot use "%s" as both leaf and non-leaf key' % '.'.join(curpath)) 196 else: 197 raise QMPShellError('Cannot set "%s" multiple times' % key) 198 parent[optpath[-1]] = value 199 200 def __build_cmd(self, cmdline): 201 """ 202 Build a QMP input object from a user provided command-line in the 203 following format: 204 205 < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ] 206 """ 207 cmdargs = re.findall(r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+''', cmdline) 208 209 # Transactional CLI entry/exit: 210 if cmdargs[0] == 'transaction(': 211 self._transmode = True 212 cmdargs.pop(0) 213 elif cmdargs[0] == ')' and self._transmode: 214 self._transmode = False 215 if len(cmdargs) > 1: 216 raise QMPShellError("Unexpected input after close of Transaction sub-shell") 217 qmpcmd = { 'execute': 'transaction', 218 'arguments': { 'actions': self._actions } } 219 self._actions = list() 220 return qmpcmd 221 222 # Nothing to process? 223 if not cmdargs: 224 return None 225 226 # Parse and then cache this Transactional Action 227 if self._transmode: 228 finalize = False 229 action = { 'type': cmdargs[0], 'data': {} } 230 if cmdargs[-1] == ')': 231 cmdargs.pop(-1) 232 finalize = True 233 self.__cli_expr(cmdargs[1:], action['data']) 234 self._actions.append(action) 235 return self.__build_cmd(')') if finalize else None 236 237 # Standard command: parse and return it to be executed. 238 qmpcmd = { 'execute': cmdargs[0], 'arguments': {} } 239 self.__cli_expr(cmdargs[1:], qmpcmd['arguments']) 240 return qmpcmd 241 242 def _print(self, qmp): 243 indent = None 244 if self._pretty: 245 indent = 4 246 jsobj = json.dumps(qmp, indent=indent, sort_keys=self._pretty) 247 print(str(jsobj)) 248 249 def _execute_cmd(self, cmdline): 250 try: 251 qmpcmd = self.__build_cmd(cmdline) 252 except Exception as e: 253 print('Error while parsing command line: %s' % e) 254 print('command format: <command-name> ', end=' ') 255 print('[arg-name1=arg1] ... [arg-nameN=argN]') 256 return True 257 # For transaction mode, we may have just cached the action: 258 if qmpcmd is None: 259 return True 260 if self._verbose: 261 self._print(qmpcmd) 262 resp = self.cmd_obj(qmpcmd) 263 if resp is None: 264 print('Disconnected') 265 return False 266 self._print(resp) 267 return True 268 269 def connect(self, negotiate): 270 self._greeting = super(QMPShell, self).connect(negotiate) 271 self.__completer_setup() 272 273 def show_banner(self, msg='Welcome to the QMP low-level shell!'): 274 print(msg) 275 if not self._greeting: 276 print('Connected') 277 return 278 version = self._greeting['QMP']['version']['qemu'] 279 print('Connected to QEMU %d.%d.%d\n' % (version['major'],version['minor'],version['micro'])) 280 281 def get_prompt(self): 282 if self._transmode: 283 return "TRANS> " 284 return "(QEMU) " 285 286 def read_exec_command(self, prompt): 287 """ 288 Read and execute a command. 289 290 @return True if execution was ok, return False if disconnected. 291 """ 292 try: 293 cmdline = input(prompt) 294 except EOFError: 295 print() 296 return False 297 if cmdline == '': 298 for ev in self.get_events(): 299 print(ev) 300 self.clear_events() 301 return True 302 else: 303 return self._execute_cmd(cmdline) 304 305 def set_verbosity(self, verbose): 306 self._verbose = verbose 307 308class HMPShell(QMPShell): 309 def __init__(self, address): 310 QMPShell.__init__(self, address) 311 self.__cpu_index = 0 312 313 def __cmd_completion(self): 314 for cmd in self.__cmd_passthrough('help')['return'].split('\r\n'): 315 if cmd and cmd[0] != '[' and cmd[0] != '\t': 316 name = cmd.split()[0] # drop help text 317 if name == 'info': 318 continue 319 if name.find('|') != -1: 320 # Command in the form 'foobar|f' or 'f|foobar', take the 321 # full name 322 opt = name.split('|') 323 if len(opt[0]) == 1: 324 name = opt[1] 325 else: 326 name = opt[0] 327 self._completer.append(name) 328 self._completer.append('help ' + name) # help completion 329 330 def __info_completion(self): 331 for cmd in self.__cmd_passthrough('info')['return'].split('\r\n'): 332 if cmd: 333 self._completer.append('info ' + cmd.split()[1]) 334 335 def __other_completion(self): 336 # special cases 337 self._completer.append('help info') 338 339 def _fill_completion(self): 340 self.__cmd_completion() 341 self.__info_completion() 342 self.__other_completion() 343 344 def __cmd_passthrough(self, cmdline, cpu_index = 0): 345 return self.cmd_obj({ 'execute': 'human-monitor-command', 'arguments': 346 { 'command-line': cmdline, 347 'cpu-index': cpu_index } }) 348 349 def _execute_cmd(self, cmdline): 350 if cmdline.split()[0] == "cpu": 351 # trap the cpu command, it requires special setting 352 try: 353 idx = int(cmdline.split()[1]) 354 if not 'return' in self.__cmd_passthrough('info version', idx): 355 print('bad CPU index') 356 return True 357 self.__cpu_index = idx 358 except ValueError: 359 print('cpu command takes an integer argument') 360 return True 361 resp = self.__cmd_passthrough(cmdline, self.__cpu_index) 362 if resp is None: 363 print('Disconnected') 364 return False 365 assert 'return' in resp or 'error' in resp 366 if 'return' in resp: 367 # Success 368 if len(resp['return']) > 0: 369 print(resp['return'], end=' ') 370 else: 371 # Error 372 print('%s: %s' % (resp['error']['class'], resp['error']['desc'])) 373 return True 374 375 def show_banner(self): 376 QMPShell.show_banner(self, msg='Welcome to the HMP shell!') 377 378def die(msg): 379 sys.stderr.write('ERROR: %s\n' % msg) 380 sys.exit(1) 381 382def fail_cmdline(option=None): 383 if option: 384 sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option) 385 sys.stderr.write('qmp-shell [ -v ] [ -p ] [ -H ] [ -N ] < UNIX socket path> | < TCP address:port >\n') 386 sys.stderr.write(' -v Verbose (echo command sent and received)\n') 387 sys.stderr.write(' -p Pretty-print JSON\n') 388 sys.stderr.write(' -H Use HMP interface\n') 389 sys.stderr.write(' -N Skip negotiate (for qemu-ga)\n') 390 sys.exit(1) 391 392def main(): 393 addr = '' 394 qemu = None 395 hmp = False 396 pretty = False 397 verbose = False 398 negotiate = True 399 400 try: 401 for arg in sys.argv[1:]: 402 if arg == "-H": 403 if qemu is not None: 404 fail_cmdline(arg) 405 hmp = True 406 elif arg == "-p": 407 pretty = True 408 elif arg == "-N": 409 negotiate = False 410 elif arg == "-v": 411 verbose = True 412 else: 413 if qemu is not None: 414 fail_cmdline(arg) 415 if hmp: 416 qemu = HMPShell(arg) 417 else: 418 qemu = QMPShell(arg, pretty) 419 addr = arg 420 421 if qemu is None: 422 fail_cmdline() 423 except qmp.QMPBadPortError: 424 die('bad port number in command-line') 425 426 try: 427 qemu.connect(negotiate) 428 except qmp.QMPConnectError: 429 die('Didn\'t get QMP greeting message') 430 except qmp.QMPCapabilitiesError: 431 die('Could not negotiate capabilities') 432 except qemu.error: 433 die('Could not connect to %s' % addr) 434 435 qemu.show_banner() 436 qemu.set_verbosity(verbose) 437 while qemu.read_exec_command(qemu.get_prompt()): 438 pass 439 qemu.close() 440 441if __name__ == '__main__': 442 main() 443