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