2
0

qmp-shell 14 KB

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