2
0

qmp-shell 14 KB

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