qemu.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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 re
  20. import shutil
  21. import socket
  22. import tempfile
  23. LOG = logging.getLogger(__name__)
  24. #: Maps machine types to the preferred console device types
  25. CONSOLE_DEV_TYPES = {
  26. r'^clipper$': 'isa-serial',
  27. r'^malta': 'isa-serial',
  28. r'^(pc.*|q35.*|isapc)$': 'isa-serial',
  29. r'^(40p|powernv|prep)$': 'isa-serial',
  30. r'^pseries.*': 'spapr-vty',
  31. r'^s390-ccw-virtio.*': 'sclpconsole',
  32. }
  33. class QEMUMachineError(Exception):
  34. """
  35. Exception called when an error in QEMUMachine happens.
  36. """
  37. class QEMUMachineAddDeviceError(QEMUMachineError):
  38. """
  39. Exception raised when a request to add a device can not be fulfilled
  40. The failures are caused by limitations, lack of information or conflicting
  41. requests on the QEMUMachine methods. This exception does not represent
  42. failures reported by the QEMU binary itself.
  43. """
  44. class MonitorResponseError(qmp.qmp.QMPError):
  45. '''
  46. Represents erroneous QMP monitor reply
  47. '''
  48. def __init__(self, reply):
  49. try:
  50. desc = reply["error"]["desc"]
  51. except KeyError:
  52. desc = reply
  53. super(MonitorResponseError, self).__init__(desc)
  54. self.reply = reply
  55. class QEMUMachine(object):
  56. '''A QEMU VM
  57. Use this object as a context manager to ensure the QEMU process terminates::
  58. with VM(binary) as vm:
  59. ...
  60. # vm is guaranteed to be shut down here
  61. '''
  62. def __init__(self, binary, args=None, wrapper=None, name=None,
  63. test_dir="/var/tmp", monitor_address=None,
  64. socket_scm_helper=None):
  65. '''
  66. Initialize a QEMUMachine
  67. @param binary: path to the qemu binary
  68. @param args: list of extra arguments
  69. @param wrapper: list of arguments used as prefix to qemu binary
  70. @param name: prefix for socket and log file names (default: qemu-PID)
  71. @param test_dir: where to create socket and log file
  72. @param monitor_address: address for QMP monitor
  73. @param socket_scm_helper: helper program, required for send_fd_scm()"
  74. @note: Qemu process is not started until launch() is used.
  75. '''
  76. if args is None:
  77. args = []
  78. if wrapper is None:
  79. wrapper = []
  80. if name is None:
  81. name = "qemu-%d" % os.getpid()
  82. self._name = name
  83. self._monitor_address = monitor_address
  84. self._vm_monitor = None
  85. self._qemu_log_path = None
  86. self._qemu_log_file = None
  87. self._popen = None
  88. self._binary = binary
  89. self._args = list(args) # Force copy args in case we modify them
  90. self._wrapper = wrapper
  91. self._events = []
  92. self._iolog = None
  93. self._socket_scm_helper = socket_scm_helper
  94. self._qmp = None
  95. self._qemu_full_args = None
  96. self._test_dir = test_dir
  97. self._temp_dir = None
  98. self._launched = False
  99. self._machine = None
  100. self._console_device_type = None
  101. self._console_address = None
  102. self._console_socket = None
  103. # just in case logging wasn't configured by the main script:
  104. logging.basicConfig()
  105. def __enter__(self):
  106. return self
  107. def __exit__(self, exc_type, exc_val, exc_tb):
  108. self.shutdown()
  109. return False
  110. # This can be used to add an unused monitor instance.
  111. def add_monitor_telnet(self, ip, port):
  112. args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
  113. self._args.append('-monitor')
  114. self._args.append(args)
  115. def add_fd(self, fd, fdset, opaque, opts=''):
  116. '''Pass a file descriptor to the VM'''
  117. options = ['fd=%d' % fd,
  118. 'set=%d' % fdset,
  119. 'opaque=%s' % opaque]
  120. if opts:
  121. options.append(opts)
  122. self._args.append('-add-fd')
  123. self._args.append(','.join(options))
  124. return self
  125. def send_fd_scm(self, fd_file_path):
  126. # In iotest.py, the qmp should always use unix socket.
  127. assert self._qmp.is_scm_available()
  128. if self._socket_scm_helper is None:
  129. raise QEMUMachineError("No path to socket_scm_helper set")
  130. if not os.path.exists(self._socket_scm_helper):
  131. raise QEMUMachineError("%s does not exist" %
  132. self._socket_scm_helper)
  133. fd_param = ["%s" % self._socket_scm_helper,
  134. "%d" % self._qmp.get_sock_fd(),
  135. "%s" % fd_file_path]
  136. devnull = open(os.path.devnull, 'rb')
  137. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
  138. stderr=subprocess.STDOUT)
  139. output = proc.communicate()[0]
  140. if output:
  141. LOG.debug(output)
  142. return proc.returncode
  143. @staticmethod
  144. def _remove_if_exists(path):
  145. '''Remove file object at path if it exists'''
  146. try:
  147. os.remove(path)
  148. except OSError as exception:
  149. if exception.errno == errno.ENOENT:
  150. return
  151. raise
  152. def is_running(self):
  153. return self._popen is not None and self._popen.poll() is None
  154. def exitcode(self):
  155. if self._popen is None:
  156. return None
  157. return self._popen.poll()
  158. def get_pid(self):
  159. if not self.is_running():
  160. return None
  161. return self._popen.pid
  162. def _load_io_log(self):
  163. if self._qemu_log_path is not None:
  164. with open(self._qemu_log_path, "r") as iolog:
  165. self._iolog = iolog.read()
  166. def _base_args(self):
  167. if isinstance(self._monitor_address, tuple):
  168. moncdev = "socket,id=mon,host=%s,port=%s" % (
  169. self._monitor_address[0],
  170. self._monitor_address[1])
  171. else:
  172. moncdev = 'socket,id=mon,path=%s' % self._vm_monitor
  173. args = ['-chardev', moncdev,
  174. '-mon', 'chardev=mon,mode=control',
  175. '-display', 'none', '-vga', 'none']
  176. if self._machine is not None:
  177. args.extend(['-machine', self._machine])
  178. if self._console_device_type is not None:
  179. self._console_address = os.path.join(self._temp_dir,
  180. self._name + "-console.sock")
  181. chardev = ('socket,id=console,path=%s,server,nowait' %
  182. self._console_address)
  183. device = '%s,chardev=console' % self._console_device_type
  184. args.extend(['-chardev', chardev, '-device', device])
  185. return args
  186. def _pre_launch(self):
  187. self._temp_dir = tempfile.mkdtemp(dir=self._test_dir)
  188. if self._monitor_address is not None:
  189. self._vm_monitor = self._monitor_address
  190. else:
  191. self._vm_monitor = os.path.join(self._temp_dir,
  192. self._name + "-monitor.sock")
  193. self._qemu_log_path = os.path.join(self._temp_dir, self._name + ".log")
  194. self._qemu_log_file = open(self._qemu_log_path, 'wb')
  195. self._qmp = qmp.qmp.QEMUMonitorProtocol(self._vm_monitor,
  196. server=True)
  197. def _post_launch(self):
  198. self._qmp.accept()
  199. def _post_shutdown(self):
  200. if self._qemu_log_file is not None:
  201. self._qemu_log_file.close()
  202. self._qemu_log_file = None
  203. self._qemu_log_path = None
  204. if self._console_socket is not None:
  205. self._console_socket.close()
  206. self._console_socket = None
  207. if self._temp_dir is not None:
  208. shutil.rmtree(self._temp_dir)
  209. self._temp_dir = None
  210. def launch(self):
  211. """
  212. Launch the VM and make sure we cleanup and expose the
  213. command line/output in case of exception
  214. """
  215. if self._launched:
  216. raise QEMUMachineError('VM already launched')
  217. self._iolog = None
  218. self._qemu_full_args = None
  219. try:
  220. self._launch()
  221. self._launched = True
  222. except:
  223. self.shutdown()
  224. LOG.debug('Error launching VM')
  225. if self._qemu_full_args:
  226. LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
  227. if self._iolog:
  228. LOG.debug('Output: %r', self._iolog)
  229. raise
  230. def _launch(self):
  231. '''Launch the VM and establish a QMP connection'''
  232. devnull = open(os.path.devnull, 'rb')
  233. self._pre_launch()
  234. self._qemu_full_args = (self._wrapper + [self._binary] +
  235. self._base_args() + self._args)
  236. self._popen = subprocess.Popen(self._qemu_full_args,
  237. stdin=devnull,
  238. stdout=self._qemu_log_file,
  239. stderr=subprocess.STDOUT,
  240. shell=False)
  241. self._post_launch()
  242. def wait(self):
  243. '''Wait for the VM to power off'''
  244. self._popen.wait()
  245. self._qmp.close()
  246. self._load_io_log()
  247. self._post_shutdown()
  248. def shutdown(self):
  249. '''Terminate the VM and clean up'''
  250. if self.is_running():
  251. try:
  252. self._qmp.cmd('quit')
  253. self._qmp.close()
  254. except:
  255. self._popen.kill()
  256. self._popen.wait()
  257. self._load_io_log()
  258. self._post_shutdown()
  259. exitcode = self.exitcode()
  260. if exitcode is not None and exitcode < 0:
  261. msg = 'qemu received signal %i: %s'
  262. if self._qemu_full_args:
  263. command = ' '.join(self._qemu_full_args)
  264. else:
  265. command = ''
  266. LOG.warn(msg, exitcode, command)
  267. self._launched = False
  268. def qmp(self, cmd, conv_keys=True, **args):
  269. '''Invoke a QMP command and return the response dict'''
  270. qmp_args = dict()
  271. for key, value in args.items():
  272. if conv_keys:
  273. qmp_args[key.replace('_', '-')] = value
  274. else:
  275. qmp_args[key] = value
  276. return self._qmp.cmd(cmd, args=qmp_args)
  277. def command(self, cmd, conv_keys=True, **args):
  278. '''
  279. Invoke a QMP command.
  280. On success return the response dict.
  281. On failure raise an exception.
  282. '''
  283. reply = self.qmp(cmd, conv_keys, **args)
  284. if reply is None:
  285. raise qmp.qmp.QMPError("Monitor is closed")
  286. if "error" in reply:
  287. raise MonitorResponseError(reply)
  288. return reply["return"]
  289. def get_qmp_event(self, wait=False):
  290. '''Poll for one queued QMP events and return it'''
  291. if len(self._events) > 0:
  292. return self._events.pop(0)
  293. return self._qmp.pull_event(wait=wait)
  294. def get_qmp_events(self, wait=False):
  295. '''Poll for queued QMP events and return a list of dicts'''
  296. events = self._qmp.get_events(wait=wait)
  297. events.extend(self._events)
  298. del self._events[:]
  299. self._qmp.clear_events()
  300. return events
  301. def event_wait(self, name, timeout=60.0, match=None):
  302. '''
  303. Wait for specified timeout on named event in QMP; optionally filter
  304. results by match.
  305. The 'match' is checked to be a recursive subset of the 'event'; skips
  306. branch processing on match's value None
  307. {"foo": {"bar": 1}} matches {"foo": None}
  308. {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
  309. '''
  310. def event_match(event, match=None):
  311. if match is None:
  312. return True
  313. for key in match:
  314. if key in event:
  315. if isinstance(event[key], dict):
  316. if not event_match(event[key], match[key]):
  317. return False
  318. elif event[key] != match[key]:
  319. return False
  320. else:
  321. return False
  322. return True
  323. # Search cached events
  324. for event in self._events:
  325. if (event['event'] == name) and event_match(event, match):
  326. self._events.remove(event)
  327. return event
  328. # Poll for new events
  329. while True:
  330. event = self._qmp.pull_event(wait=timeout)
  331. if (event['event'] == name) and event_match(event, match):
  332. return event
  333. self._events.append(event)
  334. return None
  335. def get_log(self):
  336. '''
  337. After self.shutdown or failed qemu execution, this returns the output
  338. of the qemu process.
  339. '''
  340. return self._iolog
  341. def add_args(self, *args):
  342. '''
  343. Adds to the list of extra arguments to be given to the QEMU binary
  344. '''
  345. self._args.extend(args)
  346. def set_machine(self, machine_type):
  347. '''
  348. Sets the machine type
  349. If set, the machine type will be added to the base arguments
  350. of the resulting QEMU command line.
  351. '''
  352. self._machine = machine_type
  353. def set_console(self, device_type=None):
  354. '''
  355. Sets the device type for a console device
  356. If set, the console device and a backing character device will
  357. be added to the base arguments of the resulting QEMU command
  358. line.
  359. This is a convenience method that will either use the provided
  360. device type, of if not given, it will used the device type set
  361. on CONSOLE_DEV_TYPES.
  362. The actual setting of command line arguments will be be done at
  363. machine launch time, as it depends on the temporary directory
  364. to be created.
  365. @param device_type: the device type, such as "isa-serial"
  366. @raises: QEMUMachineAddDeviceError if the device type is not given
  367. and can not be determined.
  368. '''
  369. if device_type is None:
  370. if self._machine is None:
  371. raise QEMUMachineAddDeviceError("Can not add a console device:"
  372. " QEMU instance without a "
  373. "defined machine type")
  374. for regex, device in CONSOLE_DEV_TYPES.items():
  375. if re.match(regex, self._machine):
  376. device_type = device
  377. break
  378. if device_type is None:
  379. raise QEMUMachineAddDeviceError("Can not add a console device:"
  380. " no matching console device "
  381. "type definition")
  382. self._console_device_type = device_type
  383. @property
  384. def console_socket(self):
  385. """
  386. Returns a socket connected to the console
  387. """
  388. if self._console_socket is None:
  389. self._console_socket = socket.socket(socket.AF_UNIX,
  390. socket.SOCK_STREAM)
  391. self._console_socket.connect(self._console_address)
  392. return self._console_socket