xref: /openbmc/qemu/tests/qemu-iotests/iotests.py (revision 1d48474d)
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
96def 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
100def 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
105def 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
115def 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
120test_dir_re = re.compile(r"%s" % test_dir)
121def filter_test_dir(msg):
122    return test_dir_re.sub("TEST_DIR", msg)
123
124win32_re = re.compile(r"\r")
125def filter_win32(msg):
126    return win32_re.sub("", msg)
127
128qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
129def 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
133chown_re = re.compile(r"chown [0-9]+:[0-9]+")
134def filter_chown(msg):
135    return chown_re.sub("chown UID:GID", msg)
136
137def 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
145def log(msg, filters=[]):
146    for flt in filters:
147        msg = flt(msg)
148    print msg
149
150class 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
165class 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
190class 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_device(self, opts):
201        self._args.append('-device')
202        self._args.append(opts)
203        return self
204
205    def add_drive_raw(self, opts):
206        self._args.append('-drive')
207        self._args.append(opts)
208        return self
209
210    def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
211        '''Add a virtio-blk drive to the VM'''
212        options = ['if=%s' % interface,
213                   'id=drive%d' % self._num_drives]
214
215        if path is not None:
216            options.append('file=%s' % path)
217            options.append('format=%s' % format)
218            options.append('cache=%s' % cachemode)
219
220        if opts:
221            options.append(opts)
222
223        self._args.append('-drive')
224        self._args.append(','.join(options))
225        self._num_drives += 1
226        return self
227
228    def add_blockdev(self, opts):
229        self._args.append('-blockdev')
230        if isinstance(opts, str):
231            self._args.append(opts)
232        else:
233            self._args.append(','.join(opts))
234        return self
235
236    def add_incoming(self, addr):
237        self._args.append('-incoming')
238        self._args.append(addr)
239        return self
240
241    def pause_drive(self, drive, event=None):
242        '''Pause drive r/w operations'''
243        if not event:
244            self.pause_drive(drive, "read_aio")
245            self.pause_drive(drive, "write_aio")
246            return
247        self.qmp('human-monitor-command',
248                    command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
249
250    def resume_drive(self, drive):
251        self.qmp('human-monitor-command',
252                    command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
253
254    def hmp_qemu_io(self, drive, cmd):
255        '''Write to a given drive using an HMP command'''
256        return self.qmp('human-monitor-command',
257                        command_line='qemu-io %s "%s"' % (drive, cmd))
258
259
260index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
261
262class QMPTestCase(unittest.TestCase):
263    '''Abstract base class for QMP test cases'''
264
265    def dictpath(self, d, path):
266        '''Traverse a path in a nested dict'''
267        for component in path.split('/'):
268            m = index_re.match(component)
269            if m:
270                component, idx = m.groups()
271                idx = int(idx)
272
273            if not isinstance(d, dict) or component not in d:
274                self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
275            d = d[component]
276
277            if m:
278                if not isinstance(d, list):
279                    self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
280                try:
281                    d = d[idx]
282                except IndexError:
283                    self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
284        return d
285
286    def flatten_qmp_object(self, obj, output=None, basestr=''):
287        if output is None:
288            output = dict()
289        if isinstance(obj, list):
290            for i in range(len(obj)):
291                self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
292        elif isinstance(obj, dict):
293            for key in obj:
294                self.flatten_qmp_object(obj[key], output, basestr + key + '.')
295        else:
296            output[basestr[:-1]] = obj # Strip trailing '.'
297        return output
298
299    def qmp_to_opts(self, obj):
300        obj = self.flatten_qmp_object(obj)
301        output_list = list()
302        for key in obj:
303            output_list += [key + '=' + obj[key]]
304        return ','.join(output_list)
305
306    def assert_qmp_absent(self, d, path):
307        try:
308            result = self.dictpath(d, path)
309        except AssertionError:
310            return
311        self.fail('path "%s" has value "%s"' % (path, str(result)))
312
313    def assert_qmp(self, d, path, value):
314        '''Assert that the value for a specific path in a QMP dict matches'''
315        result = self.dictpath(d, path)
316        self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
317
318    def assert_no_active_block_jobs(self):
319        result = self.vm.qmp('query-block-jobs')
320        self.assert_qmp(result, 'return', [])
321
322    def assert_has_block_node(self, node_name=None, file_name=None):
323        """Issue a query-named-block-nodes and assert node_name and/or
324        file_name is present in the result"""
325        def check_equal_or_none(a, b):
326            return a == None or b == None or a == b
327        assert node_name or file_name
328        result = self.vm.qmp('query-named-block-nodes')
329        for x in result["return"]:
330            if check_equal_or_none(x.get("node-name"), node_name) and \
331                    check_equal_or_none(x.get("file"), file_name):
332                return
333        self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
334                (node_name, file_name, result))
335
336    def assert_json_filename_equal(self, json_filename, reference):
337        '''Asserts that the given filename is a json: filename and that its
338           content is equal to the given reference object'''
339        self.assertEqual(json_filename[:5], 'json:')
340        self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])),
341                         self.flatten_qmp_object(reference))
342
343    def cancel_and_wait(self, drive='drive0', force=False, resume=False):
344        '''Cancel a block job and wait for it to finish, returning the event'''
345        result = self.vm.qmp('block-job-cancel', device=drive, force=force)
346        self.assert_qmp(result, 'return', {})
347
348        if resume:
349            self.vm.resume_drive(drive)
350
351        cancelled = False
352        result = None
353        while not cancelled:
354            for event in self.vm.get_qmp_events(wait=True):
355                if event['event'] == 'BLOCK_JOB_COMPLETED' or \
356                   event['event'] == 'BLOCK_JOB_CANCELLED':
357                    self.assert_qmp(event, 'data/device', drive)
358                    result = event
359                    cancelled = True
360
361        self.assert_no_active_block_jobs()
362        return result
363
364    def wait_until_completed(self, drive='drive0', check_offset=True):
365        '''Wait for a block job to finish, returning the event'''
366        completed = False
367        while not completed:
368            for event in self.vm.get_qmp_events(wait=True):
369                if event['event'] == 'BLOCK_JOB_COMPLETED':
370                    self.assert_qmp(event, 'data/device', drive)
371                    self.assert_qmp_absent(event, 'data/error')
372                    if check_offset:
373                        self.assert_qmp(event, 'data/offset', event['data']['len'])
374                    completed = True
375
376        self.assert_no_active_block_jobs()
377        return event
378
379    def wait_ready(self, drive='drive0'):
380        '''Wait until a block job BLOCK_JOB_READY event'''
381        f = {'data': {'type': 'mirror', 'device': drive } }
382        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
383
384    def wait_ready_and_cancel(self, drive='drive0'):
385        self.wait_ready(drive=drive)
386        event = self.cancel_and_wait(drive=drive)
387        self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
388        self.assert_qmp(event, 'data/type', 'mirror')
389        self.assert_qmp(event, 'data/offset', event['data']['len'])
390
391    def complete_and_wait(self, drive='drive0', wait_ready=True):
392        '''Complete a block job and wait for it to finish'''
393        if wait_ready:
394            self.wait_ready(drive=drive)
395
396        result = self.vm.qmp('block-job-complete', device=drive)
397        self.assert_qmp(result, 'return', {})
398
399        event = self.wait_until_completed(drive=drive)
400        self.assert_qmp(event, 'data/type', 'mirror')
401
402    def pause_job(self, job_id='job0'):
403        result = self.vm.qmp('block-job-pause', device=job_id)
404        self.assert_qmp(result, 'return', {})
405
406        with Timeout(1, "Timeout waiting for job to pause"):
407            while True:
408                result = self.vm.qmp('query-block-jobs')
409                for job in result['return']:
410                    if job['device'] == job_id and job['paused'] == True and job['busy'] == False:
411                        return job
412
413
414def notrun(reason):
415    '''Skip this test suite'''
416    # Each test in qemu-iotests has a number ("seq")
417    seq = os.path.basename(sys.argv[0])
418
419    open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
420    print '%s not run: %s' % (seq, reason)
421    sys.exit(0)
422
423def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
424    if supported_fmts and (imgfmt not in supported_fmts):
425        notrun('not suitable for this image format: %s' % imgfmt)
426    if unsupported_fmts and (imgfmt in unsupported_fmts):
427        notrun('not suitable for this image format: %s' % imgfmt)
428
429def verify_platform(supported_oses=['linux']):
430    if True not in [sys.platform.startswith(x) for x in supported_oses]:
431        notrun('not suitable for this OS: %s' % sys.platform)
432
433def supports_quorum():
434    return 'quorum' in qemu_img_pipe('--help')
435
436def verify_quorum():
437    '''Skip test suite if quorum support is not available'''
438    if not supports_quorum():
439        notrun('quorum support missing')
440
441def main(supported_fmts=[], supported_oses=['linux']):
442    '''Run tests'''
443
444    global debug
445
446    # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
447    # indicate that we're not being run via "check". There may be
448    # other things set up by "check" that individual test cases rely
449    # on.
450    if test_dir is None or qemu_default_machine is None:
451        sys.stderr.write('Please run this test via the "check" script\n')
452        sys.exit(os.EX_USAGE)
453
454    debug = '-d' in sys.argv
455    verbosity = 1
456    verify_image_format(supported_fmts)
457    verify_platform(supported_oses)
458
459    # We need to filter out the time taken from the output so that qemu-iotest
460    # can reliably diff the results against master output.
461    import StringIO
462    if debug:
463        output = sys.stdout
464        verbosity = 2
465        sys.argv.remove('-d')
466    else:
467        output = StringIO.StringIO()
468
469    logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
470
471    class MyTestRunner(unittest.TextTestRunner):
472        def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
473            unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
474
475    # unittest.main() will use sys.exit() so expect a SystemExit exception
476    try:
477        unittest.main(testRunner=MyTestRunner)
478    finally:
479        if not debug:
480            sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
481