]>
Commit | Line | Data |
---|---|---|
66613974 DB |
1 | # QEMU library |
2 | # | |
3 | # Copyright (C) 2015-2016 Red Hat Inc. | |
4 | # Copyright (C) 2012 IBM Corp. | |
5 | # | |
6 | # Authors: | |
7 | # Fam Zheng <[email protected]> | |
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 | ||
15 | import errno | |
4738b0a8 | 16 | import logging |
66613974 DB |
17 | import os |
18 | import sys | |
19 | import subprocess | |
20 | import qmp.qmp | |
21 | ||
22 | ||
4738b0a8 AP |
23 | LOG = logging.getLogger(__name__) |
24 | ||
25 | ||
26 | class QEMUMachineError(Exception): | |
27 | """ | |
28 | Exception called when an error in QEMUMachine happens. | |
29 | """ | |
30 | ||
31 | ||
a004e249 LD |
32 | class MonitorResponseError(qmp.qmp.QMPError): |
33 | ''' | |
34 | Represents erroneous QMP monitor reply | |
35 | ''' | |
36 | def __init__(self, reply): | |
37 | try: | |
38 | desc = reply["error"]["desc"] | |
39 | except KeyError: | |
40 | desc = reply | |
41 | super(MonitorResponseError, self).__init__(desc) | |
42 | self.reply = reply | |
43 | ||
44 | ||
66613974 | 45 | class QEMUMachine(object): |
d792bc38 SH |
46 | '''A QEMU VM |
47 | ||
48 | Use this object as a context manager to ensure the QEMU process terminates:: | |
49 | ||
50 | with VM(binary) as vm: | |
51 | ... | |
52 | # vm is guaranteed to be shut down here | |
53 | ''' | |
66613974 | 54 | |
2782fc51 | 55 | def __init__(self, binary, args=None, wrapper=None, name=None, |
2d853c70 | 56 | test_dir="/var/tmp", monitor_address=None, |
1a6d3757 | 57 | socket_scm_helper=None): |
2d853c70 LD |
58 | ''' |
59 | Initialize a QEMUMachine | |
60 | ||
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()" | |
2d853c70 LD |
68 | @note: Qemu process is not started until launch() is used. |
69 | ''' | |
2782fc51 LD |
70 | if args is None: |
71 | args = [] | |
72 | if wrapper is None: | |
73 | wrapper = [] | |
66613974 DB |
74 | if name is None: |
75 | name = "qemu-%d" % os.getpid() | |
76 | if monitor_address is None: | |
77 | monitor_address = os.path.join(test_dir, name + "-monitor.sock") | |
78 | self._monitor_address = monitor_address | |
79 | self._qemu_log_path = os.path.join(test_dir, name + ".log") | |
80 | self._popen = None | |
81 | self._binary = binary | |
2d853c70 | 82 | self._args = list(args) # Force copy args in case we modify them |
66613974 DB |
83 | self._wrapper = wrapper |
84 | self._events = [] | |
85 | self._iolog = None | |
4c44b4a4 | 86 | self._socket_scm_helper = socket_scm_helper |
2d853c70 | 87 | self._qmp = None |
dab91d9a | 88 | self._qemu_full_args = None |
66613974 | 89 | |
5810314e | 90 | # just in case logging wasn't configured by the main script: |
1a6d3757 | 91 | logging.basicConfig() |
5810314e | 92 | |
d792bc38 SH |
93 | def __enter__(self): |
94 | return self | |
95 | ||
96 | def __exit__(self, exc_type, exc_val, exc_tb): | |
97 | self.shutdown() | |
98 | return False | |
99 | ||
66613974 DB |
100 | # This can be used to add an unused monitor instance. |
101 | def add_monitor_telnet(self, ip, port): | |
102 | args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port) | |
103 | self._args.append('-monitor') | |
104 | self._args.append(args) | |
105 | ||
106 | def add_fd(self, fd, fdset, opaque, opts=''): | |
107 | '''Pass a file descriptor to the VM''' | |
108 | options = ['fd=%d' % fd, | |
109 | 'set=%d' % fdset, | |
110 | 'opaque=%s' % opaque] | |
111 | if opts: | |
112 | options.append(opts) | |
113 | ||
114 | self._args.append('-add-fd') | |
115 | self._args.append(','.join(options)) | |
116 | return self | |
117 | ||
118 | def send_fd_scm(self, fd_file_path): | |
119 | # In iotest.py, the qmp should always use unix socket. | |
120 | assert self._qmp.is_scm_available() | |
4c44b4a4 | 121 | if self._socket_scm_helper is None: |
4738b0a8 | 122 | raise QEMUMachineError("No path to socket_scm_helper set") |
2d853c70 | 123 | if not os.path.exists(self._socket_scm_helper): |
4738b0a8 AP |
124 | raise QEMUMachineError("%s does not exist" % |
125 | self._socket_scm_helper) | |
4c44b4a4 | 126 | fd_param = ["%s" % self._socket_scm_helper, |
66613974 DB |
127 | "%d" % self._qmp.get_sock_fd(), |
128 | "%s" % fd_file_path] | |
63e0ba55 | 129 | devnull = open(os.path.devnull, 'rb') |
4738b0a8 AP |
130 | proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE, |
131 | stderr=subprocess.STDOUT) | |
132 | output = proc.communicate()[0] | |
133 | if output: | |
134 | LOG.debug(output) | |
135 | ||
136 | return proc.returncode | |
66613974 DB |
137 | |
138 | @staticmethod | |
139 | def _remove_if_exists(path): | |
140 | '''Remove file object at path if it exists''' | |
141 | try: | |
142 | os.remove(path) | |
143 | except OSError as exception: | |
144 | if exception.errno == errno.ENOENT: | |
145 | return | |
146 | raise | |
147 | ||
37bbcd57 | 148 | def is_running(self): |
f6cf7f5a | 149 | return self._popen is not None and self._popen.returncode is None |
37bbcd57 | 150 | |
b2b8d986 EH |
151 | def exitcode(self): |
152 | if self._popen is None: | |
153 | return None | |
154 | return self._popen.returncode | |
155 | ||
66613974 | 156 | def get_pid(self): |
37bbcd57 | 157 | if not self.is_running(): |
66613974 DB |
158 | return None |
159 | return self._popen.pid | |
160 | ||
161 | def _load_io_log(self): | |
2d853c70 LD |
162 | with open(self._qemu_log_path, "r") as iolog: |
163 | self._iolog = iolog.read() | |
66613974 DB |
164 | |
165 | def _base_args(self): | |
166 | if isinstance(self._monitor_address, tuple): | |
167 | moncdev = "socket,id=mon,host=%s,port=%s" % ( | |
168 | self._monitor_address[0], | |
169 | self._monitor_address[1]) | |
170 | else: | |
171 | moncdev = 'socket,id=mon,path=%s' % self._monitor_address | |
172 | return ['-chardev', moncdev, | |
173 | '-mon', 'chardev=mon,mode=control', | |
174 | '-display', 'none', '-vga', 'none'] | |
175 | ||
176 | def _pre_launch(self): | |
2d853c70 | 177 | self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address, |
09177654 | 178 | server=True) |
66613974 DB |
179 | |
180 | def _post_launch(self): | |
181 | self._qmp.accept() | |
182 | ||
183 | def _post_shutdown(self): | |
184 | if not isinstance(self._monitor_address, tuple): | |
185 | self._remove_if_exists(self._monitor_address) | |
186 | self._remove_if_exists(self._qemu_log_path) | |
187 | ||
188 | def launch(self): | |
189 | '''Launch the VM and establish a QMP connection''' | |
b92a0011 | 190 | self._iolog = None |
dab91d9a | 191 | self._qemu_full_args = None |
63e0ba55 | 192 | devnull = open(os.path.devnull, 'rb') |
66613974 DB |
193 | qemulog = open(self._qemu_log_path, 'wb') |
194 | try: | |
195 | self._pre_launch() | |
f75637ba KW |
196 | self._qemu_full_args = (self._wrapper + [self._binary] + |
197 | self._base_args() + self._args) | |
dab91d9a AP |
198 | self._popen = subprocess.Popen(self._qemu_full_args, |
199 | stdin=devnull, | |
200 | stdout=qemulog, | |
2d853c70 LD |
201 | stderr=subprocess.STDOUT, |
202 | shell=False) | |
66613974 DB |
203 | self._post_launch() |
204 | except: | |
37bbcd57 | 205 | if self.is_running(): |
66613974 | 206 | self._popen.kill() |
37bbcd57 | 207 | self._popen.wait() |
66613974 DB |
208 | self._load_io_log() |
209 | self._post_shutdown() | |
b92a0011 AP |
210 | |
211 | LOG.debug('Error launching VM') | |
212 | if self._qemu_full_args: | |
213 | LOG.debug('Command: %r', ' '.join(self._qemu_full_args)) | |
214 | if self._iolog: | |
215 | LOG.debug('Output: %r', self._iolog) | |
66613974 DB |
216 | raise |
217 | ||
22491a2f FZ |
218 | def wait(self): |
219 | '''Wait for the VM to power off''' | |
220 | self._popen.wait() | |
221 | self._qmp.close() | |
222 | self._load_io_log() | |
223 | self._post_shutdown() | |
224 | ||
66613974 DB |
225 | def shutdown(self): |
226 | '''Terminate the VM and clean up''' | |
37bbcd57 | 227 | if self.is_running(): |
66613974 DB |
228 | try: |
229 | self._qmp.cmd('quit') | |
230 | self._qmp.close() | |
231 | except: | |
232 | self._popen.kill() | |
dab91d9a | 233 | self._popen.wait() |
66613974 | 234 | |
66613974 DB |
235 | self._load_io_log() |
236 | self._post_shutdown() | |
66613974 | 237 | |
dab91d9a AP |
238 | exitcode = self.exitcode() |
239 | if exitcode is not None and exitcode < 0: | |
240 | msg = 'qemu received signal %i: %s' | |
241 | if self._qemu_full_args: | |
242 | command = ' '.join(self._qemu_full_args) | |
243 | else: | |
244 | command = '' | |
245 | LOG.warn(msg, exitcode, command) | |
246 | ||
66613974 | 247 | def qmp(self, cmd, conv_keys=True, **args): |
2d853c70 | 248 | '''Invoke a QMP command and return the response dict''' |
66613974 | 249 | qmp_args = dict() |
7f33ca78 | 250 | for key, value in args.iteritems(): |
66613974 | 251 | if conv_keys: |
41f714b1 | 252 | qmp_args[key.replace('_', '-')] = value |
66613974 | 253 | else: |
7f33ca78 | 254 | qmp_args[key] = value |
66613974 DB |
255 | |
256 | return self._qmp.cmd(cmd, args=qmp_args) | |
257 | ||
258 | def command(self, cmd, conv_keys=True, **args): | |
2d853c70 LD |
259 | ''' |
260 | Invoke a QMP command. | |
261 | On success return the response dict. | |
262 | On failure raise an exception. | |
263 | ''' | |
66613974 DB |
264 | reply = self.qmp(cmd, conv_keys, **args) |
265 | if reply is None: | |
a004e249 | 266 | raise qmp.qmp.QMPError("Monitor is closed") |
66613974 | 267 | if "error" in reply: |
a004e249 | 268 | raise MonitorResponseError(reply) |
66613974 DB |
269 | return reply["return"] |
270 | ||
271 | def get_qmp_event(self, wait=False): | |
272 | '''Poll for one queued QMP events and return it''' | |
273 | if len(self._events) > 0: | |
274 | return self._events.pop(0) | |
275 | return self._qmp.pull_event(wait=wait) | |
276 | ||
277 | def get_qmp_events(self, wait=False): | |
278 | '''Poll for queued QMP events and return a list of dicts''' | |
279 | events = self._qmp.get_events(wait=wait) | |
280 | events.extend(self._events) | |
281 | del self._events[:] | |
282 | self._qmp.clear_events() | |
283 | return events | |
284 | ||
285 | def event_wait(self, name, timeout=60.0, match=None): | |
2d853c70 LD |
286 | ''' |
287 | Wait for specified timeout on named event in QMP; optionally filter | |
288 | results by match. | |
289 | ||
290 | The 'match' is checked to be a recursive subset of the 'event'; skips | |
291 | branch processing on match's value None | |
292 | {"foo": {"bar": 1}} matches {"foo": None} | |
293 | {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}} | |
294 | ''' | |
4c44b4a4 DB |
295 | def event_match(event, match=None): |
296 | if match is None: | |
297 | return True | |
298 | ||
299 | for key in match: | |
300 | if key in event: | |
301 | if isinstance(event[key], dict): | |
302 | if not event_match(event[key], match[key]): | |
303 | return False | |
304 | elif event[key] != match[key]: | |
305 | return False | |
306 | else: | |
307 | return False | |
308 | ||
309 | return True | |
310 | ||
66613974 DB |
311 | # Search cached events |
312 | for event in self._events: | |
313 | if (event['event'] == name) and event_match(event, match): | |
314 | self._events.remove(event) | |
315 | return event | |
316 | ||
317 | # Poll for new events | |
318 | while True: | |
319 | event = self._qmp.pull_event(wait=timeout) | |
320 | if (event['event'] == name) and event_match(event, match): | |
321 | return event | |
322 | self._events.append(event) | |
323 | ||
324 | return None | |
325 | ||
326 | def get_log(self): | |
2d853c70 LD |
327 | ''' |
328 | After self.shutdown or failed qemu execution, this returns the output | |
329 | of the qemu process. | |
330 | ''' | |
66613974 | 331 | return self._iolog |