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