machine.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. """
  2. QEMU machine module:
  3. The machine module primarily provides the QEMUMachine class,
  4. which provides facilities for managing the lifetime of a QEMU VM.
  5. """
  6. # Copyright (C) 2015-2016 Red Hat Inc.
  7. # Copyright (C) 2012 IBM Corp.
  8. #
  9. # Authors:
  10. # Fam Zheng <famz@redhat.com>
  11. #
  12. # This work is licensed under the terms of the GNU GPL, version 2. See
  13. # the COPYING file in the top-level directory.
  14. #
  15. # Based on qmp.py.
  16. #
  17. import errno
  18. import logging
  19. import os
  20. import subprocess
  21. import shutil
  22. import socket
  23. import tempfile
  24. from . import qmp
  25. LOG = logging.getLogger(__name__)
  26. class QEMUMachineError(Exception):
  27. """
  28. Exception called when an error in QEMUMachine happens.
  29. """
  30. class QEMUMachineAddDeviceError(QEMUMachineError):
  31. """
  32. Exception raised when a request to add a device can not be fulfilled
  33. The failures are caused by limitations, lack of information or conflicting
  34. requests on the QEMUMachine methods. This exception does not represent
  35. failures reported by the QEMU binary itself.
  36. """
  37. class MonitorResponseError(qmp.QMPError):
  38. """
  39. Represents erroneous QMP monitor reply
  40. """
  41. def __init__(self, reply):
  42. try:
  43. desc = reply["error"]["desc"]
  44. except KeyError:
  45. desc = reply
  46. super(MonitorResponseError, self).__init__(desc)
  47. self.reply = reply
  48. class QEMUMachine(object):
  49. """
  50. A QEMU VM
  51. Use this object as a context manager to ensure the QEMU process terminates::
  52. with VM(binary) as vm:
  53. ...
  54. # vm is guaranteed to be shut down here
  55. """
  56. def __init__(self, binary, args=None, wrapper=None, name=None,
  57. test_dir="/var/tmp", monitor_address=None,
  58. socket_scm_helper=None, sock_dir=None):
  59. '''
  60. Initialize a QEMUMachine
  61. @param binary: path to the qemu binary
  62. @param args: list of extra arguments
  63. @param wrapper: list of arguments used as prefix to qemu binary
  64. @param name: prefix for socket and log file names (default: qemu-PID)
  65. @param test_dir: where to create socket and log file
  66. @param monitor_address: address for QMP monitor
  67. @param socket_scm_helper: helper program, required for send_fd_scm()
  68. @note: Qemu process is not started until launch() is used.
  69. '''
  70. if args is None:
  71. args = []
  72. if wrapper is None:
  73. wrapper = []
  74. if name is None:
  75. name = "qemu-%d" % os.getpid()
  76. if sock_dir is None:
  77. sock_dir = test_dir
  78. self._name = name
  79. self._monitor_address = monitor_address
  80. self._vm_monitor = None
  81. self._qemu_log_path = None
  82. self._qemu_log_file = None
  83. self._popen = None
  84. self._binary = binary
  85. self._args = list(args) # Force copy args in case we modify them
  86. self._wrapper = wrapper
  87. self._events = []
  88. self._iolog = None
  89. self._socket_scm_helper = socket_scm_helper
  90. self._qmp = None
  91. self._qemu_full_args = None
  92. self._test_dir = test_dir
  93. self._temp_dir = None
  94. self._sock_dir = sock_dir
  95. self._launched = False
  96. self._machine = None
  97. self._console_set = False
  98. self._console_device_type = None
  99. self._console_address = None
  100. self._console_socket = None
  101. self._remove_files = []
  102. # just in case logging wasn't configured by the main script:
  103. logging.basicConfig()
  104. def __enter__(self):
  105. return self
  106. def __exit__(self, exc_type, exc_val, exc_tb):
  107. self.shutdown()
  108. return False
  109. def add_monitor_null(self):
  110. """
  111. This can be used to add an unused monitor instance.
  112. """
  113. self._args.append('-monitor')
  114. self._args.append('null')
  115. def add_fd(self, fd, fdset, opaque, opts=''):
  116. """
  117. Pass a file descriptor to the VM
  118. """
  119. options = ['fd=%d' % fd,
  120. 'set=%d' % fdset,
  121. 'opaque=%s' % opaque]
  122. if opts:
  123. options.append(opts)
  124. # This did not exist before 3.4, but since then it is
  125. # mandatory for our purpose
  126. if hasattr(os, 'set_inheritable'):
  127. os.set_inheritable(fd, True)
  128. self._args.append('-add-fd')
  129. self._args.append(','.join(options))
  130. return self
  131. def send_fd_scm(self, fd=None, file_path=None):
  132. """
  133. Send an fd or file_path to socket_scm_helper.
  134. Exactly one of fd and file_path must be given.
  135. If it is file_path, the helper will open that file and pass its own fd.
  136. """
  137. # In iotest.py, the qmp should always use unix socket.
  138. assert self._qmp.is_scm_available()
  139. if self._socket_scm_helper is None:
  140. raise QEMUMachineError("No path to socket_scm_helper set")
  141. if not os.path.exists(self._socket_scm_helper):
  142. raise QEMUMachineError("%s does not exist" %
  143. self._socket_scm_helper)
  144. # This did not exist before 3.4, but since then it is
  145. # mandatory for our purpose
  146. if hasattr(os, 'set_inheritable'):
  147. os.set_inheritable(self._qmp.get_sock_fd(), True)
  148. if fd is not None:
  149. os.set_inheritable(fd, True)
  150. fd_param = ["%s" % self._socket_scm_helper,
  151. "%d" % self._qmp.get_sock_fd()]
  152. if file_path is not None:
  153. assert fd is None
  154. fd_param.append(file_path)
  155. else:
  156. assert fd is not None
  157. fd_param.append(str(fd))
  158. devnull = open(os.path.devnull, 'rb')
  159. proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
  160. stderr=subprocess.STDOUT, close_fds=False)
  161. output = proc.communicate()[0]
  162. if output:
  163. LOG.debug(output)
  164. return proc.returncode
  165. @staticmethod
  166. def _remove_if_exists(path):
  167. """
  168. Remove file object at path if it exists
  169. """
  170. try:
  171. os.remove(path)
  172. except OSError as exception:
  173. if exception.errno == errno.ENOENT:
  174. return
  175. raise
  176. def is_running(self):
  177. """Returns true if the VM is running."""
  178. return self._popen is not None and self._popen.poll() is None
  179. def exitcode(self):
  180. """Returns the exit code if possible, or None."""
  181. if self._popen is None:
  182. return None
  183. return self._popen.poll()
  184. def get_pid(self):
  185. """Returns the PID of the running process, or None."""
  186. if not self.is_running():
  187. return None
  188. return self._popen.pid
  189. def _load_io_log(self):
  190. if self._qemu_log_path is not None:
  191. with open(self._qemu_log_path, "r") as iolog:
  192. self._iolog = iolog.read()
  193. def _base_args(self):
  194. if isinstance(self._monitor_address, tuple):
  195. moncdev = "socket,id=mon,host=%s,port=%s" % (
  196. self._monitor_address[0],
  197. self._monitor_address[1])
  198. else:
  199. moncdev = 'socket,id=mon,path=%s' % self._vm_monitor
  200. args = ['-chardev', moncdev,
  201. '-mon', 'chardev=mon,mode=control',
  202. '-display', 'none', '-vga', 'none']
  203. if self._machine is not None:
  204. args.extend(['-machine', self._machine])
  205. if self._console_set:
  206. self._console_address = os.path.join(self._sock_dir,
  207. self._name + "-console.sock")
  208. self._remove_files.append(self._console_address)
  209. chardev = ('socket,id=console,path=%s,server,nowait' %
  210. self._console_address)
  211. args.extend(['-chardev', chardev])
  212. if self._console_device_type is None:
  213. args.extend(['-serial', 'chardev:console'])
  214. else:
  215. device = '%s,chardev=console' % self._console_device_type
  216. args.extend(['-device', device])
  217. return args
  218. def _pre_launch(self):
  219. self._temp_dir = tempfile.mkdtemp(dir=self._test_dir)
  220. if self._monitor_address is not None:
  221. self._vm_monitor = self._monitor_address
  222. else:
  223. self._vm_monitor = os.path.join(self._sock_dir,
  224. self._name + "-monitor.sock")
  225. self._remove_files.append(self._vm_monitor)
  226. self._qemu_log_path = os.path.join(self._temp_dir, self._name + ".log")
  227. self._qemu_log_file = open(self._qemu_log_path, 'wb')
  228. self._qmp = qmp.QEMUMonitorProtocol(self._vm_monitor,
  229. server=True)
  230. def _post_launch(self):
  231. self._qmp.accept()
  232. def _post_shutdown(self):
  233. if self._qemu_log_file is not None:
  234. self._qemu_log_file.close()
  235. self._qemu_log_file = None
  236. self._qemu_log_path = None
  237. if self._temp_dir is not None:
  238. shutil.rmtree(self._temp_dir)
  239. self._temp_dir = None
  240. while len(self._remove_files) > 0:
  241. self._remove_if_exists(self._remove_files.pop())
  242. def launch(self):
  243. """
  244. Launch the VM and make sure we cleanup and expose the
  245. command line/output in case of exception
  246. """
  247. if self._launched:
  248. raise QEMUMachineError('VM already launched')
  249. self._iolog = None
  250. self._qemu_full_args = None
  251. try:
  252. self._launch()
  253. self._launched = True
  254. except:
  255. self.shutdown()
  256. LOG.debug('Error launching VM')
  257. if self._qemu_full_args:
  258. LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
  259. if self._iolog:
  260. LOG.debug('Output: %r', self._iolog)
  261. raise
  262. def _launch(self):
  263. """
  264. Launch the VM and establish a QMP connection
  265. """
  266. devnull = open(os.path.devnull, 'rb')
  267. self._pre_launch()
  268. self._qemu_full_args = (self._wrapper + [self._binary] +
  269. self._base_args() + self._args)
  270. LOG.debug('VM launch command: %r', ' '.join(self._qemu_full_args))
  271. self._popen = subprocess.Popen(self._qemu_full_args,
  272. stdin=devnull,
  273. stdout=self._qemu_log_file,
  274. stderr=subprocess.STDOUT,
  275. shell=False,
  276. close_fds=False)
  277. self._post_launch()
  278. def wait(self):
  279. """
  280. Wait for the VM to power off
  281. """
  282. self._popen.wait()
  283. self._qmp.close()
  284. self._load_io_log()
  285. self._post_shutdown()
  286. def shutdown(self, has_quit=False):
  287. """
  288. Terminate the VM and clean up
  289. """
  290. # If we keep the console socket open, we may deadlock waiting
  291. # for QEMU to exit, while QEMU is waiting for the socket to
  292. # become writeable.
  293. if self._console_socket is not None:
  294. self._console_socket.close()
  295. self._console_socket = None
  296. if self.is_running():
  297. try:
  298. if not has_quit:
  299. self._qmp.cmd('quit')
  300. self._qmp.close()
  301. except:
  302. self._popen.kill()
  303. self._popen.wait()
  304. self._load_io_log()
  305. self._post_shutdown()
  306. exitcode = self.exitcode()
  307. if exitcode is not None and exitcode < 0:
  308. msg = 'qemu received signal %i: %s'
  309. if self._qemu_full_args:
  310. command = ' '.join(self._qemu_full_args)
  311. else:
  312. command = ''
  313. LOG.warning(msg, -exitcode, command)
  314. self._launched = False
  315. def qmp(self, cmd, conv_keys=True, **args):
  316. """
  317. Invoke a QMP command and return the response dict
  318. """
  319. qmp_args = dict()
  320. for key, value in args.items():
  321. if conv_keys:
  322. qmp_args[key.replace('_', '-')] = value
  323. else:
  324. qmp_args[key] = value
  325. return self._qmp.cmd(cmd, args=qmp_args)
  326. def command(self, cmd, conv_keys=True, **args):
  327. """
  328. Invoke a QMP command.
  329. On success return the response dict.
  330. On failure raise an exception.
  331. """
  332. reply = self.qmp(cmd, conv_keys, **args)
  333. if reply is None:
  334. raise qmp.QMPError("Monitor is closed")
  335. if "error" in reply:
  336. raise MonitorResponseError(reply)
  337. return reply["return"]
  338. def get_qmp_event(self, wait=False):
  339. """
  340. Poll for one queued QMP events and return it
  341. """
  342. if self._events:
  343. return self._events.pop(0)
  344. return self._qmp.pull_event(wait=wait)
  345. def get_qmp_events(self, wait=False):
  346. """
  347. Poll for queued QMP events and return a list of dicts
  348. """
  349. events = self._qmp.get_events(wait=wait)
  350. events.extend(self._events)
  351. del self._events[:]
  352. self._qmp.clear_events()
  353. return events
  354. @staticmethod
  355. def event_match(event, match=None):
  356. """
  357. Check if an event matches optional match criteria.
  358. The match criteria takes the form of a matching subdict. The event is
  359. checked to be a superset of the subdict, recursively, with matching
  360. values whenever the subdict values are not None.
  361. This has a limitation that you cannot explicitly check for None values.
  362. Examples, with the subdict queries on the left:
  363. - None matches any object.
  364. - {"foo": None} matches {"foo": {"bar": 1}}
  365. - {"foo": None} matches {"foo": 5}
  366. - {"foo": {"abc": None}} does not match {"foo": {"bar": 1}}
  367. - {"foo": {"rab": 2}} matches {"foo": {"bar": 1, "rab": 2}}
  368. """
  369. if match is None:
  370. return True
  371. try:
  372. for key in match:
  373. if key in event:
  374. if not QEMUMachine.event_match(event[key], match[key]):
  375. return False
  376. else:
  377. return False
  378. return True
  379. except TypeError:
  380. # either match or event wasn't iterable (not a dict)
  381. return match == event
  382. def event_wait(self, name, timeout=60.0, match=None):
  383. """
  384. event_wait waits for and returns a named event from QMP with a timeout.
  385. name: The event to wait for.
  386. timeout: QEMUMonitorProtocol.pull_event timeout parameter.
  387. match: Optional match criteria. See event_match for details.
  388. """
  389. return self.events_wait([(name, match)], timeout)
  390. def events_wait(self, events, timeout=60.0):
  391. """
  392. events_wait waits for and returns a named event from QMP with a timeout.
  393. events: a sequence of (name, match_criteria) tuples.
  394. The match criteria are optional and may be None.
  395. See event_match for details.
  396. timeout: QEMUMonitorProtocol.pull_event timeout parameter.
  397. """
  398. def _match(event):
  399. for name, match in events:
  400. if event['event'] == name and self.event_match(event, match):
  401. return True
  402. return False
  403. # Search cached events
  404. for event in self._events:
  405. if _match(event):
  406. self._events.remove(event)
  407. return event
  408. # Poll for new events
  409. while True:
  410. event = self._qmp.pull_event(wait=timeout)
  411. if _match(event):
  412. return event
  413. self._events.append(event)
  414. return None
  415. def get_log(self):
  416. """
  417. After self.shutdown or failed qemu execution, this returns the output
  418. of the qemu process.
  419. """
  420. return self._iolog
  421. def add_args(self, *args):
  422. """
  423. Adds to the list of extra arguments to be given to the QEMU binary
  424. """
  425. self._args.extend(args)
  426. def set_machine(self, machine_type):
  427. """
  428. Sets the machine type
  429. If set, the machine type will be added to the base arguments
  430. of the resulting QEMU command line.
  431. """
  432. self._machine = machine_type
  433. def set_console(self, device_type=None):
  434. """
  435. Sets the device type for a console device
  436. If set, the console device and a backing character device will
  437. be added to the base arguments of the resulting QEMU command
  438. line.
  439. This is a convenience method that will either use the provided
  440. device type, or default to a "-serial chardev:console" command
  441. line argument.
  442. The actual setting of command line arguments will be be done at
  443. machine launch time, as it depends on the temporary directory
  444. to be created.
  445. @param device_type: the device type, such as "isa-serial". If
  446. None is given (the default value) a "-serial
  447. chardev:console" command line argument will
  448. be used instead, resorting to the machine's
  449. default device type.
  450. """
  451. self._console_set = True
  452. self._console_device_type = device_type
  453. @property
  454. def console_socket(self):
  455. """
  456. Returns a socket connected to the console
  457. """
  458. if self._console_socket is None:
  459. self._console_socket = socket.socket(socket.AF_UNIX,
  460. socket.SOCK_STREAM)
  461. self._console_socket.connect(self._console_address)
  462. return self._console_socket