2018-06-08 14:29:43 +02:00
|
|
|
from __future__ import print_function
|
2012-02-29 14:25:21 +01:00
|
|
|
# Common utilities and Python wrappers for qemu-iotests
|
|
|
|
#
|
|
|
|
# Copyright (C) 2012 IBM Corp.
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
#
|
|
|
|
|
qemu-iotests: iotests.VM: remove qtest socket on error
On error, VM.launch() cleaned up the monitor unix socket, but left the
qtest unix socket behind. This caused the remaining sub-tests to fail
with EADDRINUSE:
+======================================================================
+ERROR: testQuorum (__main__.TestFifoQuorumEvents)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "148", line 63, in setUp
+ self.vm.launch()
+ File "/home6/silbe/qemu/tests/qemu-iotests/iotests.py", line 247, in launch
+ self._qmp.accept()
+ File "/home6/silbe/qemu/tests/qemu-iotests/../../scripts/qmp/qmp.py", line 141, in accept
+ return self.__negotiate_capabilities()
+ File "/home6/silbe/qemu/tests/qemu-iotests/../../scripts/qmp/qmp.py", line 57, in __negotiate_capabilities
+ raise QMPConnectError
+QMPConnectError
+
+======================================================================
+ERROR: testQuorum (__main__.TestQuorumEvents)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "148", line 63, in setUp
+ self.vm.launch()
+ File "/home6/silbe/qemu/tests/qemu-iotests/iotests.py", line 244, in launch
+ self._qtest = qtest.QEMUQtestProtocol(self._qtest_path, server=True)
+ File "/home6/silbe/qemu/tests/qemu-iotests/../../scripts/qtest.py", line 33, in __init__
+ self._sock.bind(self._address)
+ File "/usr/lib64/python2.7/socket.py", line 224, in meth
+ return getattr(self._sock,name)(*args)
+error: [Errno 98] Address already in use
Fix this by cleaning up both the monitor socket and the qtest socket iff
they exist.
Signed-off-by: Sascha Silbe <silbe@linux.vnet.ibm.com>
Reviewed-by: Bo Tu <tubo@linux.vnet.ibm.com>
Message-id: 1459848109-29756-4-git-send-email-silbe@linux.vnet.ibm.com
Reviewed-by: Max Reitz <mreitz@redhat.com>
Signed-off-by: Max Reitz <mreitz@redhat.com>
2016-04-05 11:21:45 +02:00
|
|
|
import errno
|
2012-02-29 14:25:21 +01:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import subprocess
|
2012-09-28 17:23:01 +02:00
|
|
|
import string
|
2012-02-29 14:25:21 +01:00
|
|
|
import unittest
|
2015-01-30 03:49:44 +01:00
|
|
|
import sys
|
2013-05-28 17:11:37 +02:00
|
|
|
import struct
|
2016-04-20 04:48:35 +02:00
|
|
|
import json
|
2017-07-21 16:41:21 +02:00
|
|
|
import signal
|
2017-09-27 15:03:36 +02:00
|
|
|
import logging
|
2018-03-12 16:21:25 +01:00
|
|
|
import atexit
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2018-03-12 16:21:24 +01:00
|
|
|
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
|
|
|
|
import qtest
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2015-09-02 20:52:27 +02:00
|
|
|
# This will not work if arguments contain spaces but is necessary if we
|
2012-02-29 14:25:21 +01:00
|
|
|
# want to support the override options that ./check supports.
|
2015-09-02 20:52:27 +02:00
|
|
|
qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
|
|
|
|
if os.environ.get('QEMU_IMG_OPTIONS'):
|
|
|
|
qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
|
|
|
|
|
|
|
|
qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
|
|
|
|
if os.environ.get('QEMU_IO_OPTIONS'):
|
|
|
|
qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
|
|
|
|
|
2016-10-25 15:11:37 +02:00
|
|
|
qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')]
|
|
|
|
if os.environ.get('QEMU_NBD_OPTIONS'):
|
|
|
|
qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ')
|
|
|
|
|
2016-07-26 18:16:07 +02:00
|
|
|
qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
|
2016-07-20 15:23:10 +02:00
|
|
|
qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
|
2012-02-29 14:25:21 +01:00
|
|
|
|
|
|
|
imgfmt = os.environ.get('IMGFMT', 'raw')
|
|
|
|
imgproto = os.environ.get('IMGPROTO', 'file')
|
2016-04-19 21:34:02 +02:00
|
|
|
test_dir = os.environ.get('TEST_DIR')
|
2014-05-24 23:24:55 +02:00
|
|
|
output_dir = os.environ.get('OUTPUT_DIR', '.')
|
2013-12-04 02:06:59 +01:00
|
|
|
cachemode = os.environ.get('CACHEMODE')
|
2015-07-03 09:28:46 +02:00
|
|
|
qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2013-09-06 05:24:33 +02:00
|
|
|
socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
|
2016-08-23 16:44:03 +02:00
|
|
|
debug = False
|
2013-09-06 05:24:33 +02:00
|
|
|
|
2018-02-06 19:25:07 +01:00
|
|
|
luks_default_secret_object = 'secret,id=keysec0,data=' + \
|
|
|
|
os.environ['IMGKEYSECRET']
|
|
|
|
luks_default_key_secret_opt = 'key-secret=keysec0'
|
|
|
|
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
def qemu_img(*args):
|
|
|
|
'''Run qemu-img and return the exit code'''
|
|
|
|
devnull = open('/dev/null', 'r+')
|
2015-09-02 20:52:28 +02:00
|
|
|
exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
|
|
|
|
return exitcode
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2018-02-06 19:25:07 +01:00
|
|
|
def qemu_img_create(*args):
|
|
|
|
args = list(args)
|
|
|
|
|
|
|
|
# default luks support
|
|
|
|
if '-f' in args and args[args.index('-f') + 1] == 'luks':
|
|
|
|
if '-o' in args:
|
|
|
|
i = args.index('-o')
|
|
|
|
if 'key-secret' not in args[i + 1]:
|
|
|
|
args[i + 1].append(luks_default_key_secret_opt)
|
|
|
|
args.insert(i + 2, '--object')
|
|
|
|
args.insert(i + 3, luks_default_secret_object)
|
|
|
|
else:
|
|
|
|
args = ['-o', luks_default_key_secret_opt,
|
|
|
|
'--object', luks_default_secret_object] + args
|
|
|
|
|
|
|
|
args.insert(0, 'create')
|
|
|
|
|
|
|
|
return qemu_img(*args)
|
|
|
|
|
2012-10-26 20:31:15 +02:00
|
|
|
def qemu_img_verbose(*args):
|
2012-11-23 07:26:04 +01:00
|
|
|
'''Run qemu-img without suppressing its output and return the exit code'''
|
2015-09-02 20:52:28 +02:00
|
|
|
exitcode = subprocess.call(qemu_img_args + list(args))
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
|
|
|
|
return exitcode
|
2012-10-26 20:31:15 +02:00
|
|
|
|
2013-10-09 10:46:20 +02:00
|
|
|
def qemu_img_pipe(*args):
|
|
|
|
'''Run qemu-img and return its output'''
|
2016-03-21 15:11:44 +01:00
|
|
|
subp = subprocess.Popen(qemu_img_args + list(args),
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT)
|
2015-09-02 20:52:28 +02:00
|
|
|
exitcode = subp.wait()
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
|
|
|
|
return subp.communicate()[0]
|
2013-10-09 10:46:20 +02:00
|
|
|
|
2018-05-23 18:19:00 +02:00
|
|
|
def img_info_log(filename, filter_path=None, imgopts=False, extra_args=[]):
|
|
|
|
args = [ 'info' ]
|
|
|
|
if imgopts:
|
|
|
|
args.append('--image-opts')
|
|
|
|
else:
|
|
|
|
args += [ '-f', imgfmt ]
|
|
|
|
args += extra_args
|
|
|
|
args.append(filename)
|
|
|
|
|
|
|
|
output = qemu_img_pipe(*args)
|
2018-05-24 13:12:56 +02:00
|
|
|
if not filter_path:
|
|
|
|
filter_path = filename
|
|
|
|
log(filter_img_info(output, filter_path))
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
def qemu_io(*args):
|
|
|
|
'''Run qemu-io and return the stdout data'''
|
|
|
|
args = qemu_io_args + list(args)
|
2016-03-21 15:11:44 +01:00
|
|
|
subp = subprocess.Popen(args, stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT)
|
2015-09-02 20:52:28 +02:00
|
|
|
exitcode = subp.wait()
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
|
|
|
|
return subp.communicate()[0]
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2018-05-09 21:43:01 +02:00
|
|
|
def qemu_io_silent(*args):
|
|
|
|
'''Run qemu-io and return the exit code, suppressing stdout'''
|
|
|
|
args = qemu_io_args + list(args)
|
|
|
|
exitcode = subprocess.call(args, stdout=open('/dev/null', 'w'))
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-io received signal %i: %s\n' %
|
|
|
|
(-exitcode, ' '.join(args)))
|
|
|
|
return exitcode
|
|
|
|
|
2018-01-19 14:57:18 +01:00
|
|
|
|
|
|
|
class QemuIoInteractive:
|
|
|
|
def __init__(self, *args):
|
|
|
|
self.args = qemu_io_args + list(args)
|
|
|
|
self._p = subprocess.Popen(self.args, stdin=subprocess.PIPE,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT)
|
|
|
|
assert self._p.stdout.read(9) == 'qemu-io> '
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
self._p.communicate('q\n')
|
|
|
|
|
|
|
|
def _read_output(self):
|
|
|
|
pattern = 'qemu-io> '
|
|
|
|
n = len(pattern)
|
|
|
|
pos = 0
|
|
|
|
s = []
|
|
|
|
while pos != n:
|
|
|
|
c = self._p.stdout.read(1)
|
|
|
|
# check unexpected EOF
|
|
|
|
assert c != ''
|
|
|
|
s.append(c)
|
|
|
|
if c == pattern[pos]:
|
|
|
|
pos += 1
|
|
|
|
else:
|
|
|
|
pos = 0
|
|
|
|
|
|
|
|
return ''.join(s[:-n])
|
|
|
|
|
|
|
|
def cmd(self, cmd):
|
|
|
|
# quit command is in close(), '\n' is added automatically
|
|
|
|
assert '\n' not in cmd
|
|
|
|
cmd = cmd.strip()
|
|
|
|
assert cmd != 'q' and cmd != 'quit'
|
|
|
|
self._p.stdin.write(cmd + '\n')
|
|
|
|
return self._read_output()
|
|
|
|
|
|
|
|
|
2016-10-25 15:11:37 +02:00
|
|
|
def qemu_nbd(*args):
|
|
|
|
'''Run qemu-nbd in daemon mode and return the parent's exit code'''
|
|
|
|
return subprocess.call(qemu_nbd_args + ['--fork'] + list(args))
|
|
|
|
|
2016-07-22 10:17:54 +02:00
|
|
|
def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
|
2013-05-28 17:11:36 +02:00
|
|
|
'''Return True if two image files are identical'''
|
2016-07-22 10:17:54 +02:00
|
|
|
return qemu_img('compare', '-f', fmt1,
|
|
|
|
'-F', fmt2, img1, img2) == 0
|
2013-05-28 17:11:36 +02:00
|
|
|
|
2013-05-28 17:11:37 +02:00
|
|
|
def create_image(name, size):
|
|
|
|
'''Create a fully-allocated raw image with sector markers'''
|
|
|
|
file = open(name, 'w')
|
|
|
|
i = 0
|
|
|
|
while i < size:
|
|
|
|
sector = struct.pack('>l504xl', i / 512, i / 512)
|
|
|
|
file.write(sector)
|
|
|
|
i = i + 512
|
|
|
|
file.close()
|
|
|
|
|
2016-04-20 04:48:35 +02:00
|
|
|
def image_size(img):
|
|
|
|
'''Return image's virtual size'''
|
|
|
|
r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img)
|
|
|
|
return json.loads(r)['virtual-size']
|
|
|
|
|
2016-03-21 15:11:46 +01:00
|
|
|
test_dir_re = re.compile(r"%s" % test_dir)
|
|
|
|
def filter_test_dir(msg):
|
|
|
|
return test_dir_re.sub("TEST_DIR", msg)
|
|
|
|
|
|
|
|
win32_re = re.compile(r"\r")
|
|
|
|
def filter_win32(msg):
|
|
|
|
return win32_re.sub("", msg)
|
|
|
|
|
|
|
|
qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
|
|
|
|
def filter_qemu_io(msg):
|
|
|
|
msg = filter_win32(msg)
|
|
|
|
return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
|
|
|
|
|
|
|
|
chown_re = re.compile(r"chown [0-9]+:[0-9]+")
|
|
|
|
def filter_chown(msg):
|
|
|
|
return chown_re.sub("chown UID:GID", msg)
|
|
|
|
|
2017-08-23 16:05:06 +02:00
|
|
|
def filter_qmp_event(event):
|
|
|
|
'''Filter a QMP event dict'''
|
|
|
|
event = dict(event)
|
|
|
|
if 'timestamp' in event:
|
|
|
|
event['timestamp']['seconds'] = 'SECS'
|
|
|
|
event['timestamp']['microseconds'] = 'USECS'
|
|
|
|
return event
|
|
|
|
|
2018-05-23 18:17:45 +02:00
|
|
|
def filter_testfiles(msg):
|
|
|
|
prefix = os.path.join(test_dir, "%s-" % (os.getpid()))
|
|
|
|
return msg.replace(prefix, 'TEST_DIR/PID-')
|
|
|
|
|
2018-05-24 13:12:56 +02:00
|
|
|
def filter_img_info(output, filename):
|
|
|
|
lines = []
|
|
|
|
for line in output.split('\n'):
|
|
|
|
if 'disk size' in line or 'actual-size' in line:
|
|
|
|
continue
|
|
|
|
line = line.replace(filename, 'TEST_IMG') \
|
|
|
|
.replace(imgfmt, 'IMGFMT')
|
|
|
|
line = re.sub('iters: [0-9]+', 'iters: XXX', line)
|
|
|
|
line = re.sub('uuid: [-a-f0-9]+', 'uuid: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', line)
|
|
|
|
lines.append(line)
|
|
|
|
return '\n'.join(lines)
|
|
|
|
|
2016-03-21 15:11:46 +01:00
|
|
|
def log(msg, filters=[]):
|
|
|
|
for flt in filters:
|
|
|
|
msg = flt(msg)
|
2018-06-08 14:29:43 +02:00
|
|
|
print(msg)
|
2016-03-21 15:11:46 +01:00
|
|
|
|
2017-07-21 16:41:21 +02:00
|
|
|
class Timeout:
|
|
|
|
def __init__(self, seconds, errmsg = "Timeout"):
|
|
|
|
self.seconds = seconds
|
|
|
|
self.errmsg = errmsg
|
|
|
|
def __enter__(self):
|
|
|
|
signal.signal(signal.SIGALRM, self.timeout)
|
|
|
|
signal.setitimer(signal.ITIMER_REAL, self.seconds)
|
|
|
|
return self
|
|
|
|
def __exit__(self, type, value, traceback):
|
|
|
|
signal.setitimer(signal.ITIMER_REAL, 0)
|
|
|
|
return False
|
|
|
|
def timeout(self, signum, frame):
|
|
|
|
raise Exception(self.errmsg)
|
|
|
|
|
2017-08-24 09:22:01 +02:00
|
|
|
|
|
|
|
class FilePath(object):
|
|
|
|
'''An auto-generated filename that cleans itself up.
|
|
|
|
|
|
|
|
Use this context manager to generate filenames and ensure that the file
|
|
|
|
gets deleted::
|
|
|
|
|
|
|
|
with TestFilePath('test.img') as img_path:
|
|
|
|
qemu_img('create', img_path, '1G')
|
|
|
|
# migration_sock_path is automatically deleted
|
|
|
|
'''
|
|
|
|
def __init__(self, name):
|
|
|
|
filename = '{0}-{1}'.format(os.getpid(), name)
|
|
|
|
self.path = os.path.join(test_dir, filename)
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self.path
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
try:
|
|
|
|
os.remove(self.path)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2018-03-12 16:21:25 +01:00
|
|
|
def file_path_remover():
|
|
|
|
for path in reversed(file_path_remover.paths):
|
|
|
|
try:
|
|
|
|
os.remove(path)
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def file_path(*names):
|
|
|
|
''' Another way to get auto-generated filename that cleans itself up.
|
|
|
|
|
|
|
|
Use is as simple as:
|
|
|
|
|
|
|
|
img_a, img_b = file_path('a.img', 'b.img')
|
|
|
|
sock = file_path('socket')
|
|
|
|
'''
|
|
|
|
|
|
|
|
if not hasattr(file_path_remover, 'paths'):
|
|
|
|
file_path_remover.paths = []
|
|
|
|
atexit.register(file_path_remover)
|
|
|
|
|
|
|
|
paths = []
|
|
|
|
for name in names:
|
|
|
|
filename = '{0}-{1}'.format(os.getpid(), name)
|
|
|
|
path = os.path.join(test_dir, filename)
|
|
|
|
file_path_remover.paths.append(path)
|
|
|
|
paths.append(path)
|
|
|
|
|
|
|
|
return paths[0] if len(paths) == 1 else paths
|
|
|
|
|
2018-05-29 21:44:47 +02:00
|
|
|
def remote_filename(path):
|
|
|
|
if imgproto == 'file':
|
|
|
|
return path
|
|
|
|
elif imgproto == 'ssh':
|
|
|
|
return "ssh://127.0.0.1%s" % (path)
|
|
|
|
else:
|
|
|
|
raise Exception("Protocol %s not supported" % (imgproto))
|
2018-03-12 16:21:25 +01:00
|
|
|
|
2016-07-26 18:16:07 +02:00
|
|
|
class VM(qtest.QEMUQtestMachine):
|
2012-02-29 14:25:21 +01:00
|
|
|
'''A QEMU VM'''
|
|
|
|
|
2016-10-25 15:11:38 +02:00
|
|
|
def __init__(self, path_suffix=''):
|
|
|
|
name = "qemu%s-%d" % (path_suffix, os.getpid())
|
|
|
|
super(VM, self).__init__(qemu_prog, qemu_opts, name=name,
|
|
|
|
test_dir=test_dir,
|
2016-07-26 18:16:07 +02:00
|
|
|
socket_scm_helper=socket_scm_helper)
|
2012-02-29 14:25:21 +01:00
|
|
|
self._num_drives = 0
|
2013-09-06 05:24:33 +02:00
|
|
|
|
2017-12-07 21:13:18 +01:00
|
|
|
def add_object(self, opts):
|
|
|
|
self._args.append('-object')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2016-09-20 13:38:49 +02:00
|
|
|
def add_device(self, opts):
|
|
|
|
self._args.append('-device')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2015-12-01 10:36:29 +01:00
|
|
|
def add_drive_raw(self, opts):
|
|
|
|
self._args.append('-drive')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2016-07-22 10:17:54 +02:00
|
|
|
def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
|
2012-02-29 14:25:21 +01:00
|
|
|
'''Add a virtio-blk drive to the VM'''
|
2015-09-02 20:52:25 +02:00
|
|
|
options = ['if=%s' % interface,
|
2012-02-29 14:25:21 +01:00
|
|
|
'id=drive%d' % self._num_drives]
|
2015-09-02 20:52:25 +02:00
|
|
|
|
|
|
|
if path is not None:
|
|
|
|
options.append('file=%s' % path)
|
2016-07-22 10:17:54 +02:00
|
|
|
options.append('format=%s' % format)
|
2015-05-07 14:41:30 +02:00
|
|
|
options.append('cache=%s' % cachemode)
|
2015-09-02 20:52:25 +02:00
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
if opts:
|
|
|
|
options.append(opts)
|
|
|
|
|
2018-02-06 19:25:07 +01:00
|
|
|
if format == 'luks' and 'key-secret' not in opts:
|
|
|
|
# default luks support
|
|
|
|
if luks_default_secret_object not in self._args:
|
|
|
|
self.add_object(luks_default_secret_object)
|
|
|
|
|
|
|
|
options.append(luks_default_key_secret_opt)
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
self._args.append('-drive')
|
|
|
|
self._args.append(','.join(options))
|
|
|
|
self._num_drives += 1
|
|
|
|
return self
|
|
|
|
|
2017-04-03 19:51:50 +02:00
|
|
|
def add_blockdev(self, opts):
|
|
|
|
self._args.append('-blockdev')
|
|
|
|
if isinstance(opts, str):
|
|
|
|
self._args.append(opts)
|
|
|
|
else:
|
|
|
|
self._args.append(','.join(opts))
|
|
|
|
return self
|
|
|
|
|
2017-08-23 16:05:06 +02:00
|
|
|
def add_incoming(self, addr):
|
|
|
|
self._args.append('-incoming')
|
|
|
|
self._args.append(addr)
|
|
|
|
return self
|
|
|
|
|
2013-11-20 03:01:55 +01:00
|
|
|
def pause_drive(self, drive, event=None):
|
|
|
|
'''Pause drive r/w operations'''
|
|
|
|
if not event:
|
|
|
|
self.pause_drive(drive, "read_aio")
|
|
|
|
self.pause_drive(drive, "write_aio")
|
|
|
|
return
|
|
|
|
self.qmp('human-monitor-command',
|
|
|
|
command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
|
|
|
|
|
|
|
|
def resume_drive(self, drive):
|
|
|
|
self.qmp('human-monitor-command',
|
|
|
|
command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
|
|
|
|
|
2013-07-26 20:39:05 +02:00
|
|
|
def hmp_qemu_io(self, drive, cmd):
|
|
|
|
'''Write to a given drive using an HMP command'''
|
|
|
|
return self.qmp('human-monitor-command',
|
|
|
|
command_line='qemu-io %s "%s"' % (drive, cmd))
|
|
|
|
|
2018-05-08 18:10:16 +02:00
|
|
|
def flatten_qmp_object(self, obj, output=None, basestr=''):
|
|
|
|
if output is None:
|
|
|
|
output = dict()
|
|
|
|
if isinstance(obj, list):
|
|
|
|
for i in range(len(obj)):
|
|
|
|
self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
|
|
|
|
elif isinstance(obj, dict):
|
|
|
|
for key in obj:
|
|
|
|
self.flatten_qmp_object(obj[key], output, basestr + key + '.')
|
|
|
|
else:
|
|
|
|
output[basestr[:-1]] = obj # Strip trailing '.'
|
|
|
|
return output
|
|
|
|
|
|
|
|
def qmp_to_opts(self, obj):
|
|
|
|
obj = self.flatten_qmp_object(obj)
|
|
|
|
output_list = list()
|
|
|
|
for key in obj:
|
|
|
|
output_list += [key + '=' + obj[key]]
|
|
|
|
return ','.join(output_list)
|
|
|
|
|
2018-05-23 17:59:46 +02:00
|
|
|
def get_qmp_events_filtered(self, wait=True):
|
|
|
|
result = []
|
|
|
|
for ev in self.get_qmp_events(wait=wait):
|
|
|
|
result.append(filter_qmp_event(ev))
|
|
|
|
return result
|
2018-05-08 18:10:16 +02:00
|
|
|
|
2018-05-23 18:17:45 +02:00
|
|
|
def qmp_log(self, cmd, filters=[filter_testfiles], **kwargs):
|
|
|
|
logmsg = "{'execute': '%s', 'arguments': %s}" % (cmd, kwargs)
|
|
|
|
log(logmsg, filters)
|
|
|
|
result = self.qmp(cmd, **kwargs)
|
|
|
|
log(str(result), filters)
|
|
|
|
return result
|
|
|
|
|
2018-05-29 20:52:57 +02:00
|
|
|
def run_job(self, job, auto_finalize=True, auto_dismiss=False):
|
|
|
|
while True:
|
|
|
|
for ev in self.get_qmp_events_filtered(wait=True):
|
|
|
|
if ev['event'] == 'JOB_STATUS_CHANGE':
|
|
|
|
status = ev['data']['status']
|
|
|
|
if status == 'aborting':
|
|
|
|
result = self.qmp('query-jobs')
|
|
|
|
for j in result['return']:
|
|
|
|
if j['id'] == job:
|
|
|
|
log('Job failed: %s' % (j['error']))
|
|
|
|
elif status == 'pending' and not auto_finalize:
|
|
|
|
self.qmp_log('job-finalize', id=job)
|
|
|
|
elif status == 'concluded' and not auto_dismiss:
|
|
|
|
self.qmp_log('job-dismiss', id=job)
|
|
|
|
elif status == 'null':
|
|
|
|
return
|
|
|
|
else:
|
|
|
|
iotests.log(ev)
|
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
|
|
|
|
|
|
|
|
class QMPTestCase(unittest.TestCase):
|
|
|
|
'''Abstract base class for QMP test cases'''
|
|
|
|
|
|
|
|
def dictpath(self, d, path):
|
|
|
|
'''Traverse a path in a nested dict'''
|
|
|
|
for component in path.split('/'):
|
|
|
|
m = index_re.match(component)
|
|
|
|
if m:
|
|
|
|
component, idx = m.groups()
|
|
|
|
idx = int(idx)
|
|
|
|
|
|
|
|
if not isinstance(d, dict) or component not in d:
|
|
|
|
self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
|
|
|
|
d = d[component]
|
|
|
|
|
|
|
|
if m:
|
|
|
|
if not isinstance(d, list):
|
|
|
|
self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
|
|
|
|
try:
|
|
|
|
d = d[idx]
|
|
|
|
except IndexError:
|
|
|
|
self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
|
|
|
|
return d
|
|
|
|
|
2012-09-28 17:23:02 +02:00
|
|
|
def assert_qmp_absent(self, d, path):
|
|
|
|
try:
|
|
|
|
result = self.dictpath(d, path)
|
|
|
|
except AssertionError:
|
|
|
|
return
|
|
|
|
self.fail('path "%s" has value "%s"' % (path, str(result)))
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
def assert_qmp(self, d, path, value):
|
|
|
|
'''Assert that the value for a specific path in a QMP dict matches'''
|
|
|
|
result = self.dictpath(d, path)
|
|
|
|
self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
|
|
|
|
|
2013-05-28 17:11:34 +02:00
|
|
|
def assert_no_active_block_jobs(self):
|
|
|
|
result = self.vm.qmp('query-block-jobs')
|
|
|
|
self.assert_qmp(result, 'return', [])
|
|
|
|
|
2016-04-13 05:43:15 +02:00
|
|
|
def assert_has_block_node(self, node_name=None, file_name=None):
|
|
|
|
"""Issue a query-named-block-nodes and assert node_name and/or
|
|
|
|
file_name is present in the result"""
|
|
|
|
def check_equal_or_none(a, b):
|
|
|
|
return a == None or b == None or a == b
|
|
|
|
assert node_name or file_name
|
|
|
|
result = self.vm.qmp('query-named-block-nodes')
|
|
|
|
for x in result["return"]:
|
|
|
|
if check_equal_or_none(x.get("node-name"), node_name) and \
|
|
|
|
check_equal_or_none(x.get("file"), file_name):
|
|
|
|
return
|
|
|
|
self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
|
|
|
|
(node_name, file_name, result))
|
|
|
|
|
2016-10-25 15:11:40 +02:00
|
|
|
def assert_json_filename_equal(self, json_filename, reference):
|
|
|
|
'''Asserts that the given filename is a json: filename and that its
|
|
|
|
content is equal to the given reference object'''
|
|
|
|
self.assertEqual(json_filename[:5], 'json:')
|
2018-05-08 18:10:16 +02:00
|
|
|
self.assertEqual(self.vm.flatten_qmp_object(json.loads(json_filename[5:])),
|
|
|
|
self.vm.flatten_qmp_object(reference))
|
2016-10-25 15:11:40 +02:00
|
|
|
|
2013-11-20 03:01:55 +01:00
|
|
|
def cancel_and_wait(self, drive='drive0', force=False, resume=False):
|
2013-05-28 17:11:35 +02:00
|
|
|
'''Cancel a block job and wait for it to finish, returning the event'''
|
|
|
|
result = self.vm.qmp('block-job-cancel', device=drive, force=force)
|
|
|
|
self.assert_qmp(result, 'return', {})
|
|
|
|
|
2013-11-20 03:01:55 +01:00
|
|
|
if resume:
|
|
|
|
self.vm.resume_drive(drive)
|
|
|
|
|
2013-05-28 17:11:35 +02:00
|
|
|
cancelled = False
|
|
|
|
result = None
|
|
|
|
while not cancelled:
|
|
|
|
for event in self.vm.get_qmp_events(wait=True):
|
|
|
|
if event['event'] == 'BLOCK_JOB_COMPLETED' or \
|
|
|
|
event['event'] == 'BLOCK_JOB_CANCELLED':
|
|
|
|
self.assert_qmp(event, 'data/device', drive)
|
|
|
|
result = event
|
|
|
|
cancelled = True
|
2018-04-30 19:09:46 +02:00
|
|
|
elif event['event'] == 'JOB_STATUS_CHANGE':
|
|
|
|
self.assert_qmp(event, 'data/id', drive)
|
|
|
|
|
2013-05-28 17:11:35 +02:00
|
|
|
|
|
|
|
self.assert_no_active_block_jobs()
|
|
|
|
return result
|
|
|
|
|
2014-04-02 07:54:07 +02:00
|
|
|
def wait_until_completed(self, drive='drive0', check_offset=True):
|
2013-06-24 17:13:19 +02:00
|
|
|
'''Wait for a block job to finish, returning the event'''
|
2018-04-08 05:05:42 +02:00
|
|
|
while True:
|
2013-06-24 17:13:19 +02:00
|
|
|
for event in self.vm.get_qmp_events(wait=True):
|
|
|
|
if event['event'] == 'BLOCK_JOB_COMPLETED':
|
|
|
|
self.assert_qmp(event, 'data/device', drive)
|
|
|
|
self.assert_qmp_absent(event, 'data/error')
|
2014-04-02 07:54:07 +02:00
|
|
|
if check_offset:
|
2014-10-24 15:57:35 +02:00
|
|
|
self.assert_qmp(event, 'data/offset', event['data']['len'])
|
2018-04-08 05:05:42 +02:00
|
|
|
self.assert_no_active_block_jobs()
|
|
|
|
return event
|
2018-04-30 19:09:46 +02:00
|
|
|
elif event['event'] == 'JOB_STATUS_CHANGE':
|
|
|
|
self.assert_qmp(event, 'data/id', drive)
|
2013-06-24 17:13:19 +02:00
|
|
|
|
2015-06-08 07:56:12 +02:00
|
|
|
def wait_ready(self, drive='drive0'):
|
|
|
|
'''Wait until a block job BLOCK_JOB_READY event'''
|
2015-06-08 07:56:14 +02:00
|
|
|
f = {'data': {'type': 'mirror', 'device': drive } }
|
|
|
|
event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
|
2015-06-08 07:56:12 +02:00
|
|
|
|
|
|
|
def wait_ready_and_cancel(self, drive='drive0'):
|
|
|
|
self.wait_ready(drive=drive)
|
|
|
|
event = self.cancel_and_wait(drive=drive)
|
|
|
|
self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
|
|
|
|
self.assert_qmp(event, 'data/type', 'mirror')
|
|
|
|
self.assert_qmp(event, 'data/offset', event['data']['len'])
|
|
|
|
|
|
|
|
def complete_and_wait(self, drive='drive0', wait_ready=True):
|
|
|
|
'''Complete a block job and wait for it to finish'''
|
|
|
|
if wait_ready:
|
|
|
|
self.wait_ready(drive=drive)
|
|
|
|
|
|
|
|
result = self.vm.qmp('block-job-complete', device=drive)
|
|
|
|
self.assert_qmp(result, 'return', {})
|
|
|
|
|
|
|
|
event = self.wait_until_completed(drive=drive)
|
|
|
|
self.assert_qmp(event, 'data/type', 'mirror')
|
|
|
|
|
2018-03-10 09:27:31 +01:00
|
|
|
def pause_wait(self, job_id='job0'):
|
2017-07-21 16:41:21 +02:00
|
|
|
with Timeout(1, "Timeout waiting for job to pause"):
|
|
|
|
while True:
|
|
|
|
result = self.vm.qmp('query-block-jobs')
|
2018-06-01 13:59:23 +02:00
|
|
|
found = False
|
2017-07-21 16:41:21 +02:00
|
|
|
for job in result['return']:
|
2018-06-01 13:59:23 +02:00
|
|
|
if job['device'] == job_id:
|
|
|
|
found = True
|
|
|
|
if job['paused'] == True and job['busy'] == False:
|
|
|
|
return job
|
|
|
|
break
|
|
|
|
assert found
|
2017-07-21 16:41:21 +02:00
|
|
|
|
2018-03-10 09:27:31 +01:00
|
|
|
def pause_job(self, job_id='job0', wait=True):
|
|
|
|
result = self.vm.qmp('block-job-pause', device=job_id)
|
|
|
|
self.assert_qmp(result, 'return', {})
|
|
|
|
if wait:
|
|
|
|
return self.pause_wait(job_id)
|
|
|
|
return result
|
|
|
|
|
2017-07-21 16:41:21 +02:00
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
def notrun(reason):
|
|
|
|
'''Skip this test suite'''
|
|
|
|
# Each test in qemu-iotests has a number ("seq")
|
|
|
|
seq = os.path.basename(sys.argv[0])
|
|
|
|
|
2014-05-24 23:24:55 +02:00
|
|
|
open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
|
2018-06-08 14:29:43 +02:00
|
|
|
print('%s not run: %s' % (seq, reason))
|
2012-02-29 14:25:21 +01:00
|
|
|
sys.exit(0)
|
|
|
|
|
2017-09-01 12:54:34 +02:00
|
|
|
def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
|
2018-04-09 13:44:17 +02:00
|
|
|
assert not (supported_fmts and unsupported_fmts)
|
|
|
|
|
|
|
|
if 'generic' in supported_fmts and \
|
|
|
|
os.environ.get('IMGFMT_GENERIC', 'true') == 'true':
|
|
|
|
# similar to
|
|
|
|
# _supported_fmt generic
|
|
|
|
# for bash tests
|
|
|
|
return
|
|
|
|
|
|
|
|
not_sup = supported_fmts and (imgfmt not in supported_fmts)
|
|
|
|
if not_sup or (imgfmt in unsupported_fmts):
|
2017-09-01 12:54:34 +02:00
|
|
|
notrun('not suitable for this image format: %s' % imgfmt)
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2018-05-29 21:44:47 +02:00
|
|
|
def verify_protocol(supported=[], unsupported=[]):
|
|
|
|
assert not (supported and unsupported)
|
|
|
|
|
|
|
|
if 'generic' in supported:
|
|
|
|
return
|
|
|
|
|
|
|
|
not_sup = supported and (imgproto not in supported)
|
|
|
|
if not_sup or (imgproto in unsupported):
|
|
|
|
notrun('not suitable for this protocol: %s' % imgproto)
|
|
|
|
|
2016-03-21 15:11:45 +01:00
|
|
|
def verify_platform(supported_oses=['linux']):
|
2015-01-16 02:38:42 +01:00
|
|
|
if True not in [sys.platform.startswith(x) for x in supported_oses]:
|
2015-01-04 02:53:52 +01:00
|
|
|
notrun('not suitable for this OS: %s' % sys.platform)
|
|
|
|
|
2018-03-13 20:34:01 +01:00
|
|
|
def verify_cache_mode(supported_cache_modes=[]):
|
|
|
|
if supported_cache_modes and (cachemode not in supported_cache_modes):
|
|
|
|
notrun('not suitable for this cache mode: %s' % cachemode)
|
|
|
|
|
2016-10-28 09:08:17 +02:00
|
|
|
def supports_quorum():
|
|
|
|
return 'quorum' in qemu_img_pipe('--help')
|
|
|
|
|
2016-04-05 11:21:46 +02:00
|
|
|
def verify_quorum():
|
|
|
|
'''Skip test suite if quorum support is not available'''
|
2016-10-28 09:08:17 +02:00
|
|
|
if not supports_quorum():
|
2016-04-05 11:21:46 +02:00
|
|
|
notrun('quorum support missing')
|
|
|
|
|
2018-03-30 17:16:35 +02:00
|
|
|
def main(supported_fmts=[], supported_oses=['linux'], supported_cache_modes=[],
|
|
|
|
unsupported_fmts=[]):
|
2016-03-21 15:11:45 +01:00
|
|
|
'''Run tests'''
|
|
|
|
|
2016-08-23 16:44:03 +02:00
|
|
|
global debug
|
|
|
|
|
2016-04-19 21:34:02 +02:00
|
|
|
# We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
|
|
|
|
# indicate that we're not being run via "check". There may be
|
|
|
|
# other things set up by "check" that individual test cases rely
|
|
|
|
# on.
|
|
|
|
if test_dir is None or qemu_default_machine is None:
|
|
|
|
sys.stderr.write('Please run this test via the "check" script\n')
|
|
|
|
sys.exit(os.EX_USAGE)
|
|
|
|
|
2016-03-21 15:11:45 +01:00
|
|
|
debug = '-d' in sys.argv
|
|
|
|
verbosity = 1
|
2018-03-30 17:16:35 +02:00
|
|
|
verify_image_format(supported_fmts, unsupported_fmts)
|
2016-03-21 15:11:45 +01:00
|
|
|
verify_platform(supported_oses)
|
2018-03-13 20:34:01 +01:00
|
|
|
verify_cache_mode(supported_cache_modes)
|
2016-03-21 15:11:45 +01:00
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
# We need to filter out the time taken from the output so that qemu-iotest
|
|
|
|
# can reliably diff the results against master output.
|
|
|
|
import StringIO
|
2015-05-18 03:39:12 +02:00
|
|
|
if debug:
|
|
|
|
output = sys.stdout
|
|
|
|
verbosity = 2
|
|
|
|
sys.argv.remove('-d')
|
|
|
|
else:
|
|
|
|
output = StringIO.StringIO()
|
2012-02-29 14:25:21 +01:00
|
|
|
|
2017-09-27 15:03:36 +02:00
|
|
|
logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
|
|
|
|
|
2012-02-29 14:25:21 +01:00
|
|
|
class MyTestRunner(unittest.TextTestRunner):
|
2015-05-18 03:39:12 +02:00
|
|
|
def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
|
2012-02-29 14:25:21 +01:00
|
|
|
unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
|
|
|
|
|
|
|
|
# unittest.main() will use sys.exit() so expect a SystemExit exception
|
|
|
|
try:
|
|
|
|
unittest.main(testRunner=MyTestRunner)
|
|
|
|
finally:
|
2015-05-18 03:39:12 +02:00
|
|
|
if not debug:
|
|
|
|
sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
|