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