]>
Commit | Line | Data |
---|---|---|
f345cfd0 SH |
1 | # Common utilities and Python wrappers for qemu-iotests |
2 | # | |
3 | # Copyright (C) 2012 IBM Corp. | |
4 | # | |
5 | # This program is free software; you can redistribute it and/or modify | |
6 | # it under the terms of the GNU General Public License as published by | |
7 | # the Free Software Foundation; either version 2 of the License, or | |
8 | # (at your option) any later version. | |
9 | # | |
10 | # This program is distributed in the hope that it will be useful, | |
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
13 | # GNU General Public License for more details. | |
14 | # | |
15 | # You should have received a copy of the GNU General Public License | |
16 | # along with this program. If not, see <http://www.gnu.org/licenses/>. | |
17 | # | |
18 | ||
19 | import os | |
20 | import re | |
21 | import subprocess | |
4f450568 | 22 | import string |
f345cfd0 | 23 | import unittest |
ed338bb0 FZ |
24 | import sys |
25 | sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts')) | |
26 | sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'qmp')) | |
f345cfd0 | 27 | import qmp |
ed338bb0 | 28 | import qtest |
2499a096 | 29 | import struct |
f345cfd0 SH |
30 | |
31 | __all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io', | |
32 | 'VM', 'QMPTestCase', 'notrun', 'main'] | |
33 | ||
34 | # This will not work if arguments or path contain spaces but is necessary if we | |
35 | # want to support the override options that ./check supports. | |
c68b039a PB |
36 | qemu_img_args = os.environ.get('QEMU_IMG', 'qemu-img').strip().split(' ') |
37 | qemu_io_args = os.environ.get('QEMU_IO', 'qemu-io').strip().split(' ') | |
38 | qemu_args = os.environ.get('QEMU', 'qemu').strip().split(' ') | |
f345cfd0 SH |
39 | |
40 | imgfmt = os.environ.get('IMGFMT', 'raw') | |
41 | imgproto = os.environ.get('IMGPROTO', 'file') | |
42 | test_dir = os.environ.get('TEST_DIR', '/var/tmp') | |
e8f8624d | 43 | output_dir = os.environ.get('OUTPUT_DIR', '.') |
58cc2ae1 | 44 | cachemode = os.environ.get('CACHEMODE') |
f345cfd0 | 45 | |
30b005d9 WX |
46 | socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper') |
47 | ||
f345cfd0 SH |
48 | def qemu_img(*args): |
49 | '''Run qemu-img and return the exit code''' | |
50 | devnull = open('/dev/null', 'r+') | |
51 | return subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull) | |
52 | ||
d2ef210c | 53 | def qemu_img_verbose(*args): |
993d46ce | 54 | '''Run qemu-img without suppressing its output and return the exit code''' |
d2ef210c KW |
55 | return subprocess.call(qemu_img_args + list(args)) |
56 | ||
3677e6f6 HR |
57 | def qemu_img_pipe(*args): |
58 | '''Run qemu-img and return its output''' | |
59 | return subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE).communicate()[0] | |
60 | ||
f345cfd0 SH |
61 | def qemu_io(*args): |
62 | '''Run qemu-io and return the stdout data''' | |
63 | args = qemu_io_args + list(args) | |
64 | return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0] | |
65 | ||
3a3918c3 SH |
66 | def compare_images(img1, img2): |
67 | '''Return True if two image files are identical''' | |
68 | return qemu_img('compare', '-f', imgfmt, | |
69 | '-F', imgfmt, img1, img2) == 0 | |
70 | ||
2499a096 SH |
71 | def create_image(name, size): |
72 | '''Create a fully-allocated raw image with sector markers''' | |
73 | file = open(name, 'w') | |
74 | i = 0 | |
75 | while i < size: | |
76 | sector = struct.pack('>l504xl', i / 512, i / 512) | |
77 | file.write(sector) | |
78 | i = i + 512 | |
79 | file.close() | |
80 | ||
f345cfd0 SH |
81 | class VM(object): |
82 | '''A QEMU VM''' | |
83 | ||
84 | def __init__(self): | |
85 | self._monitor_path = os.path.join(test_dir, 'qemu-mon.%d' % os.getpid()) | |
86 | self._qemu_log_path = os.path.join(test_dir, 'qemu-log.%d' % os.getpid()) | |
ed338bb0 | 87 | self._qtest_path = os.path.join(test_dir, 'qemu-qtest.%d' % os.getpid()) |
f345cfd0 SH |
88 | self._args = qemu_args + ['-chardev', |
89 | 'socket,id=mon,path=' + self._monitor_path, | |
0fd05e8d | 90 | '-mon', 'chardev=mon,mode=control', |
ed338bb0 FZ |
91 | '-qtest', 'unix:path=' + self._qtest_path, |
92 | '-machine', 'accel=qtest', | |
0fd05e8d | 93 | '-display', 'none', '-vga', 'none'] |
f345cfd0 SH |
94 | self._num_drives = 0 |
95 | ||
30b005d9 WX |
96 | # This can be used to add an unused monitor instance. |
97 | def add_monitor_telnet(self, ip, port): | |
98 | args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port) | |
99 | self._args.append('-monitor') | |
100 | self._args.append(args) | |
101 | ||
f345cfd0 SH |
102 | def add_drive(self, path, opts=''): |
103 | '''Add a virtio-blk drive to the VM''' | |
104 | options = ['if=virtio', | |
105 | 'format=%s' % imgfmt, | |
58cc2ae1 | 106 | 'cache=%s' % cachemode, |
f345cfd0 SH |
107 | 'file=%s' % path, |
108 | 'id=drive%d' % self._num_drives] | |
109 | if opts: | |
110 | options.append(opts) | |
111 | ||
112 | self._args.append('-drive') | |
113 | self._args.append(','.join(options)) | |
114 | self._num_drives += 1 | |
115 | return self | |
116 | ||
3cf53c77 FZ |
117 | def pause_drive(self, drive, event=None): |
118 | '''Pause drive r/w operations''' | |
119 | if not event: | |
120 | self.pause_drive(drive, "read_aio") | |
121 | self.pause_drive(drive, "write_aio") | |
122 | return | |
123 | self.qmp('human-monitor-command', | |
124 | command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive)) | |
125 | ||
126 | def resume_drive(self, drive): | |
127 | self.qmp('human-monitor-command', | |
128 | command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive)) | |
129 | ||
e3409362 IM |
130 | def hmp_qemu_io(self, drive, cmd): |
131 | '''Write to a given drive using an HMP command''' | |
132 | return self.qmp('human-monitor-command', | |
133 | command_line='qemu-io %s "%s"' % (drive, cmd)) | |
134 | ||
23e956bf CB |
135 | def add_fd(self, fd, fdset, opaque, opts=''): |
136 | '''Pass a file descriptor to the VM''' | |
137 | options = ['fd=%d' % fd, | |
138 | 'set=%d' % fdset, | |
139 | 'opaque=%s' % opaque] | |
140 | if opts: | |
141 | options.append(opts) | |
142 | ||
143 | self._args.append('-add-fd') | |
144 | self._args.append(','.join(options)) | |
145 | return self | |
146 | ||
30b005d9 WX |
147 | def send_fd_scm(self, fd_file_path): |
148 | # In iotest.py, the qmp should always use unix socket. | |
149 | assert self._qmp.is_scm_available() | |
150 | bin = socket_scm_helper | |
151 | if os.path.exists(bin) == False: | |
152 | print "Scm help program does not present, path '%s'." % bin | |
153 | return -1 | |
154 | fd_param = ["%s" % bin, | |
155 | "%d" % self._qmp.get_sock_fd(), | |
156 | "%s" % fd_file_path] | |
157 | devnull = open('/dev/null', 'rb') | |
158 | p = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout, | |
159 | stderr=sys.stderr) | |
160 | return p.wait() | |
161 | ||
f345cfd0 SH |
162 | def launch(self): |
163 | '''Launch the VM and establish a QMP connection''' | |
164 | devnull = open('/dev/null', 'rb') | |
165 | qemulog = open(self._qemu_log_path, 'wb') | |
166 | try: | |
167 | self._qmp = qmp.QEMUMonitorProtocol(self._monitor_path, server=True) | |
ed338bb0 | 168 | self._qtest = qtest.QEMUQtestProtocol(self._qtest_path, server=True) |
f345cfd0 SH |
169 | self._popen = subprocess.Popen(self._args, stdin=devnull, stdout=qemulog, |
170 | stderr=subprocess.STDOUT) | |
171 | self._qmp.accept() | |
ed338bb0 | 172 | self._qtest.accept() |
f345cfd0 SH |
173 | except: |
174 | os.remove(self._monitor_path) | |
175 | raise | |
176 | ||
177 | def shutdown(self): | |
178 | '''Terminate the VM and clean up''' | |
863a5d04 PB |
179 | if not self._popen is None: |
180 | self._qmp.cmd('quit') | |
181 | self._popen.wait() | |
182 | os.remove(self._monitor_path) | |
ed338bb0 | 183 | os.remove(self._qtest_path) |
863a5d04 PB |
184 | os.remove(self._qemu_log_path) |
185 | self._popen = None | |
f345cfd0 | 186 | |
4f450568 | 187 | underscore_to_dash = string.maketrans('_', '-') |
df89d112 | 188 | def qmp(self, cmd, conv_keys=True, **args): |
f345cfd0 | 189 | '''Invoke a QMP command and return the result dict''' |
4f450568 PB |
190 | qmp_args = dict() |
191 | for k in args.keys(): | |
df89d112 FZ |
192 | if conv_keys: |
193 | qmp_args[k.translate(self.underscore_to_dash)] = args[k] | |
194 | else: | |
195 | qmp_args[k] = args[k] | |
4f450568 PB |
196 | |
197 | return self._qmp.cmd(cmd, args=qmp_args) | |
f345cfd0 | 198 | |
ed338bb0 FZ |
199 | def qtest(self, cmd): |
200 | '''Send a qtest command to guest''' | |
201 | return self._qtest.cmd(cmd) | |
202 | ||
9dfa9f59 PB |
203 | def get_qmp_event(self, wait=False): |
204 | '''Poll for one queued QMP events and return it''' | |
205 | return self._qmp.pull_event(wait=wait) | |
206 | ||
f345cfd0 SH |
207 | def get_qmp_events(self, wait=False): |
208 | '''Poll for queued QMP events and return a list of dicts''' | |
209 | events = self._qmp.get_events(wait=wait) | |
210 | self._qmp.clear_events() | |
211 | return events | |
212 | ||
213 | index_re = re.compile(r'([^\[]+)\[([^\]]+)\]') | |
214 | ||
215 | class QMPTestCase(unittest.TestCase): | |
216 | '''Abstract base class for QMP test cases''' | |
217 | ||
218 | def dictpath(self, d, path): | |
219 | '''Traverse a path in a nested dict''' | |
220 | for component in path.split('/'): | |
221 | m = index_re.match(component) | |
222 | if m: | |
223 | component, idx = m.groups() | |
224 | idx = int(idx) | |
225 | ||
226 | if not isinstance(d, dict) or component not in d: | |
227 | self.fail('failed path traversal for "%s" in "%s"' % (path, str(d))) | |
228 | d = d[component] | |
229 | ||
230 | if m: | |
231 | if not isinstance(d, list): | |
232 | self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d))) | |
233 | try: | |
234 | d = d[idx] | |
235 | except IndexError: | |
236 | self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d))) | |
237 | return d | |
238 | ||
90f0b711 PB |
239 | def assert_qmp_absent(self, d, path): |
240 | try: | |
241 | result = self.dictpath(d, path) | |
242 | except AssertionError: | |
243 | return | |
244 | self.fail('path "%s" has value "%s"' % (path, str(result))) | |
245 | ||
f345cfd0 SH |
246 | def assert_qmp(self, d, path, value): |
247 | '''Assert that the value for a specific path in a QMP dict matches''' | |
248 | result = self.dictpath(d, path) | |
249 | self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value))) | |
250 | ||
ecc1c88e SH |
251 | def assert_no_active_block_jobs(self): |
252 | result = self.vm.qmp('query-block-jobs') | |
253 | self.assert_qmp(result, 'return', []) | |
254 | ||
3cf53c77 | 255 | def cancel_and_wait(self, drive='drive0', force=False, resume=False): |
2575fe16 SH |
256 | '''Cancel a block job and wait for it to finish, returning the event''' |
257 | result = self.vm.qmp('block-job-cancel', device=drive, force=force) | |
258 | self.assert_qmp(result, 'return', {}) | |
259 | ||
3cf53c77 FZ |
260 | if resume: |
261 | self.vm.resume_drive(drive) | |
262 | ||
2575fe16 SH |
263 | cancelled = False |
264 | result = None | |
265 | while not cancelled: | |
266 | for event in self.vm.get_qmp_events(wait=True): | |
267 | if event['event'] == 'BLOCK_JOB_COMPLETED' or \ | |
268 | event['event'] == 'BLOCK_JOB_CANCELLED': | |
269 | self.assert_qmp(event, 'data/device', drive) | |
270 | result = event | |
271 | cancelled = True | |
272 | ||
273 | self.assert_no_active_block_jobs() | |
274 | return result | |
275 | ||
9974ad40 | 276 | def wait_until_completed(self, drive='drive0', check_offset=True): |
0dbe8a1b SH |
277 | '''Wait for a block job to finish, returning the event''' |
278 | completed = False | |
279 | while not completed: | |
280 | for event in self.vm.get_qmp_events(wait=True): | |
281 | if event['event'] == 'BLOCK_JOB_COMPLETED': | |
282 | self.assert_qmp(event, 'data/device', drive) | |
283 | self.assert_qmp_absent(event, 'data/error') | |
9974ad40 | 284 | if check_offset: |
1d3ba15a | 285 | self.assert_qmp(event, 'data/offset', event['data']['len']) |
0dbe8a1b SH |
286 | completed = True |
287 | ||
288 | self.assert_no_active_block_jobs() | |
289 | return event | |
290 | ||
f345cfd0 SH |
291 | def notrun(reason): |
292 | '''Skip this test suite''' | |
293 | # Each test in qemu-iotests has a number ("seq") | |
294 | seq = os.path.basename(sys.argv[0]) | |
295 | ||
e8f8624d | 296 | open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n') |
f345cfd0 SH |
297 | print '%s not run: %s' % (seq, reason) |
298 | sys.exit(0) | |
299 | ||
bc521696 | 300 | def main(supported_fmts=[], supported_oses=['linux']): |
f345cfd0 SH |
301 | '''Run tests''' |
302 | ||
303 | if supported_fmts and (imgfmt not in supported_fmts): | |
304 | notrun('not suitable for this image format: %s' % imgfmt) | |
305 | ||
79e7a019 | 306 | if True not in [sys.platform.startswith(x) for x in supported_oses]: |
bc521696 FZ |
307 | notrun('not suitable for this OS: %s' % sys.platform) |
308 | ||
f345cfd0 SH |
309 | # We need to filter out the time taken from the output so that qemu-iotest |
310 | # can reliably diff the results against master output. | |
311 | import StringIO | |
312 | output = StringIO.StringIO() | |
313 | ||
314 | class MyTestRunner(unittest.TextTestRunner): | |
315 | def __init__(self, stream=output, descriptions=True, verbosity=1): | |
316 | unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) | |
317 | ||
318 | # unittest.main() will use sys.exit() so expect a SystemExit exception | |
319 | try: | |
320 | unittest.main(testRunner=MyTestRunner) | |
321 | finally: | |
d2ef210c | 322 | sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue())) |