qemu.py 15 KB

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