qemu.py 16 KB

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