]>
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 | ||
c1c71e49 | 19 | import errno |
f345cfd0 SH |
20 | import os |
21 | import re | |
22 | import subprocess | |
4f450568 | 23 | import string |
f345cfd0 | 24 | import unittest |
ed338bb0 FZ |
25 | import sys |
26 | sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts')) | |
ed338bb0 | 27 | import qtest |
2499a096 | 28 | import struct |
74f69050 | 29 | import json |
2c93c5cb | 30 | import signal |
f345cfd0 | 31 | |
f345cfd0 | 32 | |
934659c4 | 33 | # This will not work if arguments contain spaces but is necessary if we |
f345cfd0 | 34 | # want to support the override options that ./check supports. |
934659c4 HR |
35 | qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')] |
36 | if os.environ.get('QEMU_IMG_OPTIONS'): | |
37 | qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ') | |
38 | ||
39 | qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')] | |
40 | if os.environ.get('QEMU_IO_OPTIONS'): | |
41 | qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ') | |
42 | ||
bec87774 HR |
43 | qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')] |
44 | if os.environ.get('QEMU_NBD_OPTIONS'): | |
45 | qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ') | |
46 | ||
4c44b4a4 | 47 | qemu_prog = os.environ.get('QEMU_PROG', 'qemu') |
66613974 | 48 | qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ') |
f345cfd0 SH |
49 | |
50 | imgfmt = os.environ.get('IMGFMT', 'raw') | |
51 | imgproto = os.environ.get('IMGPROTO', 'file') | |
5a8fabf3 | 52 | test_dir = os.environ.get('TEST_DIR') |
e8f8624d | 53 | output_dir = os.environ.get('OUTPUT_DIR', '.') |
58cc2ae1 | 54 | cachemode = os.environ.get('CACHEMODE') |
e166b414 | 55 | qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE') |
f345cfd0 | 56 | |
30b005d9 | 57 | socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper') |
c0088d79 | 58 | debug = False |
30b005d9 | 59 | |
f345cfd0 SH |
60 | def qemu_img(*args): |
61 | '''Run qemu-img and return the exit code''' | |
62 | devnull = open('/dev/null', 'r+') | |
2ef6093c HR |
63 | exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull) |
64 | if exitcode < 0: | |
65 | sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) | |
66 | return exitcode | |
f345cfd0 | 67 | |
d2ef210c | 68 | def qemu_img_verbose(*args): |
993d46ce | 69 | '''Run qemu-img without suppressing its output and return the exit code''' |
2ef6093c HR |
70 | exitcode = subprocess.call(qemu_img_args + list(args)) |
71 | if exitcode < 0: | |
72 | sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) | |
73 | return exitcode | |
d2ef210c | 74 | |
3677e6f6 HR |
75 | def qemu_img_pipe(*args): |
76 | '''Run qemu-img and return its output''' | |
491e5e85 DB |
77 | subp = subprocess.Popen(qemu_img_args + list(args), |
78 | stdout=subprocess.PIPE, | |
79 | stderr=subprocess.STDOUT) | |
2ef6093c HR |
80 | exitcode = subp.wait() |
81 | if exitcode < 0: | |
82 | sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) | |
83 | return subp.communicate()[0] | |
3677e6f6 | 84 | |
f345cfd0 SH |
85 | def qemu_io(*args): |
86 | '''Run qemu-io and return the stdout data''' | |
87 | args = qemu_io_args + list(args) | |
491e5e85 DB |
88 | subp = subprocess.Popen(args, stdout=subprocess.PIPE, |
89 | stderr=subprocess.STDOUT) | |
2ef6093c HR |
90 | exitcode = subp.wait() |
91 | if exitcode < 0: | |
92 | sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args))) | |
93 | return subp.communicate()[0] | |
f345cfd0 | 94 | |
bec87774 HR |
95 | def qemu_nbd(*args): |
96 | '''Run qemu-nbd in daemon mode and return the parent's exit code''' | |
97 | return subprocess.call(qemu_nbd_args + ['--fork'] + list(args)) | |
98 | ||
e1b5c51f | 99 | def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt): |
3a3918c3 | 100 | '''Return True if two image files are identical''' |
e1b5c51f PB |
101 | return qemu_img('compare', '-f', fmt1, |
102 | '-F', fmt2, img1, img2) == 0 | |
3a3918c3 | 103 | |
2499a096 SH |
104 | def create_image(name, size): |
105 | '''Create a fully-allocated raw image with sector markers''' | |
106 | file = open(name, 'w') | |
107 | i = 0 | |
108 | while i < size: | |
109 | sector = struct.pack('>l504xl', i / 512, i / 512) | |
110 | file.write(sector) | |
111 | i = i + 512 | |
112 | file.close() | |
113 | ||
74f69050 FZ |
114 | def image_size(img): |
115 | '''Return image's virtual size''' | |
116 | r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img) | |
117 | return json.loads(r)['virtual-size'] | |
118 | ||
a2d1c8fd DB |
119 | test_dir_re = re.compile(r"%s" % test_dir) |
120 | def filter_test_dir(msg): | |
121 | return test_dir_re.sub("TEST_DIR", msg) | |
122 | ||
123 | win32_re = re.compile(r"\r") | |
124 | def filter_win32(msg): | |
125 | return win32_re.sub("", msg) | |
126 | ||
127 | qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)") | |
128 | def filter_qemu_io(msg): | |
129 | msg = filter_win32(msg) | |
130 | return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg) | |
131 | ||
132 | chown_re = re.compile(r"chown [0-9]+:[0-9]+") | |
133 | def filter_chown(msg): | |
134 | return chown_re.sub("chown UID:GID", msg) | |
135 | ||
136 | def log(msg, filters=[]): | |
137 | for flt in filters: | |
138 | msg = flt(msg) | |
139 | print msg | |
140 | ||
2c93c5cb KW |
141 | class Timeout: |
142 | def __init__(self, seconds, errmsg = "Timeout"): | |
143 | self.seconds = seconds | |
144 | self.errmsg = errmsg | |
145 | def __enter__(self): | |
146 | signal.signal(signal.SIGALRM, self.timeout) | |
147 | signal.setitimer(signal.ITIMER_REAL, self.seconds) | |
148 | return self | |
149 | def __exit__(self, type, value, traceback): | |
150 | signal.setitimer(signal.ITIMER_REAL, 0) | |
151 | return False | |
152 | def timeout(self, signum, frame): | |
153 | raise Exception(self.errmsg) | |
154 | ||
4c44b4a4 | 155 | class VM(qtest.QEMUQtestMachine): |
f345cfd0 SH |
156 | '''A QEMU VM''' |
157 | ||
5fcbdf50 HR |
158 | def __init__(self, path_suffix=''): |
159 | name = "qemu%s-%d" % (path_suffix, os.getpid()) | |
160 | super(VM, self).__init__(qemu_prog, qemu_opts, name=name, | |
161 | test_dir=test_dir, | |
4c44b4a4 | 162 | socket_scm_helper=socket_scm_helper) |
c0088d79 KW |
163 | if debug: |
164 | self._debug = True | |
f345cfd0 | 165 | self._num_drives = 0 |
30b005d9 | 166 | |
486b88bd KW |
167 | def add_device(self, opts): |
168 | self._args.append('-device') | |
169 | self._args.append(opts) | |
170 | return self | |
171 | ||
78b666f4 FZ |
172 | def add_drive_raw(self, opts): |
173 | self._args.append('-drive') | |
174 | self._args.append(opts) | |
175 | return self | |
176 | ||
e1b5c51f | 177 | def add_drive(self, path, opts='', interface='virtio', format=imgfmt): |
f345cfd0 | 178 | '''Add a virtio-blk drive to the VM''' |
8e492253 | 179 | options = ['if=%s' % interface, |
f345cfd0 | 180 | 'id=drive%d' % self._num_drives] |
8e492253 HR |
181 | |
182 | if path is not None: | |
183 | options.append('file=%s' % path) | |
e1b5c51f | 184 | options.append('format=%s' % format) |
fc17c259 | 185 | options.append('cache=%s' % cachemode) |
8e492253 | 186 | |
f345cfd0 SH |
187 | if opts: |
188 | options.append(opts) | |
189 | ||
190 | self._args.append('-drive') | |
191 | self._args.append(','.join(options)) | |
192 | self._num_drives += 1 | |
193 | return self | |
194 | ||
5694923a HR |
195 | def add_blockdev(self, opts): |
196 | self._args.append('-blockdev') | |
197 | if isinstance(opts, str): | |
198 | self._args.append(opts) | |
199 | else: | |
200 | self._args.append(','.join(opts)) | |
201 | return self | |
202 | ||
3cf53c77 FZ |
203 | def pause_drive(self, drive, event=None): |
204 | '''Pause drive r/w operations''' | |
205 | if not event: | |
206 | self.pause_drive(drive, "read_aio") | |
207 | self.pause_drive(drive, "write_aio") | |
208 | return | |
209 | self.qmp('human-monitor-command', | |
210 | command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive)) | |
211 | ||
212 | def resume_drive(self, drive): | |
213 | self.qmp('human-monitor-command', | |
214 | command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive)) | |
215 | ||
e3409362 IM |
216 | def hmp_qemu_io(self, drive, cmd): |
217 | '''Write to a given drive using an HMP command''' | |
218 | return self.qmp('human-monitor-command', | |
219 | command_line='qemu-io %s "%s"' % (drive, cmd)) | |
220 | ||
7898f74e | 221 | |
f345cfd0 SH |
222 | index_re = re.compile(r'([^\[]+)\[([^\]]+)\]') |
223 | ||
224 | class QMPTestCase(unittest.TestCase): | |
225 | '''Abstract base class for QMP test cases''' | |
226 | ||
227 | def dictpath(self, d, path): | |
228 | '''Traverse a path in a nested dict''' | |
229 | for component in path.split('/'): | |
230 | m = index_re.match(component) | |
231 | if m: | |
232 | component, idx = m.groups() | |
233 | idx = int(idx) | |
234 | ||
235 | if not isinstance(d, dict) or component not in d: | |
236 | self.fail('failed path traversal for "%s" in "%s"' % (path, str(d))) | |
237 | d = d[component] | |
238 | ||
239 | if m: | |
240 | if not isinstance(d, list): | |
241 | self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d))) | |
242 | try: | |
243 | d = d[idx] | |
244 | except IndexError: | |
245 | self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d))) | |
246 | return d | |
247 | ||
e07375f5 HR |
248 | def flatten_qmp_object(self, obj, output=None, basestr=''): |
249 | if output is None: | |
250 | output = dict() | |
251 | if isinstance(obj, list): | |
252 | for i in range(len(obj)): | |
253 | self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.') | |
254 | elif isinstance(obj, dict): | |
255 | for key in obj: | |
256 | self.flatten_qmp_object(obj[key], output, basestr + key + '.') | |
257 | else: | |
258 | output[basestr[:-1]] = obj # Strip trailing '.' | |
259 | return output | |
260 | ||
5694923a HR |
261 | def qmp_to_opts(self, obj): |
262 | obj = self.flatten_qmp_object(obj) | |
263 | output_list = list() | |
264 | for key in obj: | |
265 | output_list += [key + '=' + obj[key]] | |
266 | return ','.join(output_list) | |
267 | ||
90f0b711 PB |
268 | def assert_qmp_absent(self, d, path): |
269 | try: | |
270 | result = self.dictpath(d, path) | |
271 | except AssertionError: | |
272 | return | |
273 | self.fail('path "%s" has value "%s"' % (path, str(result))) | |
274 | ||
f345cfd0 SH |
275 | def assert_qmp(self, d, path, value): |
276 | '''Assert that the value for a specific path in a QMP dict matches''' | |
277 | result = self.dictpath(d, path) | |
278 | self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value))) | |
279 | ||
ecc1c88e SH |
280 | def assert_no_active_block_jobs(self): |
281 | result = self.vm.qmp('query-block-jobs') | |
282 | self.assert_qmp(result, 'return', []) | |
283 | ||
e71fc0ba FZ |
284 | def assert_has_block_node(self, node_name=None, file_name=None): |
285 | """Issue a query-named-block-nodes and assert node_name and/or | |
286 | file_name is present in the result""" | |
287 | def check_equal_or_none(a, b): | |
288 | return a == None or b == None or a == b | |
289 | assert node_name or file_name | |
290 | result = self.vm.qmp('query-named-block-nodes') | |
291 | for x in result["return"]: | |
292 | if check_equal_or_none(x.get("node-name"), node_name) and \ | |
293 | check_equal_or_none(x.get("file"), file_name): | |
294 | return | |
295 | self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \ | |
296 | (node_name, file_name, result)) | |
297 | ||
e07375f5 HR |
298 | def assert_json_filename_equal(self, json_filename, reference): |
299 | '''Asserts that the given filename is a json: filename and that its | |
300 | content is equal to the given reference object''' | |
301 | self.assertEqual(json_filename[:5], 'json:') | |
302 | self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])), | |
303 | self.flatten_qmp_object(reference)) | |
304 | ||
3cf53c77 | 305 | def cancel_and_wait(self, drive='drive0', force=False, resume=False): |
2575fe16 SH |
306 | '''Cancel a block job and wait for it to finish, returning the event''' |
307 | result = self.vm.qmp('block-job-cancel', device=drive, force=force) | |
308 | self.assert_qmp(result, 'return', {}) | |
309 | ||
3cf53c77 FZ |
310 | if resume: |
311 | self.vm.resume_drive(drive) | |
312 | ||
2575fe16 SH |
313 | cancelled = False |
314 | result = None | |
315 | while not cancelled: | |
316 | for event in self.vm.get_qmp_events(wait=True): | |
317 | if event['event'] == 'BLOCK_JOB_COMPLETED' or \ | |
318 | event['event'] == 'BLOCK_JOB_CANCELLED': | |
319 | self.assert_qmp(event, 'data/device', drive) | |
320 | result = event | |
321 | cancelled = True | |
322 | ||
323 | self.assert_no_active_block_jobs() | |
324 | return result | |
325 | ||
9974ad40 | 326 | def wait_until_completed(self, drive='drive0', check_offset=True): |
0dbe8a1b SH |
327 | '''Wait for a block job to finish, returning the event''' |
328 | completed = False | |
329 | while not completed: | |
330 | for event in self.vm.get_qmp_events(wait=True): | |
331 | if event['event'] == 'BLOCK_JOB_COMPLETED': | |
332 | self.assert_qmp(event, 'data/device', drive) | |
333 | self.assert_qmp_absent(event, 'data/error') | |
9974ad40 | 334 | if check_offset: |
1d3ba15a | 335 | self.assert_qmp(event, 'data/offset', event['data']['len']) |
0dbe8a1b SH |
336 | completed = True |
337 | ||
338 | self.assert_no_active_block_jobs() | |
339 | return event | |
340 | ||
866323f3 FZ |
341 | def wait_ready(self, drive='drive0'): |
342 | '''Wait until a block job BLOCK_JOB_READY event''' | |
d7b25297 FZ |
343 | f = {'data': {'type': 'mirror', 'device': drive } } |
344 | event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f) | |
866323f3 FZ |
345 | |
346 | def wait_ready_and_cancel(self, drive='drive0'): | |
347 | self.wait_ready(drive=drive) | |
348 | event = self.cancel_and_wait(drive=drive) | |
349 | self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED') | |
350 | self.assert_qmp(event, 'data/type', 'mirror') | |
351 | self.assert_qmp(event, 'data/offset', event['data']['len']) | |
352 | ||
353 | def complete_and_wait(self, drive='drive0', wait_ready=True): | |
354 | '''Complete a block job and wait for it to finish''' | |
355 | if wait_ready: | |
356 | self.wait_ready(drive=drive) | |
357 | ||
358 | result = self.vm.qmp('block-job-complete', device=drive) | |
359 | self.assert_qmp(result, 'return', {}) | |
360 | ||
361 | event = self.wait_until_completed(drive=drive) | |
362 | self.assert_qmp(event, 'data/type', 'mirror') | |
363 | ||
2c93c5cb KW |
364 | def pause_job(self, job_id='job0'): |
365 | result = self.vm.qmp('block-job-pause', device=job_id) | |
366 | self.assert_qmp(result, 'return', {}) | |
367 | ||
368 | with Timeout(1, "Timeout waiting for job to pause"): | |
369 | while True: | |
370 | result = self.vm.qmp('query-block-jobs') | |
371 | for job in result['return']: | |
372 | if job['device'] == job_id and job['paused'] == True and job['busy'] == False: | |
373 | return job | |
374 | ||
375 | ||
f345cfd0 SH |
376 | def notrun(reason): |
377 | '''Skip this test suite''' | |
378 | # Each test in qemu-iotests has a number ("seq") | |
379 | seq = os.path.basename(sys.argv[0]) | |
380 | ||
e8f8624d | 381 | open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n') |
f345cfd0 SH |
382 | print '%s not run: %s' % (seq, reason) |
383 | sys.exit(0) | |
384 | ||
c6a92369 | 385 | def verify_image_format(supported_fmts=[]): |
f345cfd0 SH |
386 | if supported_fmts and (imgfmt not in supported_fmts): |
387 | notrun('not suitable for this image format: %s' % imgfmt) | |
388 | ||
c6a92369 | 389 | def verify_platform(supported_oses=['linux']): |
79e7a019 | 390 | if True not in [sys.platform.startswith(x) for x in supported_oses]: |
bc521696 FZ |
391 | notrun('not suitable for this OS: %s' % sys.platform) |
392 | ||
b0f90495 AG |
393 | def supports_quorum(): |
394 | return 'quorum' in qemu_img_pipe('--help') | |
395 | ||
3f647b51 SS |
396 | def verify_quorum(): |
397 | '''Skip test suite if quorum support is not available''' | |
b0f90495 | 398 | if not supports_quorum(): |
3f647b51 SS |
399 | notrun('quorum support missing') |
400 | ||
c6a92369 DB |
401 | def main(supported_fmts=[], supported_oses=['linux']): |
402 | '''Run tests''' | |
403 | ||
c0088d79 KW |
404 | global debug |
405 | ||
5a8fabf3 SS |
406 | # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to |
407 | # indicate that we're not being run via "check". There may be | |
408 | # other things set up by "check" that individual test cases rely | |
409 | # on. | |
410 | if test_dir is None or qemu_default_machine is None: | |
411 | sys.stderr.write('Please run this test via the "check" script\n') | |
412 | sys.exit(os.EX_USAGE) | |
413 | ||
c6a92369 DB |
414 | debug = '-d' in sys.argv |
415 | verbosity = 1 | |
416 | verify_image_format(supported_fmts) | |
417 | verify_platform(supported_oses) | |
418 | ||
f345cfd0 SH |
419 | # We need to filter out the time taken from the output so that qemu-iotest |
420 | # can reliably diff the results against master output. | |
421 | import StringIO | |
aa4f592a FZ |
422 | if debug: |
423 | output = sys.stdout | |
424 | verbosity = 2 | |
425 | sys.argv.remove('-d') | |
426 | else: | |
427 | output = StringIO.StringIO() | |
f345cfd0 SH |
428 | |
429 | class MyTestRunner(unittest.TextTestRunner): | |
aa4f592a | 430 | def __init__(self, stream=output, descriptions=True, verbosity=verbosity): |
f345cfd0 SH |
431 | unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) |
432 | ||
433 | # unittest.main() will use sys.exit() so expect a SystemExit exception | |
434 | try: | |
435 | unittest.main(testRunner=MyTestRunner) | |
436 | finally: | |
aa4f592a FZ |
437 | if not debug: |
438 | sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue())) |