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