xref: /qemu/tests/qemu-iotests/iotests.py (revision 2c533c54)
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
19import errno
20import os
21import re
22import subprocess
23import string
24import unittest
25import sys
26sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
27import qtest
28import struct
29import json
30
31
32# This will not work if arguments contain spaces but is necessary if we
33# want to support the override options that ./check supports.
34qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
35if os.environ.get('QEMU_IMG_OPTIONS'):
36    qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
37
38qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
39if os.environ.get('QEMU_IO_OPTIONS'):
40    qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
41
42qemu_prog = [os.environ.get('QEMU_PROG', 'qemu')]
43qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
44
45imgfmt = os.environ.get('IMGFMT', 'raw')
46imgproto = os.environ.get('IMGPROTO', 'file')
47test_dir = os.environ.get('TEST_DIR')
48output_dir = os.environ.get('OUTPUT_DIR', '.')
49cachemode = os.environ.get('CACHEMODE')
50qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
51
52socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
53
54def qemu_img(*args):
55    '''Run qemu-img and return the exit code'''
56    devnull = open('/dev/null', 'r+')
57    exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
58    if exitcode < 0:
59        sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
60    return exitcode
61
62def qemu_img_verbose(*args):
63    '''Run qemu-img without suppressing its output and return the exit code'''
64    exitcode = subprocess.call(qemu_img_args + list(args))
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
69def qemu_img_pipe(*args):
70    '''Run qemu-img and return its output'''
71    subp = subprocess.Popen(qemu_img_args + list(args),
72                            stdout=subprocess.PIPE,
73                            stderr=subprocess.STDOUT)
74    exitcode = subp.wait()
75    if exitcode < 0:
76        sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
77    return subp.communicate()[0]
78
79def qemu_io(*args):
80    '''Run qemu-io and return the stdout data'''
81    args = qemu_io_args + list(args)
82    subp = subprocess.Popen(args, stdout=subprocess.PIPE,
83                            stderr=subprocess.STDOUT)
84    exitcode = subp.wait()
85    if exitcode < 0:
86        sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
87    return subp.communicate()[0]
88
89def compare_images(img1, img2):
90    '''Return True if two image files are identical'''
91    return qemu_img('compare', '-f', imgfmt,
92                    '-F', imgfmt, img1, img2) == 0
93
94def create_image(name, size):
95    '''Create a fully-allocated raw image with sector markers'''
96    file = open(name, 'w')
97    i = 0
98    while i < size:
99        sector = struct.pack('>l504xl', i / 512, i / 512)
100        file.write(sector)
101        i = i + 512
102    file.close()
103
104def image_size(img):
105    '''Return image's virtual size'''
106    r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img)
107    return json.loads(r)['virtual-size']
108
109test_dir_re = re.compile(r"%s" % test_dir)
110def filter_test_dir(msg):
111    return test_dir_re.sub("TEST_DIR", msg)
112
113win32_re = re.compile(r"\r")
114def filter_win32(msg):
115    return win32_re.sub("", msg)
116
117qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
118def filter_qemu_io(msg):
119    msg = filter_win32(msg)
120    return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
121
122chown_re = re.compile(r"chown [0-9]+:[0-9]+")
123def filter_chown(msg):
124    return chown_re.sub("chown UID:GID", msg)
125
126def log(msg, filters=[]):
127    for flt in filters:
128        msg = flt(msg)
129    print msg
130
131# Test if 'match' is a recursive subset of 'event'
132def event_match(event, match=None):
133    if match is None:
134        return True
135
136    for key in match:
137        if key in event:
138            if isinstance(event[key], dict):
139                if not event_match(event[key], match[key]):
140                    return False
141            elif event[key] != match[key]:
142                return False
143        else:
144            return False
145
146    return True
147
148class VM(qtest.QEMUMachine):
149    '''A QEMU VM'''
150
151    def __init__(self):
152        super(self, VM).__init__(qemu_prog, qemu_opts, test_dir)
153        self._num_drives = 0
154
155    def add_drive_raw(self, opts):
156        self._args.append('-drive')
157        self._args.append(opts)
158        return self
159
160    def add_drive(self, path, opts='', interface='virtio'):
161        '''Add a virtio-blk drive to the VM'''
162        options = ['if=%s' % interface,
163                   'id=drive%d' % self._num_drives]
164
165        if path is not None:
166            options.append('file=%s' % path)
167            options.append('format=%s' % imgfmt)
168            options.append('cache=%s' % cachemode)
169
170        if opts:
171            options.append(opts)
172
173        self._args.append('-drive')
174        self._args.append(','.join(options))
175        self._num_drives += 1
176        return self
177
178    def pause_drive(self, drive, event=None):
179        '''Pause drive r/w operations'''
180        if not event:
181            self.pause_drive(drive, "read_aio")
182            self.pause_drive(drive, "write_aio")
183            return
184        self.qmp('human-monitor-command',
185                    command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
186
187    def resume_drive(self, drive):
188        self.qmp('human-monitor-command',
189                    command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
190
191    def hmp_qemu_io(self, drive, cmd):
192        '''Write to a given drive using an HMP command'''
193        return self.qmp('human-monitor-command',
194                        command_line='qemu-io %s "%s"' % (drive, cmd))
195
196
197index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
198
199class QMPTestCase(unittest.TestCase):
200    '''Abstract base class for QMP test cases'''
201
202    def dictpath(self, d, path):
203        '''Traverse a path in a nested dict'''
204        for component in path.split('/'):
205            m = index_re.match(component)
206            if m:
207                component, idx = m.groups()
208                idx = int(idx)
209
210            if not isinstance(d, dict) or component not in d:
211                self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
212            d = d[component]
213
214            if m:
215                if not isinstance(d, list):
216                    self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
217                try:
218                    d = d[idx]
219                except IndexError:
220                    self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
221        return d
222
223    def assert_qmp_absent(self, d, path):
224        try:
225            result = self.dictpath(d, path)
226        except AssertionError:
227            return
228        self.fail('path "%s" has value "%s"' % (path, str(result)))
229
230    def assert_qmp(self, d, path, value):
231        '''Assert that the value for a specific path in a QMP dict matches'''
232        result = self.dictpath(d, path)
233        self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
234
235    def assert_no_active_block_jobs(self):
236        result = self.vm.qmp('query-block-jobs')
237        self.assert_qmp(result, 'return', [])
238
239    def assert_has_block_node(self, node_name=None, file_name=None):
240        """Issue a query-named-block-nodes and assert node_name and/or
241        file_name is present in the result"""
242        def check_equal_or_none(a, b):
243            return a == None or b == None or a == b
244        assert node_name or file_name
245        result = self.vm.qmp('query-named-block-nodes')
246        for x in result["return"]:
247            if check_equal_or_none(x.get("node-name"), node_name) and \
248                    check_equal_or_none(x.get("file"), file_name):
249                return
250        self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
251                (node_name, file_name, result))
252
253    def cancel_and_wait(self, drive='drive0', force=False, resume=False):
254        '''Cancel a block job and wait for it to finish, returning the event'''
255        result = self.vm.qmp('block-job-cancel', device=drive, force=force)
256        self.assert_qmp(result, 'return', {})
257
258        if resume:
259            self.vm.resume_drive(drive)
260
261        cancelled = False
262        result = None
263        while not cancelled:
264            for event in self.vm.get_qmp_events(wait=True):
265                if event['event'] == 'BLOCK_JOB_COMPLETED' or \
266                   event['event'] == 'BLOCK_JOB_CANCELLED':
267                    self.assert_qmp(event, 'data/device', drive)
268                    result = event
269                    cancelled = True
270
271        self.assert_no_active_block_jobs()
272        return result
273
274    def wait_until_completed(self, drive='drive0', check_offset=True):
275        '''Wait for a block job to finish, returning the event'''
276        completed = False
277        while not completed:
278            for event in self.vm.get_qmp_events(wait=True):
279                if event['event'] == 'BLOCK_JOB_COMPLETED':
280                    self.assert_qmp(event, 'data/device', drive)
281                    self.assert_qmp_absent(event, 'data/error')
282                    if check_offset:
283                        self.assert_qmp(event, 'data/offset', event['data']['len'])
284                    completed = True
285
286        self.assert_no_active_block_jobs()
287        return event
288
289    def wait_ready(self, drive='drive0'):
290        '''Wait until a block job BLOCK_JOB_READY event'''
291        f = {'data': {'type': 'mirror', 'device': drive } }
292        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
293
294    def wait_ready_and_cancel(self, drive='drive0'):
295        self.wait_ready(drive=drive)
296        event = self.cancel_and_wait(drive=drive)
297        self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
298        self.assert_qmp(event, 'data/type', 'mirror')
299        self.assert_qmp(event, 'data/offset', event['data']['len'])
300
301    def complete_and_wait(self, drive='drive0', wait_ready=True):
302        '''Complete a block job and wait for it to finish'''
303        if wait_ready:
304            self.wait_ready(drive=drive)
305
306        result = self.vm.qmp('block-job-complete', device=drive)
307        self.assert_qmp(result, 'return', {})
308
309        event = self.wait_until_completed(drive=drive)
310        self.assert_qmp(event, 'data/type', 'mirror')
311
312def notrun(reason):
313    '''Skip this test suite'''
314    # Each test in qemu-iotests has a number ("seq")
315    seq = os.path.basename(sys.argv[0])
316
317    open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
318    print '%s not run: %s' % (seq, reason)
319    sys.exit(0)
320
321def verify_image_format(supported_fmts=[]):
322    if supported_fmts and (imgfmt not in supported_fmts):
323        notrun('not suitable for this image format: %s' % imgfmt)
324
325def verify_platform(supported_oses=['linux']):
326    if True not in [sys.platform.startswith(x) for x in supported_oses]:
327        notrun('not suitable for this OS: %s' % sys.platform)
328
329def verify_quorum():
330    '''Skip test suite if quorum support is not available'''
331    if 'quorum' not in qemu_img_pipe('--help'):
332        notrun('quorum support missing')
333
334def main(supported_fmts=[], supported_oses=['linux']):
335    '''Run tests'''
336
337    # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
338    # indicate that we're not being run via "check". There may be
339    # other things set up by "check" that individual test cases rely
340    # on.
341    if test_dir is None or qemu_default_machine is None:
342        sys.stderr.write('Please run this test via the "check" script\n')
343        sys.exit(os.EX_USAGE)
344
345    debug = '-d' in sys.argv
346    verbosity = 1
347    verify_image_format(supported_fmts)
348    verify_platform(supported_oses)
349
350    # We need to filter out the time taken from the output so that qemu-iotest
351    # can reliably diff the results against master output.
352    import StringIO
353    if debug:
354        output = sys.stdout
355        verbosity = 2
356        sys.argv.remove('-d')
357    else:
358        output = StringIO.StringIO()
359
360    class MyTestRunner(unittest.TextTestRunner):
361        def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
362            unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
363
364    # unittest.main() will use sys.exit() so expect a SystemExit exception
365    try:
366        unittest.main(testRunner=MyTestRunner)
367    finally:
368        if not debug:
369            sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
370