qemu.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. self._launched = False
  81. # just in case logging wasn't configured by the main script:
  82. logging.basicConfig()
  83. def __enter__(self):
  84. return self
  85. def __exit__(self, exc_type, exc_val, exc_tb):
  86. self.shutdown()
  87. return False
  88. # This can be used to add an unused monitor instance.
  89. def add_monitor_telnet(self, ip, port):
  90. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  91. self._args.append('-monitor')
  92. self._args.append(args)
  93. def add_fd(self, fd, fdset, opaque, opts=''):
  94. '''Pass a file descriptor to the VM'''
  95. options = ['fd=%d' % fd,
  96. 'set=%d' % fdset,
  97. 'opaque=%s' % opaque]
  98. if opts:
  99. options.append(opts)
  100. self._args.append('-add-fd')
  101. self._args.append(','.join(options))
  102. return self
  103. def send_fd_scm(self, fd_file_path):
  104. # In iotest.py, the qmp should always use unix socket.
  105. assert self._qmp.is_scm_available()
  106. if self._socket_scm_helper is None:
  107. raise QEMUMachineError("No path to socket_scm_helper set")
  108. if not os.path.exists(self._socket_scm_helper):
  109. raise QEMUMachineError("%s does not exist" %
  110. self._socket_scm_helper)
  111. fd_param = ["%s" % self._socket_scm_helper,
  112. "%d" % self._qmp.get_sock_fd(),
  113. "%s" % fd_file_path]
  114. devnull = open(os.path.devnull, 'rb')
  115. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
  116. stderr=subprocess.STDOUT)
  117. output = proc.communicate()[0]
  118. if output:
  119. LOG.debug(output)
  120. return proc.returncode
  121. @staticmethod
  122. def _remove_if_exists(path):
  123. '''Remove file object at path if it exists'''
  124. try:
  125. os.remove(path)
  126. except OSError as exception:
  127. if exception.errno == errno.ENOENT:
  128. return
  129. raise
  130. def is_running(self):
  131. return self._popen is not None and self._popen.poll() is None
  132. def exitcode(self):
  133. if self._popen is None:
  134. return None
  135. return self._popen.poll()
  136. def get_pid(self):
  137. if not self.is_running():
  138. return None
  139. return self._popen.pid
  140. def _load_io_log(self):
  141. if self._qemu_log_path is not None:
  142. with open(self._qemu_log_path, "r") as iolog:
  143. self._iolog = iolog.read()
  144. def _base_args(self):
  145. if isinstance(self._monitor_address, tuple):
  146. moncdev = "socket,id=mon,host=%s,port=%s" % (
  147. self._monitor_address[0],
  148. self._monitor_address[1])
  149. else:
  150. moncdev = 'socket,id=mon,path=%s' % self._vm_monitor
  151. return ['-chardev', moncdev,
  152. '-mon', 'chardev=mon,mode=control',
  153. '-display', 'none', '-vga', 'none']
  154. def _pre_launch(self):
  155. self._temp_dir = tempfile.mkdtemp(dir=self._test_dir)
  156. if self._monitor_address is not None:
  157. self._vm_monitor = self._monitor_address
  158. else:
  159. self._vm_monitor = os.path.join(self._temp_dir,
  160. self._name + "-monitor.sock")
  161. self._qemu_log_path = os.path.join(self._temp_dir, self._name + ".log")
  162. self._qemu_log_file = open(self._qemu_log_path, 'wb')
  163. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._vm_monitor,
  164. server=True)
  165. def _post_launch(self):
  166. self._qmp.accept()
  167. def _post_shutdown(self):
  168. if self._qemu_log_file is not None:
  169. self._qemu_log_file.close()
  170. self._qemu_log_file = None
  171. self._qemu_log_path = None
  172. if self._temp_dir is not None:
  173. shutil.rmtree(self._temp_dir)
  174. self._temp_dir = None
  175. def launch(self):
  176. """
  177. Launch the VM and make sure we cleanup and expose the
  178. command line/output in case of exception
  179. """
  180. if self._launched:
  181. raise QEMUMachineError('VM already launched')
  182. self._iolog = None
  183. self._qemu_full_args = None
  184. try:
  185. self._launch()
  186. self._launched = True
  187. except:
  188. self.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. self._launched = False
  233. def qmp(self, cmd, conv_keys=True, **args):
  234. '''Invoke a QMP command and return the response dict'''
  235. qmp_args = dict()
  236. for key, value in args.items():
  237. if conv_keys:
  238. qmp_args[key.replace('_', '-')] = value
  239. else:
  240. qmp_args[key] = value
  241. return self._qmp.cmd(cmd, args=qmp_args)
  242. def command(self, cmd, conv_keys=True, **args):
  243. '''
  244. Invoke a QMP command.
  245. On success return the response dict.
  246. On failure raise an exception.
  247. '''
  248. reply = self.qmp(cmd, conv_keys, **args)
  249. if reply is None:
  250. raise qmp.qmp.QMPError("Monitor is closed")
  251. if "error" in reply:
  252. raise MonitorResponseError(reply)
  253. return reply["return"]
  254. def get_qmp_event(self, wait=False):
  255. '''Poll for one queued QMP events and return it'''
  256. if len(self._events) > 0:
  257. return self._events.pop(0)
  258. return self._qmp.pull_event(wait=wait)
  259. def get_qmp_events(self, wait=False):
  260. '''Poll for queued QMP events and return a list of dicts'''
  261. events = self._qmp.get_events(wait=wait)
  262. events.extend(self._events)
  263. del self._events[:]
  264. self._qmp.clear_events()
  265. return events
  266. def event_wait(self, name, timeout=60.0, match=None):
  267. '''
  268. Wait for specified timeout on named event in QMP; optionally filter
  269. results by match.
  270. The 'match' is checked to be a recursive subset of the 'event'; skips
  271. branch processing on match's value None
  272. {"foo": {"bar": 1}} matches {"foo": None}
  273. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  274. '''
  275. def event_match(event, match=None):
  276. if match is None:
  277. return True
  278. for key in match:
  279. if key in event:
  280. if isinstance(event[key], dict):
  281. if not event_match(event[key], match[key]):
  282. return False
  283. elif event[key] != match[key]:
  284. return False
  285. else:
  286. return False
  287. return True
  288. # Search cached events
  289. for event in self._events:
  290. if (event['event'] == name) and event_match(event, match):
  291. self._events.remove(event)
  292. return event
  293. # Poll for new events
  294. while True:
  295. event = self._qmp.pull_event(wait=timeout)
  296. if (event['event'] == name) and event_match(event, match):
  297. return event
  298. self._events.append(event)
  299. return None
  300. def get_log(self):
  301. '''
  302. After self.shutdown or failed qemu execution, this returns the output
  303. of the qemu process.
  304. '''
  305. return self._iolog