2
0

qemu.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # QEMU library
  2. #
  3. # Copyright (C) 2015-2016 Red Hat Inc.
  4. # Copyright (C) 2012 IBM Corp.
  5. #
  6. # Authors:
  7. # Fam Zheng <famz@redhat.com>
  8. #
  9. # This work is licensed under the terms of the GNU GPL, version 2. See
  10. # the COPYING file in the top-level directory.
  11. #
  12. # Based on qmp.py.
  13. #
  14. import errno
  15. import logging
  16. import os
  17. import sys
  18. import subprocess
  19. import qmp.qmp
  20. LOG = logging.getLogger(__name__)
  21. class QEMUMachineError(Exception):
  22. """
  23. Exception called when an error in QEMUMachine happens.
  24. """
  25. class MonitorResponseError(qmp.qmp.QMPError):
  26. '''
  27. Represents erroneous QMP monitor reply
  28. '''
  29. def __init__(self, reply):
  30. try:
  31. desc = reply["error"]["desc"]
  32. except KeyError:
  33. desc = reply
  34. super(MonitorResponseError, self).__init__(desc)
  35. self.reply = reply
  36. class QEMUMachine(object):
  37. '''A QEMU VM
  38. Use this object as a context manager to ensure the QEMU process terminates::
  39. with VM(binary) as vm:
  40. ...
  41. # vm is guaranteed to be shut down here
  42. '''
  43. def __init__(self, binary, args=None, wrapper=None, name=None,
  44. test_dir="/var/tmp", monitor_address=None,
  45. socket_scm_helper=None, debug=False):
  46. '''
  47. Initialize a QEMUMachine
  48. @param binary: path to the qemu binary
  49. @param args: list of extra arguments
  50. @param wrapper: list of arguments used as prefix to qemu binary
  51. @param name: prefix for socket and log file names (default: qemu-PID)
  52. @param test_dir: where to create socket and log file
  53. @param monitor_address: address for QMP monitor
  54. @param socket_scm_helper: helper program, required for send_fd_scm()"
  55. @param debug: enable debug mode
  56. @note: Qemu process is not started until launch() is used.
  57. '''
  58. if args is None:
  59. args = []
  60. if wrapper is None:
  61. wrapper = []
  62. if name is None:
  63. name = "qemu-%d" % os.getpid()
  64. if monitor_address is None:
  65. monitor_address = os.path.join(test_dir, name + "-monitor.sock")
  66. self._monitor_address = monitor_address
  67. self._qemu_log_path = os.path.join(test_dir, name + ".log")
  68. self._popen = None
  69. self._binary = binary
  70. self._args = list(args) # Force copy args in case we modify them
  71. self._wrapper = wrapper
  72. self._events = []
  73. self._iolog = None
  74. self._socket_scm_helper = socket_scm_helper
  75. self._debug = debug
  76. self._qmp = None
  77. self._qemu_full_args = None
  78. def __enter__(self):
  79. return self
  80. def __exit__(self, exc_type, exc_val, exc_tb):
  81. self.shutdown()
  82. return False
  83. # This can be used to add an unused monitor instance.
  84. def add_monitor_telnet(self, ip, port):
  85. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  86. self._args.append('-monitor')
  87. self._args.append(args)
  88. def add_fd(self, fd, fdset, opaque, opts=''):
  89. '''Pass a file descriptor to the VM'''
  90. options = ['fd=%d' % fd,
  91. 'set=%d' % fdset,
  92. 'opaque=%s' % opaque]
  93. if opts:
  94. options.append(opts)
  95. self._args.append('-add-fd')
  96. self._args.append(','.join(options))
  97. return self
  98. def send_fd_scm(self, fd_file_path):
  99. # In iotest.py, the qmp should always use unix socket.
  100. assert self._qmp.is_scm_available()
  101. if self._socket_scm_helper is None:
  102. raise QEMUMachineError("No path to socket_scm_helper set")
  103. if not os.path.exists(self._socket_scm_helper):
  104. raise QEMUMachineError("%s does not exist" %
  105. self._socket_scm_helper)
  106. fd_param = ["%s" % self._socket_scm_helper,
  107. "%d" % self._qmp.get_sock_fd(),
  108. "%s" % fd_file_path]
  109. devnull = open(os.path.devnull, 'rb')
  110. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
  111. stderr=subprocess.STDOUT)
  112. output = proc.communicate()[0]
  113. if output:
  114. LOG.debug(output)
  115. return proc.returncode
  116. @staticmethod
  117. def _remove_if_exists(path):
  118. '''Remove file object at path if it exists'''
  119. try:
  120. os.remove(path)
  121. except OSError as exception:
  122. if exception.errno == errno.ENOENT:
  123. return
  124. raise
  125. def is_running(self):
  126. return self._popen is not None and self._popen.returncode is None
  127. def exitcode(self):
  128. if self._popen is None:
  129. return None
  130. return self._popen.returncode
  131. def get_pid(self):
  132. if not self.is_running():
  133. return None
  134. return self._popen.pid
  135. def _load_io_log(self):
  136. with open(self._qemu_log_path, "r") as iolog:
  137. self._iolog = iolog.read()
  138. def _base_args(self):
  139. if isinstance(self._monitor_address, tuple):
  140. moncdev = "socket,id=mon,host=%s,port=%s" % (
  141. self._monitor_address[0],
  142. self._monitor_address[1])
  143. else:
  144. moncdev = 'socket,id=mon,path=%s' % self._monitor_address
  145. return ['-chardev', moncdev,
  146. '-mon', 'chardev=mon,mode=control',
  147. '-display', 'none', '-vga', 'none']
  148. def _pre_launch(self):
  149. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
  150. server=True,
  151. debug=self._debug)
  152. def _post_launch(self):
  153. self._qmp.accept()
  154. def _post_shutdown(self):
  155. if not isinstance(self._monitor_address, tuple):
  156. self._remove_if_exists(self._monitor_address)
  157. self._remove_if_exists(self._qemu_log_path)
  158. def launch(self):
  159. '''Launch the VM and establish a QMP connection'''
  160. self._qemu_full_args = None
  161. devnull = open(os.path.devnull, 'rb')
  162. qemulog = open(self._qemu_log_path, 'wb')
  163. try:
  164. self._pre_launch()
  165. self._qemu_full_args = self._wrapper + [self._binary] +
  166. self._base_args() + self._args
  167. self._popen = subprocess.Popen(self._qemu_full_args,
  168. stdin=devnull,
  169. stdout=qemulog,
  170. stderr=subprocess.STDOUT,
  171. shell=False)
  172. self._post_launch()
  173. except:
  174. if self.is_running():
  175. self._popen.kill()
  176. self._popen.wait()
  177. self._load_io_log()
  178. self._post_shutdown()
  179. raise
  180. def shutdown(self):
  181. '''Terminate the VM and clean up'''
  182. if self.is_running():
  183. try:
  184. self._qmp.cmd('quit')
  185. self._qmp.close()
  186. except:
  187. self._popen.kill()
  188. self._popen.wait()
  189. self._load_io_log()
  190. self._post_shutdown()
  191. exitcode = self.exitcode()
  192. if exitcode is not None and exitcode < 0:
  193. msg = 'qemu received signal %i: %s'
  194. if self._qemu_full_args:
  195. command = ' '.join(self._qemu_full_args)
  196. else:
  197. command = ''
  198. LOG.warn(msg, exitcode, command)
  199. def qmp(self, cmd, conv_keys=True, **args):
  200. '''Invoke a QMP command and return the response dict'''
  201. qmp_args = dict()
  202. for key, value in args.iteritems():
  203. if conv_keys:
  204. qmp_args[key.replace('_', '-')] = value
  205. else:
  206. qmp_args[key] = value
  207. return self._qmp.cmd(cmd, args=qmp_args)
  208. def command(self, cmd, conv_keys=True, **args):
  209. '''
  210. Invoke a QMP command.
  211. On success return the response dict.
  212. On failure raise an exception.
  213. '''
  214. reply = self.qmp(cmd, conv_keys, **args)
  215. if reply is None:
  216. raise qmp.qmp.QMPError("Monitor is closed")
  217. if "error" in reply:
  218. raise MonitorResponseError(reply)
  219. return reply["return"]
  220. def get_qmp_event(self, wait=False):
  221. '''Poll for one queued QMP events and return it'''
  222. if len(self._events) > 0:
  223. return self._events.pop(0)
  224. return self._qmp.pull_event(wait=wait)
  225. def get_qmp_events(self, wait=False):
  226. '''Poll for queued QMP events and return a list of dicts'''
  227. events = self._qmp.get_events(wait=wait)
  228. events.extend(self._events)
  229. del self._events[:]
  230. self._qmp.clear_events()
  231. return events
  232. def event_wait(self, name, timeout=60.0, match=None):
  233. '''
  234. Wait for specified timeout on named event in QMP; optionally filter
  235. results by match.
  236. The 'match' is checked to be a recursive subset of the 'event'; skips
  237. branch processing on match's value None
  238. {"foo": {"bar": 1}} matches {"foo": None}
  239. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  240. '''
  241. def event_match(event, match=None):
  242. if match is None:
  243. return True
  244. for key in match:
  245. if key in event:
  246. if isinstance(event[key], dict):
  247. if not event_match(event[key], match[key]):
  248. return False
  249. elif event[key] != match[key]:
  250. return False
  251. else:
  252. return False
  253. return True
  254. # Search cached events
  255. for event in self._events:
  256. if (event['event'] == name) and event_match(event, match):
  257. self._events.remove(event)
  258. return event
  259. # Poll for new events
  260. while True:
  261. event = self._qmp.pull_event(wait=timeout)
  262. if (event['event'] == name) and event_match(event, match):
  263. return event
  264. self._events.append(event)
  265. return None
  266. def get_log(self):
  267. '''
  268. After self.shutdown or failed qemu execution, this returns the output
  269. of the qemu process.
  270. '''
  271. return self._iolog