qemu.py 15 KB

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