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