qemu.py 11 KB

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