qemu.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. with open(self._qemu_log_path, "r") as iolog:
  141. self._iolog = iolog.read()
  142. def _base_args(self):
  143. if isinstance(self._monitor_address, tuple):
  144. moncdev = "socket,id=mon,host=%s,port=%s" % (
  145. self._monitor_address[0],
  146. self._monitor_address[1])
  147. else:
  148. moncdev = 'socket,id=mon,path=%s' % self._vm_monitor
  149. return ['-chardev', moncdev,
  150. '-mon', 'chardev=mon,mode=control',
  151. '-display', 'none', '-vga', 'none']
  152. def _pre_launch(self):
  153. self._temp_dir = tempfile.mkdtemp(dir=self._test_dir)
  154. if self._monitor_address is not None:
  155. self._vm_monitor = self._monitor_address
  156. else:
  157. self._vm_monitor = os.path.join(self._temp_dir,
  158. self._name + "-monitor.sock")
  159. self._qemu_log_path = os.path.join(self._temp_dir, self._name + ".log")
  160. self._qemu_log_file = open(self._qemu_log_path, 'wb')
  161. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._vm_monitor,
  162. server=True)
  163. def _post_launch(self):
  164. self._qmp.accept()
  165. def _post_shutdown(self):
  166. if self._qemu_log_file is not None:
  167. self._qemu_log_file.close()
  168. self._qemu_log_file = None
  169. self._qemu_log_path = None
  170. if self._temp_dir is not None:
  171. shutil.rmtree(self._temp_dir)
  172. self._temp_dir = None
  173. def launch(self):
  174. """
  175. Launch the VM and make sure we cleanup and expose the
  176. command line/output in case of exception
  177. """
  178. self._iolog = None
  179. self._qemu_full_args = None
  180. try:
  181. self._launch()
  182. except:
  183. if self.is_running():
  184. self._popen.kill()
  185. self._popen.wait()
  186. self._load_io_log()
  187. self._post_shutdown()
  188. LOG.debug('Error launching VM')
  189. if self._qemu_full_args:
  190. LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
  191. if self._iolog:
  192. LOG.debug('Output: %r', self._iolog)
  193. raise
  194. def _launch(self):
  195. '''Launch the VM and establish a QMP connection'''
  196. devnull = open(os.path.devnull, 'rb')
  197. self._pre_launch()
  198. self._qemu_full_args = (self._wrapper + [self._binary] +
  199. self._base_args() + self._args)
  200. self._popen = subprocess.Popen(self._qemu_full_args,
  201. stdin=devnull,
  202. stdout=self._qemu_log_file,
  203. stderr=subprocess.STDOUT,
  204. shell=False)
  205. self._post_launch()
  206. def wait(self):
  207. '''Wait for the VM to power off'''
  208. self._popen.wait()
  209. self._qmp.close()
  210. self._load_io_log()
  211. self._post_shutdown()
  212. def shutdown(self):
  213. '''Terminate the VM and clean up'''
  214. if self.is_running():
  215. try:
  216. self._qmp.cmd('quit')
  217. self._qmp.close()
  218. except:
  219. self._popen.kill()
  220. self._popen.wait()
  221. self._load_io_log()
  222. self._post_shutdown()
  223. exitcode = self.exitcode()
  224. if exitcode is not None and exitcode < 0:
  225. msg = 'qemu received signal %i: %s'
  226. if self._qemu_full_args:
  227. command = ' '.join(self._qemu_full_args)
  228. else:
  229. command = ''
  230. LOG.warn(msg, exitcode, command)
  231. def qmp(self, cmd, conv_keys=True, **args):
  232. '''Invoke a QMP command and return the response dict'''
  233. qmp_args = dict()
  234. for key, value in args.iteritems():
  235. if conv_keys:
  236. qmp_args[key.replace('_', '-')] = value
  237. else:
  238. qmp_args[key] = value
  239. return self._qmp.cmd(cmd, args=qmp_args)
  240. def command(self, cmd, conv_keys=True, **args):
  241. '''
  242. Invoke a QMP command.
  243. On success return the response dict.
  244. On failure raise an exception.
  245. '''
  246. reply = self.qmp(cmd, conv_keys, **args)
  247. if reply is None:
  248. raise qmp.qmp.QMPError("Monitor is closed")
  249. if "error" in reply:
  250. raise MonitorResponseError(reply)
  251. return reply["return"]
  252. def get_qmp_event(self, wait=False):
  253. '''Poll for one queued QMP events and return it'''
  254. if len(self._events) > 0:
  255. return self._events.pop(0)
  256. return self._qmp.pull_event(wait=wait)
  257. def get_qmp_events(self, wait=False):
  258. '''Poll for queued QMP events and return a list of dicts'''
  259. events = self._qmp.get_events(wait=wait)
  260. events.extend(self._events)
  261. del self._events[:]
  262. self._qmp.clear_events()
  263. return events
  264. def event_wait(self, name, timeout=60.0, match=None):
  265. '''
  266. Wait for specified timeout on named event in QMP; optionally filter
  267. results by match.
  268. The 'match' is checked to be a recursive subset of the 'event'; skips
  269. branch processing on match's value None
  270. {"foo": {"bar": 1}} matches {"foo": None}
  271. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  272. '''
  273. def event_match(event, match=None):
  274. if match is None:
  275. return True
  276. for key in match:
  277. if key in event:
  278. if isinstance(event[key], dict):
  279. if not event_match(event[key], match[key]):
  280. return False
  281. elif event[key] != match[key]:
  282. return False
  283. else:
  284. return False
  285. return True
  286. # Search cached events
  287. for event in self._events:
  288. if (event['event'] == name) and event_match(event, match):
  289. self._events.remove(event)
  290. return event
  291. # Poll for new events
  292. while True:
  293. event = self._qmp.pull_event(wait=timeout)
  294. if (event['event'] == name) and event_match(event, match):
  295. return event
  296. self._events.append(event)
  297. return None
  298. def get_log(self):
  299. '''
  300. After self.shutdown or failed qemu execution, this returns the output
  301. of the qemu process.
  302. '''
  303. return self._iolog