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