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