qemu.py 11 KB

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