]> git.proxmox.com Git - mirror_qemu.git/blame - tests/qemu-iotests/iotests.py
qemu-iotests: Add "_supported_os Linux" to 058
[mirror_qemu.git] / tests / qemu-iotests / iotests.py
CommitLineData
f345cfd0
SH
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
4f450568 22import string
f345cfd0 23import unittest
212774c5 24import sys; sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts', 'qmp'))
f345cfd0 25import qmp
2499a096 26import struct
f345cfd0
SH
27
28__all__ = ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
29 'VM', 'QMPTestCase', 'notrun', 'main']
30
31# This will not work if arguments or path contain spaces but is necessary if we
32# want to support the override options that ./check supports.
c68b039a
PB
33qemu_img_args = os.environ.get('QEMU_IMG', 'qemu-img').strip().split(' ')
34qemu_io_args = os.environ.get('QEMU_IO', 'qemu-io').strip().split(' ')
35qemu_args = os.environ.get('QEMU', 'qemu').strip().split(' ')
f345cfd0
SH
36
37imgfmt = os.environ.get('IMGFMT', 'raw')
38imgproto = os.environ.get('IMGPROTO', 'file')
39test_dir = os.environ.get('TEST_DIR', '/var/tmp')
e8f8624d 40output_dir = os.environ.get('OUTPUT_DIR', '.')
58cc2ae1 41cachemode = os.environ.get('CACHEMODE')
f345cfd0 42
30b005d9
WX
43socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
44
f345cfd0
SH
45def qemu_img(*args):
46 '''Run qemu-img and return the exit code'''
47 devnull = open('/dev/null', 'r+')
48 return subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
49
d2ef210c 50def qemu_img_verbose(*args):
993d46ce 51 '''Run qemu-img without suppressing its output and return the exit code'''
d2ef210c
KW
52 return subprocess.call(qemu_img_args + list(args))
53
3677e6f6
HR
54def qemu_img_pipe(*args):
55 '''Run qemu-img and return its output'''
56 return subprocess.Popen(qemu_img_args + list(args), stdout=subprocess.PIPE).communicate()[0]
57
f345cfd0
SH
58def qemu_io(*args):
59 '''Run qemu-io and return the stdout data'''
60 args = qemu_io_args + list(args)
61 return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
62
3a3918c3
SH
63def compare_images(img1, img2):
64 '''Return True if two image files are identical'''
65 return qemu_img('compare', '-f', imgfmt,
66 '-F', imgfmt, img1, img2) == 0
67
2499a096
SH
68def create_image(name, size):
69 '''Create a fully-allocated raw image with sector markers'''
70 file = open(name, 'w')
71 i = 0
72 while i < size:
73 sector = struct.pack('>l504xl', i / 512, i / 512)
74 file.write(sector)
75 i = i + 512
76 file.close()
77
f345cfd0
SH
78class VM(object):
79 '''A QEMU VM'''
80
81 def __init__(self):
82 self._monitor_path = os.path.join(test_dir, 'qemu-mon.%d' % os.getpid())
83 self._qemu_log_path = os.path.join(test_dir, 'qemu-log.%d' % os.getpid())
84 self._args = qemu_args + ['-chardev',
85 'socket,id=mon,path=' + self._monitor_path,
0fd05e8d
PB
86 '-mon', 'chardev=mon,mode=control',
87 '-qtest', 'stdio', '-machine', 'accel=qtest',
88 '-display', 'none', '-vga', 'none']
f345cfd0
SH
89 self._num_drives = 0
90
30b005d9
WX
91 # This can be used to add an unused monitor instance.
92 def add_monitor_telnet(self, ip, port):
93 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
94 self._args.append('-monitor')
95 self._args.append(args)
96
f345cfd0
SH
97 def add_drive(self, path, opts=''):
98 '''Add a virtio-blk drive to the VM'''
99 options = ['if=virtio',
100 'format=%s' % imgfmt,
58cc2ae1 101 'cache=%s' % cachemode,
f345cfd0
SH
102 'file=%s' % path,
103 'id=drive%d' % self._num_drives]
104 if opts:
105 options.append(opts)
106
107 self._args.append('-drive')
108 self._args.append(','.join(options))
109 self._num_drives += 1
110 return self
111
3cf53c77
FZ
112 def pause_drive(self, drive, event=None):
113 '''Pause drive r/w operations'''
114 if not event:
115 self.pause_drive(drive, "read_aio")
116 self.pause_drive(drive, "write_aio")
117 return
118 self.qmp('human-monitor-command',
119 command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
120
121 def resume_drive(self, drive):
122 self.qmp('human-monitor-command',
123 command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
124
e3409362
IM
125 def hmp_qemu_io(self, drive, cmd):
126 '''Write to a given drive using an HMP command'''
127 return self.qmp('human-monitor-command',
128 command_line='qemu-io %s "%s"' % (drive, cmd))
129
23e956bf
CB
130 def add_fd(self, fd, fdset, opaque, opts=''):
131 '''Pass a file descriptor to the VM'''
132 options = ['fd=%d' % fd,
133 'set=%d' % fdset,
134 'opaque=%s' % opaque]
135 if opts:
136 options.append(opts)
137
138 self._args.append('-add-fd')
139 self._args.append(','.join(options))
140 return self
141
30b005d9
WX
142 def send_fd_scm(self, fd_file_path):
143 # In iotest.py, the qmp should always use unix socket.
144 assert self._qmp.is_scm_available()
145 bin = socket_scm_helper
146 if os.path.exists(bin) == False:
147 print "Scm help program does not present, path '%s'." % bin
148 return -1
149 fd_param = ["%s" % bin,
150 "%d" % self._qmp.get_sock_fd(),
151 "%s" % fd_file_path]
152 devnull = open('/dev/null', 'rb')
153 p = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
154 stderr=sys.stderr)
155 return p.wait()
156
f345cfd0
SH
157 def launch(self):
158 '''Launch the VM and establish a QMP connection'''
159 devnull = open('/dev/null', 'rb')
160 qemulog = open(self._qemu_log_path, 'wb')
161 try:
162 self._qmp = qmp.QEMUMonitorProtocol(self._monitor_path, server=True)
163 self._popen = subprocess.Popen(self._args, stdin=devnull, stdout=qemulog,
164 stderr=subprocess.STDOUT)
165 self._qmp.accept()
166 except:
167 os.remove(self._monitor_path)
168 raise
169
170 def shutdown(self):
171 '''Terminate the VM and clean up'''
863a5d04
PB
172 if not self._popen is None:
173 self._qmp.cmd('quit')
174 self._popen.wait()
175 os.remove(self._monitor_path)
176 os.remove(self._qemu_log_path)
177 self._popen = None
f345cfd0 178
4f450568 179 underscore_to_dash = string.maketrans('_', '-')
f345cfd0
SH
180 def qmp(self, cmd, **args):
181 '''Invoke a QMP command and return the result dict'''
4f450568
PB
182 qmp_args = dict()
183 for k in args.keys():
184 qmp_args[k.translate(self.underscore_to_dash)] = args[k]
185
186 return self._qmp.cmd(cmd, args=qmp_args)
f345cfd0 187
9dfa9f59
PB
188 def get_qmp_event(self, wait=False):
189 '''Poll for one queued QMP events and return it'''
190 return self._qmp.pull_event(wait=wait)
191
f345cfd0
SH
192 def get_qmp_events(self, wait=False):
193 '''Poll for queued QMP events and return a list of dicts'''
194 events = self._qmp.get_events(wait=wait)
195 self._qmp.clear_events()
196 return events
197
198index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
199
200class QMPTestCase(unittest.TestCase):
201 '''Abstract base class for QMP test cases'''
202
203 def dictpath(self, d, path):
204 '''Traverse a path in a nested dict'''
205 for component in path.split('/'):
206 m = index_re.match(component)
207 if m:
208 component, idx = m.groups()
209 idx = int(idx)
210
211 if not isinstance(d, dict) or component not in d:
212 self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
213 d = d[component]
214
215 if m:
216 if not isinstance(d, list):
217 self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
218 try:
219 d = d[idx]
220 except IndexError:
221 self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
222 return d
223
90f0b711
PB
224 def assert_qmp_absent(self, d, path):
225 try:
226 result = self.dictpath(d, path)
227 except AssertionError:
228 return
229 self.fail('path "%s" has value "%s"' % (path, str(result)))
230
f345cfd0
SH
231 def assert_qmp(self, d, path, value):
232 '''Assert that the value for a specific path in a QMP dict matches'''
233 result = self.dictpath(d, path)
234 self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
235
ecc1c88e
SH
236 def assert_no_active_block_jobs(self):
237 result = self.vm.qmp('query-block-jobs')
238 self.assert_qmp(result, 'return', [])
239
3cf53c77 240 def cancel_and_wait(self, drive='drive0', force=False, resume=False):
2575fe16
SH
241 '''Cancel a block job and wait for it to finish, returning the event'''
242 result = self.vm.qmp('block-job-cancel', device=drive, force=force)
243 self.assert_qmp(result, 'return', {})
244
3cf53c77
FZ
245 if resume:
246 self.vm.resume_drive(drive)
247
2575fe16
SH
248 cancelled = False
249 result = None
250 while not cancelled:
251 for event in self.vm.get_qmp_events(wait=True):
252 if event['event'] == 'BLOCK_JOB_COMPLETED' or \
253 event['event'] == 'BLOCK_JOB_CANCELLED':
254 self.assert_qmp(event, 'data/device', drive)
255 result = event
256 cancelled = True
257
258 self.assert_no_active_block_jobs()
259 return result
260
9974ad40 261 def wait_until_completed(self, drive='drive0', check_offset=True):
0dbe8a1b
SH
262 '''Wait for a block job to finish, returning the event'''
263 completed = False
264 while not completed:
265 for event in self.vm.get_qmp_events(wait=True):
266 if event['event'] == 'BLOCK_JOB_COMPLETED':
267 self.assert_qmp(event, 'data/device', drive)
268 self.assert_qmp_absent(event, 'data/error')
9974ad40 269 if check_offset:
1d3ba15a 270 self.assert_qmp(event, 'data/offset', event['data']['len'])
0dbe8a1b
SH
271 completed = True
272
273 self.assert_no_active_block_jobs()
274 return event
275
f345cfd0
SH
276def notrun(reason):
277 '''Skip this test suite'''
278 # Each test in qemu-iotests has a number ("seq")
279 seq = os.path.basename(sys.argv[0])
280
e8f8624d 281 open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
f345cfd0
SH
282 print '%s not run: %s' % (seq, reason)
283 sys.exit(0)
284
285def main(supported_fmts=[]):
286 '''Run tests'''
287
288 if supported_fmts and (imgfmt not in supported_fmts):
289 notrun('not suitable for this image format: %s' % imgfmt)
290
291 # We need to filter out the time taken from the output so that qemu-iotest
292 # can reliably diff the results against master output.
293 import StringIO
294 output = StringIO.StringIO()
295
296 class MyTestRunner(unittest.TextTestRunner):
297 def __init__(self, stream=output, descriptions=True, verbosity=1):
298 unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
299
300 # unittest.main() will use sys.exit() so expect a SystemExit exception
301 try:
302 unittest.main(testRunner=MyTestRunner)
303 finally:
d2ef210c 304 sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))