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