qemu.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. def __init__(self, binary, args=[], wrapper=[], name=None, test_dir="/var/tmp",
  23. monitor_address=None, socket_scm_helper=None, debug=False):
  24. if name is None:
  25. name = "qemu-%d" % os.getpid()
  26. if monitor_address is None:
  27. monitor_address = os.path.join(test_dir, name + "-monitor.sock")
  28. self._monitor_address = monitor_address
  29. self._qemu_log_path = os.path.join(test_dir, name + ".log")
  30. self._popen = None
  31. self._binary = binary
  32. self._args = list(args) # Force copy args in case we modify them
  33. self._wrapper = wrapper
  34. self._events = []
  35. self._iolog = None
  36. self._socket_scm_helper = socket_scm_helper
  37. self._debug = debug
  38. # This can be used to add an unused monitor instance.
  39. def add_monitor_telnet(self, ip, port):
  40. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  41. self._args.append('-monitor')
  42. self._args.append(args)
  43. def add_fd(self, fd, fdset, opaque, opts=''):
  44. '''Pass a file descriptor to the VM'''
  45. options = ['fd=%d' % fd,
  46. 'set=%d' % fdset,
  47. 'opaque=%s' % opaque]
  48. if opts:
  49. options.append(opts)
  50. self._args.append('-add-fd')
  51. self._args.append(','.join(options))
  52. return self
  53. def send_fd_scm(self, fd_file_path):
  54. # In iotest.py, the qmp should always use unix socket.
  55. assert self._qmp.is_scm_available()
  56. if self._socket_scm_helper is None:
  57. print >>sys.stderr, "No path to socket_scm_helper set"
  58. return -1
  59. if os.path.exists(self._socket_scm_helper) == False:
  60. print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
  61. return -1
  62. fd_param = ["%s" % self._socket_scm_helper,
  63. "%d" % self._qmp.get_sock_fd(),
  64. "%s" % fd_file_path]
  65. devnull = open('/dev/null', 'rb')
  66. p = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
  67. stderr=sys.stderr)
  68. return p.wait()
  69. @staticmethod
  70. def _remove_if_exists(path):
  71. '''Remove file object at path if it exists'''
  72. try:
  73. os.remove(path)
  74. except OSError as exception:
  75. if exception.errno == errno.ENOENT:
  76. return
  77. raise
  78. def get_pid(self):
  79. if not self._popen:
  80. return None
  81. return self._popen.pid
  82. def _load_io_log(self):
  83. with open(self._qemu_log_path, "r") as fh:
  84. self._iolog = fh.read()
  85. def _base_args(self):
  86. if isinstance(self._monitor_address, tuple):
  87. moncdev = "socket,id=mon,host=%s,port=%s" % (
  88. self._monitor_address[0],
  89. self._monitor_address[1])
  90. else:
  91. moncdev = 'socket,id=mon,path=%s' % self._monitor_address
  92. return ['-chardev', moncdev,
  93. '-mon', 'chardev=mon,mode=control',
  94. '-display', 'none', '-vga', 'none']
  95. def _pre_launch(self):
  96. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address, server=True,
  97. debug=self._debug)
  98. def _post_launch(self):
  99. self._qmp.accept()
  100. def _post_shutdown(self):
  101. if not isinstance(self._monitor_address, tuple):
  102. self._remove_if_exists(self._monitor_address)
  103. self._remove_if_exists(self._qemu_log_path)
  104. def launch(self):
  105. '''Launch the VM and establish a QMP connection'''
  106. devnull = open('/dev/null', 'rb')
  107. qemulog = open(self._qemu_log_path, 'wb')
  108. try:
  109. self._pre_launch()
  110. args = self._wrapper + [self._binary] + self._base_args() + self._args
  111. self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
  112. stderr=subprocess.STDOUT, shell=False)
  113. self._post_launch()
  114. except:
  115. if self._popen:
  116. self._popen.kill()
  117. self._load_io_log()
  118. self._post_shutdown()
  119. self._popen = None
  120. raise
  121. def shutdown(self):
  122. '''Terminate the VM and clean up'''
  123. if not self._popen is None:
  124. try:
  125. self._qmp.cmd('quit')
  126. self._qmp.close()
  127. except:
  128. self._popen.kill()
  129. exitcode = self._popen.wait()
  130. if exitcode < 0:
  131. sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode, ' '.join(self._args)))
  132. self._load_io_log()
  133. self._post_shutdown()
  134. self._popen = None
  135. underscore_to_dash = string.maketrans('_', '-')
  136. def qmp(self, cmd, conv_keys=True, **args):
  137. '''Invoke a QMP command and return the result dict'''
  138. qmp_args = dict()
  139. for k in args.keys():
  140. if conv_keys:
  141. qmp_args[k.translate(self.underscore_to_dash)] = args[k]
  142. else:
  143. qmp_args[k] = args[k]
  144. return self._qmp.cmd(cmd, args=qmp_args)
  145. def command(self, cmd, conv_keys=True, **args):
  146. reply = self.qmp(cmd, conv_keys, **args)
  147. if reply is None:
  148. raise Exception("Monitor is closed")
  149. if "error" in reply:
  150. raise Exception(reply["error"]["desc"])
  151. return reply["return"]
  152. def get_qmp_event(self, wait=False):
  153. '''Poll for one queued QMP events and return it'''
  154. if len(self._events) > 0:
  155. return self._events.pop(0)
  156. return self._qmp.pull_event(wait=wait)
  157. def get_qmp_events(self, wait=False):
  158. '''Poll for queued QMP events and return a list of dicts'''
  159. events = self._qmp.get_events(wait=wait)
  160. events.extend(self._events)
  161. del self._events[:]
  162. self._qmp.clear_events()
  163. return events
  164. def event_wait(self, name, timeout=60.0, match=None):
  165. # Test if 'match' is a recursive subset of 'event'
  166. def event_match(event, match=None):
  167. if match is None:
  168. return True
  169. for key in match:
  170. if key in event:
  171. if isinstance(event[key], dict):
  172. if not event_match(event[key], match[key]):
  173. return False
  174. elif event[key] != match[key]:
  175. return False
  176. else:
  177. return False
  178. return True
  179. # Search cached events
  180. for event in self._events:
  181. if (event['event'] == name) and event_match(event, match):
  182. self._events.remove(event)
  183. return event
  184. # Poll for new events
  185. while True:
  186. event = self._qmp.pull_event(wait=timeout)
  187. if (event['event'] == name) and event_match(event, match):
  188. return event
  189. self._events.append(event)
  190. return None
  191. def get_log(self):
  192. return self._iolog