xref: /openbmc/qemu/tests/qemu-iotests/iotests.py (revision 87e0331c)
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
30import signal
31
32
33# This will not work if arguments contain spaces but is necessary if we
34# want to support the override options that ./check supports.
35qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
36if os.environ.get('QEMU_IMG_OPTIONS'):
37    qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
38
39qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
40if os.environ.get('QEMU_IO_OPTIONS'):
41    qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
42
43qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')]
44if os.environ.get('QEMU_NBD_OPTIONS'):
45    qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ')
46
47qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
48qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
49
50imgfmt = os.environ.get('IMGFMT', 'raw')
51imgproto = os.environ.get('IMGPROTO', 'file')
52test_dir = os.environ.get('TEST_DIR')
53output_dir = os.environ.get('OUTPUT_DIR', '.')
54cachemode = os.environ.get('CACHEMODE')
55qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
56
57socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
58debug = False
59
60def qemu_img(*args):
61    '''Run qemu-img and return the exit code'''
62    devnull = open('/dev/null', 'r+')
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
67
68def qemu_img_verbose(*args):
69    '''Run qemu-img without suppressing its output and return the exit code'''
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
74
75def qemu_img_pipe(*args):
76    '''Run qemu-img and return its output'''
77    subp = subprocess.Popen(qemu_img_args + list(args),
78                            stdout=subprocess.PIPE,
79                            stderr=subprocess.STDOUT)
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]
84
85def qemu_io(*args):
86    '''Run qemu-io and return the stdout data'''
87    args = qemu_io_args + list(args)
88    subp = subprocess.Popen(args, stdout=subprocess.PIPE,
89                            stderr=subprocess.STDOUT)
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]
94
95def 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
99def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
100    '''Return True if two image files are identical'''
101    return qemu_img('compare', '-f', fmt1,
102                    '-F', fmt2, img1, img2) == 0
103
104def 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
114def 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
119test_dir_re = re.compile(r"%s" % test_dir)
120def filter_test_dir(msg):
121    return test_dir_re.sub("TEST_DIR", msg)
122
123win32_re = re.compile(r"\r")
124def filter_win32(msg):
125    return win32_re.sub("", msg)
126
127qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
128def 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
132chown_re = re.compile(r"chown [0-9]+:[0-9]+")
133def filter_chown(msg):
134    return chown_re.sub("chown UID:GID", msg)
135
136def log(msg, filters=[]):
137    for flt in filters:
138        msg = flt(msg)
139    print msg
140
141class 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
155class VM(qtest.QEMUQtestMachine):
156    '''A QEMU VM'''
157
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,
162                                 socket_scm_helper=socket_scm_helper)
163        if debug:
164            self._debug = True
165        self._num_drives = 0
166
167    def add_device(self, opts):
168        self._args.append('-device')
169        self._args.append(opts)
170        return self
171
172    def add_drive_raw(self, opts):
173        self._args.append('-drive')
174        self._args.append(opts)
175        return self
176
177    def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
178        '''Add a virtio-blk drive to the VM'''
179        options = ['if=%s' % interface,
180                   'id=drive%d' % self._num_drives]
181
182        if path is not None:
183            options.append('file=%s' % path)
184            options.append('format=%s' % format)
185            options.append('cache=%s' % cachemode)
186
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
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
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
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
221
222index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
223
224class 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
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
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
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
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
280    def assert_no_active_block_jobs(self):
281        result = self.vm.qmp('query-block-jobs')
282        self.assert_qmp(result, 'return', [])
283
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
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
305    def cancel_and_wait(self, drive='drive0', force=False, resume=False):
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
310        if resume:
311            self.vm.resume_drive(drive)
312
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
326    def wait_until_completed(self, drive='drive0', check_offset=True):
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')
334                    if check_offset:
335                        self.assert_qmp(event, 'data/offset', event['data']['len'])
336                    completed = True
337
338        self.assert_no_active_block_jobs()
339        return event
340
341    def wait_ready(self, drive='drive0'):
342        '''Wait until a block job BLOCK_JOB_READY event'''
343        f = {'data': {'type': 'mirror', 'device': drive } }
344        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
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
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
376def 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
381    open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
382    print '%s not run: %s' % (seq, reason)
383    sys.exit(0)
384
385def verify_image_format(supported_fmts=[]):
386    if supported_fmts and (imgfmt not in supported_fmts):
387        notrun('not suitable for this image format: %s' % imgfmt)
388
389def verify_platform(supported_oses=['linux']):
390    if True not in [sys.platform.startswith(x) for x in supported_oses]:
391        notrun('not suitable for this OS: %s' % sys.platform)
392
393def supports_quorum():
394    return 'quorum' in qemu_img_pipe('--help')
395
396def verify_quorum():
397    '''Skip test suite if quorum support is not available'''
398    if not supports_quorum():
399        notrun('quorum support missing')
400
401def main(supported_fmts=[], supported_oses=['linux']):
402    '''Run tests'''
403
404    global debug
405
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
414    debug = '-d' in sys.argv
415    verbosity = 1
416    verify_image_format(supported_fmts)
417    verify_platform(supported_oses)
418
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
422    if debug:
423        output = sys.stdout
424        verbosity = 2
425        sys.argv.remove('-d')
426    else:
427        output = StringIO.StringIO()
428
429    class MyTestRunner(unittest.TextTestRunner):
430        def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
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:
437        if not debug:
438            sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
439