qemu.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. def __enter__(self):
  78. return self
  79. def __exit__(self, exc_type, exc_val, exc_tb):
  80. self.shutdown()
  81. return False
  82. # This can be used to add an unused monitor instance.
  83. def add_monitor_telnet(self, ip, port):
  84. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  85. self._args.append('-monitor')
  86. self._args.append(args)
  87. def add_fd(self, fd, fdset, opaque, opts=''):
  88. '''Pass a file descriptor to the VM'''
  89. options = ['fd=%d' % fd,
  90. 'set=%d' % fdset,
  91. 'opaque=%s' % opaque]
  92. if opts:
  93. options.append(opts)
  94. self._args.append('-add-fd')
  95. self._args.append(','.join(options))
  96. return self
  97. def send_fd_scm(self, fd_file_path):
  98. # In iotest.py, the qmp should always use unix socket.
  99. assert self._qmp.is_scm_available()
  100. if self._socket_scm_helper is None:
  101. raise QEMUMachineError("No path to socket_scm_helper set")
  102. if not os.path.exists(self._socket_scm_helper):
  103. raise QEMUMachineError("%s does not exist" %
  104. self._socket_scm_helper)
  105. fd_param = ["%s" % self._socket_scm_helper,
  106. "%d" % self._qmp.get_sock_fd(),
  107. "%s" % fd_file_path]
  108. devnull = open('/dev/null', 'rb')
  109. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
  110. stderr=subprocess.STDOUT)
  111. output = proc.communicate()[0]
  112. if output:
  113. LOG.debug(output)
  114. return proc.returncode
  115. @staticmethod
  116. def _remove_if_exists(path):
  117. '''Remove file object at path if it exists'''
  118. try:
  119. os.remove(path)
  120. except OSError as exception:
  121. if exception.errno == errno.ENOENT:
  122. return
  123. raise
  124. def is_running(self):
  125. return self._popen is not None and self._popen.returncode is None
  126. def exitcode(self):
  127. if self._popen is None:
  128. return None
  129. return self._popen.returncode
  130. def get_pid(self):
  131. if not self.is_running():
  132. return None
  133. return self._popen.pid
  134. def _load_io_log(self):
  135. with open(self._qemu_log_path, "r") as iolog:
  136. self._iolog = iolog.read()
  137. def _base_args(self):
  138. if isinstance(self._monitor_address, tuple):
  139. moncdev = "socket,id=mon,host=%s,port=%s" % (
  140. self._monitor_address[0],
  141. self._monitor_address[1])
  142. else:
  143. moncdev = 'socket,id=mon,path=%s' % self._monitor_address
  144. return ['-chardev', moncdev,
  145. '-mon', 'chardev=mon,mode=control',
  146. '-display', 'none', '-vga', 'none']
  147. def _pre_launch(self):
  148. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
  149. server=True,
  150. debug=self._debug)
  151. def _post_launch(self):
  152. self._qmp.accept()
  153. def _post_shutdown(self):
  154. if not isinstance(self._monitor_address, tuple):
  155. self._remove_if_exists(self._monitor_address)
  156. self._remove_if_exists(self._qemu_log_path)
  157. def launch(self):
  158. '''Launch the VM and establish a QMP connection'''
  159. devnull = open('/dev/null', 'rb')
  160. qemulog = open(self._qemu_log_path, 'wb')
  161. try:
  162. self._pre_launch()
  163. args = (self._wrapper + [self._binary] + self._base_args() +
  164. self._args)
  165. self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
  166. stderr=subprocess.STDOUT,
  167. shell=False)
  168. self._post_launch()
  169. except:
  170. if self.is_running():
  171. self._popen.kill()
  172. self._popen.wait()
  173. self._load_io_log()
  174. self._post_shutdown()
  175. raise
  176. def shutdown(self):
  177. '''Terminate the VM and clean up'''
  178. if self.is_running():
  179. try:
  180. self._qmp.cmd('quit')
  181. self._qmp.close()
  182. except:
  183. self._popen.kill()
  184. exitcode = self._popen.wait()
  185. if exitcode < 0:
  186. LOG.warn('qemu received signal %i: %s', -exitcode,
  187. ' '.join(self._args))
  188. self._load_io_log()
  189. self._post_shutdown()
  190. def qmp(self, cmd, conv_keys=True, **args):
  191. '''Invoke a QMP command and return the response dict'''
  192. qmp_args = dict()
  193. for key, value in args.iteritems():
  194. if conv_keys:
  195. qmp_args[key.replace('_', '-')] = value
  196. else:
  197. qmp_args[key] = value
  198. return self._qmp.cmd(cmd, args=qmp_args)
  199. def command(self, cmd, conv_keys=True, **args):
  200. '''
  201. Invoke a QMP command.
  202. On success return the response dict.
  203. On failure raise an exception.
  204. '''
  205. reply = self.qmp(cmd, conv_keys, **args)
  206. if reply is None:
  207. raise qmp.qmp.QMPError("Monitor is closed")
  208. if "error" in reply:
  209. raise MonitorResponseError(reply)
  210. return reply["return"]
  211. def get_qmp_event(self, wait=False):
  212. '''Poll for one queued QMP events and return it'''
  213. if len(self._events) > 0:
  214. return self._events.pop(0)
  215. return self._qmp.pull_event(wait=wait)
  216. def get_qmp_events(self, wait=False):
  217. '''Poll for queued QMP events and return a list of dicts'''
  218. events = self._qmp.get_events(wait=wait)
  219. events.extend(self._events)
  220. del self._events[:]
  221. self._qmp.clear_events()
  222. return events
  223. def event_wait(self, name, timeout=60.0, match=None):
  224. '''
  225. Wait for specified timeout on named event in QMP; optionally filter
  226. results by match.
  227. The 'match' is checked to be a recursive subset of the 'event'; skips
  228. branch processing on match's value None
  229. {"foo": {"bar": 1}} matches {"foo": None}
  230. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  231. '''
  232. def event_match(event, match=None):
  233. if match is None:
  234. return True
  235. for key in match:
  236. if key in event:
  237. if isinstance(event[key], dict):
  238. if not event_match(event[key], match[key]):
  239. return False
  240. elif event[key] != match[key]:
  241. return False
  242. else:
  243. return False
  244. return True
  245. # Search cached events
  246. for event in self._events:
  247. if (event['event'] == name) and event_match(event, match):
  248. self._events.remove(event)
  249. return event
  250. # Poll for new events
  251. while True:
  252. event = self._qmp.pull_event(wait=timeout)
  253. if (event['event'] == name) and event_match(event, match):
  254. return event
  255. self._events.append(event)
  256. return None
  257. def get_log(self):
  258. '''
  259. After self.shutdown or failed qemu execution, this returns the output
  260. of the qemu process.
  261. '''
  262. return self._iolog