xref: /openbmc/qemu/tests/qemu-iotests/iotests.py (revision bb2e0039)
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 filter_qmp_event(event):
137    '''Filter a QMP event dict'''
138    event = dict(event)
139    if 'timestamp' in event:
140        event['timestamp']['seconds'] = 'SECS'
141        event['timestamp']['microseconds'] = 'USECS'
142    return event
143
144def log(msg, filters=[]):
145    for flt in filters:
146        msg = flt(msg)
147    print msg
148
149class Timeout:
150    def __init__(self, seconds, errmsg = "Timeout"):
151        self.seconds = seconds
152        self.errmsg = errmsg
153    def __enter__(self):
154        signal.signal(signal.SIGALRM, self.timeout)
155        signal.setitimer(signal.ITIMER_REAL, self.seconds)
156        return self
157    def __exit__(self, type, value, traceback):
158        signal.setitimer(signal.ITIMER_REAL, 0)
159        return False
160    def timeout(self, signum, frame):
161        raise Exception(self.errmsg)
162
163
164class FilePath(object):
165    '''An auto-generated filename that cleans itself up.
166
167    Use this context manager to generate filenames and ensure that the file
168    gets deleted::
169
170        with TestFilePath('test.img') as img_path:
171            qemu_img('create', img_path, '1G')
172        # migration_sock_path is automatically deleted
173    '''
174    def __init__(self, name):
175        filename = '{0}-{1}'.format(os.getpid(), name)
176        self.path = os.path.join(test_dir, filename)
177
178    def __enter__(self):
179        return self.path
180
181    def __exit__(self, exc_type, exc_val, exc_tb):
182        try:
183            os.remove(self.path)
184        except OSError:
185            pass
186        return False
187
188
189class VM(qtest.QEMUQtestMachine):
190    '''A QEMU VM'''
191
192    def __init__(self, path_suffix=''):
193        name = "qemu%s-%d" % (path_suffix, os.getpid())
194        super(VM, self).__init__(qemu_prog, qemu_opts, name=name,
195                                 test_dir=test_dir,
196                                 socket_scm_helper=socket_scm_helper)
197        if debug:
198            self._debug = True
199        self._num_drives = 0
200
201    def add_device(self, opts):
202        self._args.append('-device')
203        self._args.append(opts)
204        return self
205
206    def add_drive_raw(self, opts):
207        self._args.append('-drive')
208        self._args.append(opts)
209        return self
210
211    def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
212        '''Add a virtio-blk drive to the VM'''
213        options = ['if=%s' % interface,
214                   'id=drive%d' % self._num_drives]
215
216        if path is not None:
217            options.append('file=%s' % path)
218            options.append('format=%s' % format)
219            options.append('cache=%s' % cachemode)
220
221        if opts:
222            options.append(opts)
223
224        self._args.append('-drive')
225        self._args.append(','.join(options))
226        self._num_drives += 1
227        return self
228
229    def add_blockdev(self, opts):
230        self._args.append('-blockdev')
231        if isinstance(opts, str):
232            self._args.append(opts)
233        else:
234            self._args.append(','.join(opts))
235        return self
236
237    def add_incoming(self, addr):
238        self._args.append('-incoming')
239        self._args.append(addr)
240        return self
241
242    def pause_drive(self, drive, event=None):
243        '''Pause drive r/w operations'''
244        if not event:
245            self.pause_drive(drive, "read_aio")
246            self.pause_drive(drive, "write_aio")
247            return
248        self.qmp('human-monitor-command',
249                    command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
250
251    def resume_drive(self, drive):
252        self.qmp('human-monitor-command',
253                    command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
254
255    def hmp_qemu_io(self, drive, cmd):
256        '''Write to a given drive using an HMP command'''
257        return self.qmp('human-monitor-command',
258                        command_line='qemu-io %s "%s"' % (drive, cmd))
259
260
261index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
262
263class QMPTestCase(unittest.TestCase):
264    '''Abstract base class for QMP test cases'''
265
266    def dictpath(self, d, path):
267        '''Traverse a path in a nested dict'''
268        for component in path.split('/'):
269            m = index_re.match(component)
270            if m:
271                component, idx = m.groups()
272                idx = int(idx)
273
274            if not isinstance(d, dict) or component not in d:
275                self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
276            d = d[component]
277
278            if m:
279                if not isinstance(d, list):
280                    self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
281                try:
282                    d = d[idx]
283                except IndexError:
284                    self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
285        return d
286
287    def flatten_qmp_object(self, obj, output=None, basestr=''):
288        if output is None:
289            output = dict()
290        if isinstance(obj, list):
291            for i in range(len(obj)):
292                self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
293        elif isinstance(obj, dict):
294            for key in obj:
295                self.flatten_qmp_object(obj[key], output, basestr + key + '.')
296        else:
297            output[basestr[:-1]] = obj # Strip trailing '.'
298        return output
299
300    def qmp_to_opts(self, obj):
301        obj = self.flatten_qmp_object(obj)
302        output_list = list()
303        for key in obj:
304            output_list += [key + '=' + obj[key]]
305        return ','.join(output_list)
306
307    def assert_qmp_absent(self, d, path):
308        try:
309            result = self.dictpath(d, path)
310        except AssertionError:
311            return
312        self.fail('path "%s" has value "%s"' % (path, str(result)))
313
314    def assert_qmp(self, d, path, value):
315        '''Assert that the value for a specific path in a QMP dict matches'''
316        result = self.dictpath(d, path)
317        self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
318
319    def assert_no_active_block_jobs(self):
320        result = self.vm.qmp('query-block-jobs')
321        self.assert_qmp(result, 'return', [])
322
323    def assert_has_block_node(self, node_name=None, file_name=None):
324        """Issue a query-named-block-nodes and assert node_name and/or
325        file_name is present in the result"""
326        def check_equal_or_none(a, b):
327            return a == None or b == None or a == b
328        assert node_name or file_name
329        result = self.vm.qmp('query-named-block-nodes')
330        for x in result["return"]:
331            if check_equal_or_none(x.get("node-name"), node_name) and \
332                    check_equal_or_none(x.get("file"), file_name):
333                return
334        self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
335                (node_name, file_name, result))
336
337    def assert_json_filename_equal(self, json_filename, reference):
338        '''Asserts that the given filename is a json: filename and that its
339           content is equal to the given reference object'''
340        self.assertEqual(json_filename[:5], 'json:')
341        self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])),
342                         self.flatten_qmp_object(reference))
343
344    def cancel_and_wait(self, drive='drive0', force=False, resume=False):
345        '''Cancel a block job and wait for it to finish, returning the event'''
346        result = self.vm.qmp('block-job-cancel', device=drive, force=force)
347        self.assert_qmp(result, 'return', {})
348
349        if resume:
350            self.vm.resume_drive(drive)
351
352        cancelled = False
353        result = None
354        while not cancelled:
355            for event in self.vm.get_qmp_events(wait=True):
356                if event['event'] == 'BLOCK_JOB_COMPLETED' or \
357                   event['event'] == 'BLOCK_JOB_CANCELLED':
358                    self.assert_qmp(event, 'data/device', drive)
359                    result = event
360                    cancelled = True
361
362        self.assert_no_active_block_jobs()
363        return result
364
365    def wait_until_completed(self, drive='drive0', check_offset=True):
366        '''Wait for a block job to finish, returning the event'''
367        completed = False
368        while not completed:
369            for event in self.vm.get_qmp_events(wait=True):
370                if event['event'] == 'BLOCK_JOB_COMPLETED':
371                    self.assert_qmp(event, 'data/device', drive)
372                    self.assert_qmp_absent(event, 'data/error')
373                    if check_offset:
374                        self.assert_qmp(event, 'data/offset', event['data']['len'])
375                    completed = True
376
377        self.assert_no_active_block_jobs()
378        return event
379
380    def wait_ready(self, drive='drive0'):
381        '''Wait until a block job BLOCK_JOB_READY event'''
382        f = {'data': {'type': 'mirror', 'device': drive } }
383        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
384
385    def wait_ready_and_cancel(self, drive='drive0'):
386        self.wait_ready(drive=drive)
387        event = self.cancel_and_wait(drive=drive)
388        self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
389        self.assert_qmp(event, 'data/type', 'mirror')
390        self.assert_qmp(event, 'data/offset', event['data']['len'])
391
392    def complete_and_wait(self, drive='drive0', wait_ready=True):
393        '''Complete a block job and wait for it to finish'''
394        if wait_ready:
395            self.wait_ready(drive=drive)
396
397        result = self.vm.qmp('block-job-complete', device=drive)
398        self.assert_qmp(result, 'return', {})
399
400        event = self.wait_until_completed(drive=drive)
401        self.assert_qmp(event, 'data/type', 'mirror')
402
403    def pause_job(self, job_id='job0'):
404        result = self.vm.qmp('block-job-pause', device=job_id)
405        self.assert_qmp(result, 'return', {})
406
407        with Timeout(1, "Timeout waiting for job to pause"):
408            while True:
409                result = self.vm.qmp('query-block-jobs')
410                for job in result['return']:
411                    if job['device'] == job_id and job['paused'] == True and job['busy'] == False:
412                        return job
413
414
415def notrun(reason):
416    '''Skip this test suite'''
417    # Each test in qemu-iotests has a number ("seq")
418    seq = os.path.basename(sys.argv[0])
419
420    open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
421    print '%s not run: %s' % (seq, reason)
422    sys.exit(0)
423
424def verify_image_format(supported_fmts=[]):
425    if supported_fmts and (imgfmt not in supported_fmts):
426        notrun('not suitable for this image format: %s' % imgfmt)
427
428def verify_platform(supported_oses=['linux']):
429    if True not in [sys.platform.startswith(x) for x in supported_oses]:
430        notrun('not suitable for this OS: %s' % sys.platform)
431
432def supports_quorum():
433    return 'quorum' in qemu_img_pipe('--help')
434
435def verify_quorum():
436    '''Skip test suite if quorum support is not available'''
437    if not supports_quorum():
438        notrun('quorum support missing')
439
440def main(supported_fmts=[], supported_oses=['linux']):
441    '''Run tests'''
442
443    global debug
444
445    # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
446    # indicate that we're not being run via "check". There may be
447    # other things set up by "check" that individual test cases rely
448    # on.
449    if test_dir is None or qemu_default_machine is None:
450        sys.stderr.write('Please run this test via the "check" script\n')
451        sys.exit(os.EX_USAGE)
452
453    debug = '-d' in sys.argv
454    verbosity = 1
455    verify_image_format(supported_fmts)
456    verify_platform(supported_oses)
457
458    # We need to filter out the time taken from the output so that qemu-iotest
459    # can reliably diff the results against master output.
460    import StringIO
461    if debug:
462        output = sys.stdout
463        verbosity = 2
464        sys.argv.remove('-d')
465    else:
466        output = StringIO.StringIO()
467
468    class MyTestRunner(unittest.TextTestRunner):
469        def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
470            unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
471
472    # unittest.main() will use sys.exit() so expect a SystemExit exception
473    try:
474        unittest.main(testRunner=MyTestRunner)
475    finally:
476        if not debug:
477            sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
478