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