qemu.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 string
  16. import os
  17. import sys
  18. import subprocess
  19. import qmp.qmp
  20. class QEMUMachine(object):
  21. '''A QEMU VM
  22. Use this object as a context manager to ensure the QEMU process terminates::
  23. with VM(binary) as vm:
  24. ...
  25. # vm is guaranteed to be shut down here
  26. '''
  27. def __init__(self, binary, args=None, wrapper=None, name=None,
  28. test_dir="/var/tmp", monitor_address=None,
  29. socket_scm_helper=None, debug=False):
  30. '''
  31. Initialize a QEMUMachine
  32. @param binary: path to the qemu binary
  33. @param args: list of extra arguments
  34. @param wrapper: list of arguments used as prefix to qemu binary
  35. @param name: prefix for socket and log file names (default: qemu-PID)
  36. @param test_dir: where to create socket and log file
  37. @param monitor_address: address for QMP monitor
  38. @param socket_scm_helper: helper program, required for send_fd_scm()"
  39. @param debug: enable debug mode
  40. @note: Qemu process is not started until launch() is used.
  41. '''
  42. if args is None:
  43. args = []
  44. if wrapper is None:
  45. wrapper = []
  46. if name is None:
  47. name = "qemu-%d" % os.getpid()
  48. if monitor_address is None:
  49. monitor_address = os.path.join(test_dir, name + "-monitor.sock")
  50. self._monitor_address = monitor_address
  51. self._qemu_log_path = os.path.join(test_dir, name + ".log")
  52. self._popen = None
  53. self._binary = binary
  54. self._args = list(args) # Force copy args in case we modify them
  55. self._wrapper = wrapper
  56. self._events = []
  57. self._iolog = None
  58. self._socket_scm_helper = socket_scm_helper
  59. self._debug = debug
  60. self._qmp = None
  61. def __enter__(self):
  62. return self
  63. def __exit__(self, exc_type, exc_val, exc_tb):
  64. self.shutdown()
  65. return False
  66. # This can be used to add an unused monitor instance.
  67. def add_monitor_telnet(self, ip, port):
  68. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  69. self._args.append('-monitor')
  70. self._args.append(args)
  71. def add_fd(self, fd, fdset, opaque, opts=''):
  72. '''Pass a file descriptor to the VM'''
  73. options = ['fd=%d' % fd,
  74. 'set=%d' % fdset,
  75. 'opaque=%s' % opaque]
  76. if opts:
  77. options.append(opts)
  78. self._args.append('-add-fd')
  79. self._args.append(','.join(options))
  80. return self
  81. def send_fd_scm(self, fd_file_path):
  82. # In iotest.py, the qmp should always use unix socket.
  83. assert self._qmp.is_scm_available()
  84. if self._socket_scm_helper is None:
  85. print >>sys.stderr, "No path to socket_scm_helper set"
  86. return -1
  87. if not os.path.exists(self._socket_scm_helper):
  88. print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
  89. return -1
  90. fd_param = ["%s" % self._socket_scm_helper,
  91. "%d" % self._qmp.get_sock_fd(),
  92. "%s" % fd_file_path]
  93. devnull = open('/dev/null', 'rb')
  94. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
  95. stderr=sys.stderr)
  96. return proc.wait()
  97. @staticmethod
  98. def _remove_if_exists(path):
  99. '''Remove file object at path if it exists'''
  100. try:
  101. os.remove(path)
  102. except OSError as exception:
  103. if exception.errno == errno.ENOENT:
  104. return
  105. raise
  106. def is_running(self):
  107. return self._popen and (self._popen.returncode is None)
  108. def exitcode(self):
  109. if self._popen is None:
  110. return None
  111. return self._popen.returncode
  112. def get_pid(self):
  113. if not self.is_running():
  114. return None
  115. return self._popen.pid
  116. def _load_io_log(self):
  117. with open(self._qemu_log_path, "r") as iolog:
  118. self._iolog = iolog.read()
  119. def _base_args(self):
  120. if isinstance(self._monitor_address, tuple):
  121. moncdev = "socket,id=mon,host=%s,port=%s" % (
  122. self._monitor_address[0],
  123. self._monitor_address[1])
  124. else:
  125. moncdev = 'socket,id=mon,path=%s' % self._monitor_address
  126. return ['-chardev', moncdev,
  127. '-mon', 'chardev=mon,mode=control',
  128. '-display', 'none', '-vga', 'none']
  129. def _pre_launch(self):
  130. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
  131. server=True,
  132. debug=self._debug)
  133. def _post_launch(self):
  134. self._qmp.accept()
  135. def _post_shutdown(self):
  136. if not isinstance(self._monitor_address, tuple):
  137. self._remove_if_exists(self._monitor_address)
  138. self._remove_if_exists(self._qemu_log_path)
  139. def launch(self):
  140. '''Launch the VM and establish a QMP connection'''
  141. devnull = open('/dev/null', 'rb')
  142. qemulog = open(self._qemu_log_path, 'wb')
  143. try:
  144. self._pre_launch()
  145. args = (self._wrapper + [self._binary] + self._base_args() +
  146. self._args)
  147. self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
  148. stderr=subprocess.STDOUT,
  149. shell=False)
  150. self._post_launch()
  151. except:
  152. if self.is_running():
  153. self._popen.kill()
  154. self._popen.wait()
  155. self._load_io_log()
  156. self._post_shutdown()
  157. raise
  158. def shutdown(self):
  159. '''Terminate the VM and clean up'''
  160. if self.is_running():
  161. try:
  162. self._qmp.cmd('quit')
  163. self._qmp.close()
  164. except:
  165. self._popen.kill()
  166. exitcode = self._popen.wait()
  167. if exitcode < 0:
  168. sys.stderr.write('qemu received signal %i: %s\n'
  169. % (-exitcode, ' '.join(self._args)))
  170. self._load_io_log()
  171. self._post_shutdown()
  172. underscore_to_dash = string.maketrans('_', '-')
  173. def qmp(self, cmd, conv_keys=True, **args):
  174. '''Invoke a QMP command and return the response dict'''
  175. qmp_args = dict()
  176. for key, value in args.iteritems():
  177. if conv_keys:
  178. qmp_args[key.translate(self.underscore_to_dash)] = value
  179. else:
  180. qmp_args[key] = value
  181. return self._qmp.cmd(cmd, args=qmp_args)
  182. def command(self, cmd, conv_keys=True, **args):
  183. '''
  184. Invoke a QMP command.
  185. On success return the response dict.
  186. On failure raise an exception.
  187. '''
  188. reply = self.qmp(cmd, conv_keys, **args)
  189. if reply is None:
  190. raise Exception("Monitor is closed")
  191. if "error" in reply:
  192. raise Exception(reply["error"]["desc"])
  193. return reply["return"]
  194. def get_qmp_event(self, wait=False):
  195. '''Poll for one queued QMP events and return it'''
  196. if len(self._events) > 0:
  197. return self._events.pop(0)
  198. return self._qmp.pull_event(wait=wait)
  199. def get_qmp_events(self, wait=False):
  200. '''Poll for queued QMP events and return a list of dicts'''
  201. events = self._qmp.get_events(wait=wait)
  202. events.extend(self._events)
  203. del self._events[:]
  204. self._qmp.clear_events()
  205. return events
  206. def event_wait(self, name, timeout=60.0, match=None):
  207. '''
  208. Wait for specified timeout on named event in QMP; optionally filter
  209. results by match.
  210. The 'match' is checked to be a recursive subset of the 'event'; skips
  211. branch processing on match's value None
  212. {"foo": {"bar": 1}} matches {"foo": None}
  213. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  214. '''
  215. def event_match(event, match=None):
  216. if match is None:
  217. return True
  218. for key in match:
  219. if key in event:
  220. if isinstance(event[key], dict):
  221. if not event_match(event[key], match[key]):
  222. return False
  223. elif event[key] != match[key]:
  224. return False
  225. else:
  226. return False
  227. return True
  228. # Search cached events
  229. for event in self._events:
  230. if (event['event'] == name) and event_match(event, match):
  231. self._events.remove(event)
  232. return event
  233. # Poll for new events
  234. while True:
  235. event = self._qmp.pull_event(wait=timeout)
  236. if (event['event'] == name) and event_match(event, match):
  237. return event
  238. self._events.append(event)
  239. return None
  240. def get_log(self):
  241. '''
  242. After self.shutdown or failed qemu execution, this returns the output
  243. of the qemu process.
  244. '''
  245. return self._iolog