xref: /qemu/tests/qemu-iotests/iotests.py (revision 67cc32eb)
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 os
20import re
21import subprocess
22import string
23import unittest
24import sys
25sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
26sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'qmp'))
27import qmp
28import qtest
29import struct
30
31__all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
32           'VM', 'QMPTestCase', 'notrun', 'main']
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_args = [os.environ.get('QEMU_PROG', 'qemu')]
45if os.environ.get('QEMU_OPTIONS'):
46    qemu_args += os.environ['QEMU_OPTIONS'].strip().split(' ')
47
48imgfmt = os.environ.get('IMGFMT', 'raw')
49imgproto = os.environ.get('IMGPROTO', 'file')
50test_dir = os.environ.get('TEST_DIR', '/var/tmp')
51output_dir = os.environ.get('OUTPUT_DIR', '.')
52cachemode = os.environ.get('CACHEMODE')
53qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
54
55socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
56
57def qemu_img(*args):
58    '''Run qemu-img and return the exit code'''
59    devnull = open('/dev/null', 'r+')
60    exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
61    if exitcode < 0:
62        sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
63    return exitcode
64
65def qemu_img_verbose(*args):
66    '''Run qemu-img without suppressing its output and return the exit code'''
67    exitcode = subprocess.call(qemu_img_args + list(args))
68    if exitcode < 0:
69        sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
70    return exitcode
71
72def qemu_img_pipe(*args):
73    '''Run qemu-img and return its output'''
74    subp = subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE)
75    exitcode = subp.wait()
76    if exitcode < 0:
77        sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
78    return subp.communicate()[0]
79
80def qemu_io(*args):
81    '''Run qemu-io and return the stdout data'''
82    args = qemu_io_args + list(args)
83    subp = subprocess.Popen(args, stdout=subprocess.PIPE)
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
104# Test if 'match' is a recursive subset of 'event'
105def event_match(event, match=None):
106    if match is None:
107        return True
108
109    for key in match:
110        if key in event:
111            if isinstance(event[key], dict):
112                if not event_match(event[key], match[key]):
113                    return False
114            elif event[key] != match[key]:
115                return False
116        else:
117            return False
118
119    return True
120
121class VM(object):
122    '''A QEMU VM'''
123
124    def __init__(self):
125        self._monitor_path = os.path.join(test_dir, 'qemu-mon.%d' % os.getpid())
126        self._qemu_log_path = os.path.join(test_dir, 'qemu-log.%d' % os.getpid())
127        self._qtest_path = os.path.join(test_dir, 'qemu-qtest.%d' % os.getpid())
128        self._args = qemu_args + ['-chardev',
129                     'socket,id=mon,path=' + self._monitor_path,
130                     '-mon', 'chardev=mon,mode=control',
131                     '-qtest', 'unix:path=' + self._qtest_path,
132                     '-machine', 'accel=qtest',
133                     '-display', 'none', '-vga', 'none']
134        self._num_drives = 0
135        self._events = []
136
137    # This can be used to add an unused monitor instance.
138    def add_monitor_telnet(self, ip, port):
139        args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
140        self._args.append('-monitor')
141        self._args.append(args)
142
143    def add_drive(self, path, opts='', interface='virtio'):
144        '''Add a virtio-blk drive to the VM'''
145        options = ['if=%s' % interface,
146                   'format=%s' % imgfmt,
147                   'cache=%s' % cachemode,
148                   'id=drive%d' % self._num_drives]
149
150        if path is not None:
151            options.append('file=%s' % path)
152
153        if opts:
154            options.append(opts)
155
156        self._args.append('-drive')
157        self._args.append(','.join(options))
158        self._num_drives += 1
159        return self
160
161    def pause_drive(self, drive, event=None):
162        '''Pause drive r/w operations'''
163        if not event:
164            self.pause_drive(drive, "read_aio")
165            self.pause_drive(drive, "write_aio")
166            return
167        self.qmp('human-monitor-command',
168                    command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
169
170    def resume_drive(self, drive):
171        self.qmp('human-monitor-command',
172                    command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
173
174    def hmp_qemu_io(self, drive, cmd):
175        '''Write to a given drive using an HMP command'''
176        return self.qmp('human-monitor-command',
177                        command_line='qemu-io %s "%s"' % (drive, cmd))
178
179    def add_fd(self, fd, fdset, opaque, opts=''):
180        '''Pass a file descriptor to the VM'''
181        options = ['fd=%d' % fd,
182                   'set=%d' % fdset,
183                   'opaque=%s' % opaque]
184        if opts:
185            options.append(opts)
186
187        self._args.append('-add-fd')
188        self._args.append(','.join(options))
189        return self
190
191    def send_fd_scm(self, fd_file_path):
192        # In iotest.py, the qmp should always use unix socket.
193        assert self._qmp.is_scm_available()
194        bin = socket_scm_helper
195        if os.path.exists(bin) == False:
196            print "Scm help program does not present, path '%s'." % bin
197            return -1
198        fd_param = ["%s" % bin,
199                    "%d" % self._qmp.get_sock_fd(),
200                    "%s" % fd_file_path]
201        devnull = open('/dev/null', 'rb')
202        p = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
203                             stderr=sys.stderr)
204        return p.wait()
205
206    def launch(self):
207        '''Launch the VM and establish a QMP connection'''
208        devnull = open('/dev/null', 'rb')
209        qemulog = open(self._qemu_log_path, 'wb')
210        try:
211            self._qmp = qmp.QEMUMonitorProtocol(self._monitor_path, server=True)
212            self._qtest = qtest.QEMUQtestProtocol(self._qtest_path, server=True)
213            self._popen = subprocess.Popen(self._args, stdin=devnull, stdout=qemulog,
214                                           stderr=subprocess.STDOUT)
215            self._qmp.accept()
216            self._qtest.accept()
217        except:
218            os.remove(self._monitor_path)
219            raise
220
221    def shutdown(self):
222        '''Terminate the VM and clean up'''
223        if not self._popen is None:
224            self._qmp.cmd('quit')
225            exitcode = self._popen.wait()
226            if exitcode < 0:
227                sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode, ' '.join(self._args)))
228            os.remove(self._monitor_path)
229            os.remove(self._qtest_path)
230            os.remove(self._qemu_log_path)
231            self._popen = None
232
233    underscore_to_dash = string.maketrans('_', '-')
234    def qmp(self, cmd, conv_keys=True, **args):
235        '''Invoke a QMP command and return the result dict'''
236        qmp_args = dict()
237        for k in args.keys():
238            if conv_keys:
239                qmp_args[k.translate(self.underscore_to_dash)] = args[k]
240            else:
241                qmp_args[k] = args[k]
242
243        return self._qmp.cmd(cmd, args=qmp_args)
244
245    def qtest(self, cmd):
246        '''Send a qtest command to guest'''
247        return self._qtest.cmd(cmd)
248
249    def get_qmp_event(self, wait=False):
250        '''Poll for one queued QMP events and return it'''
251        if len(self._events) > 0:
252            return self._events.pop(0)
253        return self._qmp.pull_event(wait=wait)
254
255    def get_qmp_events(self, wait=False):
256        '''Poll for queued QMP events and return a list of dicts'''
257        events = self._qmp.get_events(wait=wait)
258        events.extend(self._events)
259        del self._events[:]
260        self._qmp.clear_events()
261        return events
262
263    def event_wait(self, name='BLOCK_JOB_COMPLETED', timeout=60.0, match=None):
264        # Search cached events
265        for event in self._events:
266            if (event['event'] == name) and event_match(event, match):
267                self._events.remove(event)
268                return event
269
270        # Poll for new events
271        while True:
272            event = self._qmp.pull_event(wait=timeout)
273            if (event['event'] == name) and event_match(event, match):
274                return event
275            self._events.append(event)
276
277        return None
278
279index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
280
281class QMPTestCase(unittest.TestCase):
282    '''Abstract base class for QMP test cases'''
283
284    def dictpath(self, d, path):
285        '''Traverse a path in a nested dict'''
286        for component in path.split('/'):
287            m = index_re.match(component)
288            if m:
289                component, idx = m.groups()
290                idx = int(idx)
291
292            if not isinstance(d, dict) or component not in d:
293                self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
294            d = d[component]
295
296            if m:
297                if not isinstance(d, list):
298                    self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
299                try:
300                    d = d[idx]
301                except IndexError:
302                    self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
303        return d
304
305    def assert_qmp_absent(self, d, path):
306        try:
307            result = self.dictpath(d, path)
308        except AssertionError:
309            return
310        self.fail('path "%s" has value "%s"' % (path, str(result)))
311
312    def assert_qmp(self, d, path, value):
313        '''Assert that the value for a specific path in a QMP dict matches'''
314        result = self.dictpath(d, path)
315        self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
316
317    def assert_no_active_block_jobs(self):
318        result = self.vm.qmp('query-block-jobs')
319        self.assert_qmp(result, 'return', [])
320
321    def cancel_and_wait(self, drive='drive0', force=False, resume=False):
322        '''Cancel a block job and wait for it to finish, returning the event'''
323        result = self.vm.qmp('block-job-cancel', device=drive, force=force)
324        self.assert_qmp(result, 'return', {})
325
326        if resume:
327            self.vm.resume_drive(drive)
328
329        cancelled = False
330        result = None
331        while not cancelled:
332            for event in self.vm.get_qmp_events(wait=True):
333                if event['event'] == 'BLOCK_JOB_COMPLETED' or \
334                   event['event'] == 'BLOCK_JOB_CANCELLED':
335                    self.assert_qmp(event, 'data/device', drive)
336                    result = event
337                    cancelled = True
338
339        self.assert_no_active_block_jobs()
340        return result
341
342    def wait_until_completed(self, drive='drive0', check_offset=True):
343        '''Wait for a block job to finish, returning the event'''
344        completed = False
345        while not completed:
346            for event in self.vm.get_qmp_events(wait=True):
347                if event['event'] == 'BLOCK_JOB_COMPLETED':
348                    self.assert_qmp(event, 'data/device', drive)
349                    self.assert_qmp_absent(event, 'data/error')
350                    if check_offset:
351                        self.assert_qmp(event, 'data/offset', event['data']['len'])
352                    completed = True
353
354        self.assert_no_active_block_jobs()
355        return event
356
357    def wait_ready(self, drive='drive0'):
358        '''Wait until a block job BLOCK_JOB_READY event'''
359        f = {'data': {'type': 'mirror', 'device': drive } }
360        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
361
362    def wait_ready_and_cancel(self, drive='drive0'):
363        self.wait_ready(drive=drive)
364        event = self.cancel_and_wait(drive=drive)
365        self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
366        self.assert_qmp(event, 'data/type', 'mirror')
367        self.assert_qmp(event, 'data/offset', event['data']['len'])
368
369    def complete_and_wait(self, drive='drive0', wait_ready=True):
370        '''Complete a block job and wait for it to finish'''
371        if wait_ready:
372            self.wait_ready(drive=drive)
373
374        result = self.vm.qmp('block-job-complete', device=drive)
375        self.assert_qmp(result, 'return', {})
376
377        event = self.wait_until_completed(drive=drive)
378        self.assert_qmp(event, 'data/type', 'mirror')
379
380def notrun(reason):
381    '''Skip this test suite'''
382    # Each test in qemu-iotests has a number ("seq")
383    seq = os.path.basename(sys.argv[0])
384
385    open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
386    print '%s not run: %s' % (seq, reason)
387    sys.exit(0)
388
389def main(supported_fmts=[], supported_oses=['linux']):
390    '''Run tests'''
391
392    debug = '-d' in sys.argv
393    verbosity = 1
394    if supported_fmts and (imgfmt not in supported_fmts):
395        notrun('not suitable for this image format: %s' % imgfmt)
396
397    if True not in [sys.platform.startswith(x) for x in supported_oses]:
398        notrun('not suitable for this OS: %s' % sys.platform)
399
400    # We need to filter out the time taken from the output so that qemu-iotest
401    # can reliably diff the results against master output.
402    import StringIO
403    if debug:
404        output = sys.stdout
405        verbosity = 2
406        sys.argv.remove('-d')
407    else:
408        output = StringIO.StringIO()
409
410    class MyTestRunner(unittest.TextTestRunner):
411        def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
412            unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
413
414    # unittest.main() will use sys.exit() so expect a SystemExit exception
415    try:
416        unittest.main(testRunner=MyTestRunner)
417    finally:
418        if not debug:
419            sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
420