2018-06-08 15:29:43 +03:00
|
|
|
from __future__ import print_function
|
2012-02-29 17:25:21 +04: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 12:21:45 +03:00
|
|
|
import errno
|
2012-02-29 17:25:21 +04:00
|
|
|
import os
|
|
|
|
import re
|
|
|
|
import subprocess
|
2012-09-28 19:23:01 +04:00
|
|
|
import string
|
2012-02-29 17:25:21 +04:00
|
|
|
import unittest
|
2015-01-30 05:49:44 +03:00
|
|
|
import sys
|
2013-05-28 19:11:37 +04:00
|
|
|
import struct
|
2016-04-20 05:48:35 +03:00
|
|
|
import json
|
2017-07-21 17:41:21 +03:00
|
|
|
import signal
|
2017-09-27 16:03:36 +03:00
|
|
|
import logging
|
2018-03-12 18:21:25 +03:00
|
|
|
import atexit
|
2018-10-22 16:53:06 +03:00
|
|
|
import io
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
from collections import OrderedDict
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2019-02-06 19:29:01 +03:00
|
|
|
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python'))
|
|
|
|
from qemu import qtest
|
2018-03-12 18:21:24 +03:00
|
|
|
|
2019-09-19 19:18:31 +03:00
|
|
|
assert sys.version_info >= (3,6)
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2015-09-02 21:52:27 +03:00
|
|
|
# This will not work if arguments contain spaces but is necessary if we
|
2012-02-29 17:25:21 +04:00
|
|
|
# want to support the override options that ./check supports.
|
2015-09-02 21:52:27 +03: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 16:11:37 +03: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 19:16:07 +03:00
|
|
|
qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
|
2016-07-20 16:23:10 +03:00
|
|
|
qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
|
2012-02-29 17:25:21 +04:00
|
|
|
|
|
|
|
imgfmt = os.environ.get('IMGFMT', 'raw')
|
|
|
|
imgproto = os.environ.get('IMGPROTO', 'file')
|
2016-04-19 22:34:02 +03:00
|
|
|
test_dir = os.environ.get('TEST_DIR')
|
2014-05-25 01:24:55 +04:00
|
|
|
output_dir = os.environ.get('OUTPUT_DIR', '.')
|
2013-12-04 05:06:59 +04:00
|
|
|
cachemode = os.environ.get('CACHEMODE')
|
2015-07-03 10:28:46 +03:00
|
|
|
qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2013-09-06 07:24:33 +04:00
|
|
|
socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
|
|
|
|
|
2018-02-06 21:25:07 +03:00
|
|
|
luks_default_secret_object = 'secret,id=keysec0,data=' + \
|
2018-12-21 12:35:23 +03:00
|
|
|
os.environ.get('IMGKEYSECRET', '')
|
2018-02-06 21:25:07 +03:00
|
|
|
luks_default_key_secret_opt = 'key-secret=keysec0'
|
|
|
|
|
|
|
|
|
2012-02-29 17:25:21 +04:00
|
|
|
def qemu_img(*args):
|
|
|
|
'''Run qemu-img and return the exit code'''
|
|
|
|
devnull = open('/dev/null', 'r+')
|
2015-09-02 21:52:28 +03: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 17:25:21 +04:00
|
|
|
|
2019-02-10 17:57:36 +03:00
|
|
|
def ordered_qmp(qmsg, conv_keys=True):
|
2019-01-31 05:26:48 +03:00
|
|
|
# Dictionaries are not ordered prior to 3.6, therefore:
|
|
|
|
if isinstance(qmsg, list):
|
|
|
|
return [ordered_qmp(atom) for atom in qmsg]
|
|
|
|
if isinstance(qmsg, dict):
|
|
|
|
od = OrderedDict()
|
|
|
|
for k, v in sorted(qmsg.items()):
|
2019-02-10 17:57:36 +03:00
|
|
|
if conv_keys:
|
|
|
|
k = k.replace('_', '-')
|
|
|
|
od[k] = ordered_qmp(v, conv_keys=False)
|
2019-01-31 05:26:48 +03:00
|
|
|
return od
|
|
|
|
return qmsg
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
|
2018-02-06 21:25:07 +03: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 22:31:15 +04:00
|
|
|
def qemu_img_verbose(*args):
|
2012-11-23 10:26:04 +04:00
|
|
|
'''Run qemu-img without suppressing its output and return the exit code'''
|
2015-09-02 21:52:28 +03: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 22:31:15 +04:00
|
|
|
|
2013-10-09 12:46:20 +04:00
|
|
|
def qemu_img_pipe(*args):
|
|
|
|
'''Run qemu-img and return its output'''
|
2016-03-21 17:11:44 +03:00
|
|
|
subp = subprocess.Popen(qemu_img_args + list(args),
|
|
|
|
stdout=subprocess.PIPE,
|
2018-10-22 16:53:01 +03:00
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True)
|
2015-09-02 21:52:28 +03: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 12:46:20 +04:00
|
|
|
|
2019-05-21 21:35:52 +03:00
|
|
|
def qemu_img_log(*args):
|
|
|
|
result = qemu_img_pipe(*args)
|
|
|
|
log(result, filters=[filter_testfiles])
|
|
|
|
return result
|
|
|
|
|
2018-05-23 19:19:00 +03: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 14:12:56 +03:00
|
|
|
if not filter_path:
|
|
|
|
filter_path = filename
|
|
|
|
log(filter_img_info(output, filter_path))
|
|
|
|
|
2012-02-29 17:25:21 +04:00
|
|
|
def qemu_io(*args):
|
|
|
|
'''Run qemu-io and return the stdout data'''
|
|
|
|
args = qemu_io_args + list(args)
|
2016-03-21 17:11:44 +03:00
|
|
|
subp = subprocess.Popen(args, stdout=subprocess.PIPE,
|
2018-10-22 16:53:01 +03:00
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True)
|
2015-09-02 21:52:28 +03: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 17:25:21 +04:00
|
|
|
|
2018-05-09 22:43:01 +03: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
|
|
|
|
|
2019-07-29 23:35:54 +03:00
|
|
|
def get_virtio_scsi_device():
|
|
|
|
if qemu_default_machine == 's390-ccw-virtio':
|
|
|
|
return 'virtio-scsi-ccw'
|
|
|
|
return 'virtio-scsi-pci'
|
2018-01-19 16:57:18 +03: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,
|
2018-10-22 16:53:01 +03:00
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True)
|
2018-01-19 16:57:18 +03:00
|
|
|
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')
|
2018-10-22 16:53:00 +03:00
|
|
|
self._p.stdin.flush()
|
2018-01-19 16:57:18 +03:00
|
|
|
return self._read_output()
|
|
|
|
|
|
|
|
|
2016-10-25 16:11:37 +03: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))
|
|
|
|
|
2019-05-09 00:18:17 +03:00
|
|
|
def qemu_nbd_early_pipe(*args):
|
2018-12-22 02:47:48 +03:00
|
|
|
'''Run qemu-nbd in daemon mode and return both the parent's exit code
|
2019-05-09 00:18:17 +03:00
|
|
|
and its output in case of an error'''
|
2018-12-22 02:47:48 +03:00
|
|
|
subp = subprocess.Popen(qemu_nbd_args + ['--fork'] + list(args),
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True)
|
|
|
|
exitcode = subp.wait()
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu-nbd received signal %i: %s\n' %
|
|
|
|
(-exitcode,
|
|
|
|
' '.join(qemu_nbd_args + ['--fork'] + list(args))))
|
2019-05-09 00:18:17 +03:00
|
|
|
if exitcode == 0:
|
|
|
|
return exitcode, ''
|
|
|
|
else:
|
|
|
|
return exitcode, subp.communicate()[0]
|
2018-12-22 02:47:48 +03:00
|
|
|
|
2016-07-22 11:17:54 +03:00
|
|
|
def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
|
2013-05-28 19:11:36 +04:00
|
|
|
'''Return True if two image files are identical'''
|
2016-07-22 11:17:54 +03:00
|
|
|
return qemu_img('compare', '-f', fmt1,
|
|
|
|
'-F', fmt2, img1, img2) == 0
|
2013-05-28 19:11:36 +04:00
|
|
|
|
2013-05-28 19:11:37 +04:00
|
|
|
def create_image(name, size):
|
|
|
|
'''Create a fully-allocated raw image with sector markers'''
|
2018-10-22 16:53:01 +03:00
|
|
|
file = open(name, 'wb')
|
2013-05-28 19:11:37 +04:00
|
|
|
i = 0
|
|
|
|
while i < size:
|
2018-10-22 16:53:02 +03:00
|
|
|
sector = struct.pack('>l504xl', i // 512, i // 512)
|
2013-05-28 19:11:37 +04:00
|
|
|
file.write(sector)
|
|
|
|
i = i + 512
|
|
|
|
file.close()
|
|
|
|
|
2016-04-20 05:48:35 +03: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']
|
|
|
|
|
2019-02-10 17:57:32 +03:00
|
|
|
def is_str(val):
|
2019-09-19 19:18:31 +03:00
|
|
|
return isinstance(val, str)
|
2019-02-10 17:57:32 +03:00
|
|
|
|
2016-03-21 17:11:46 +03: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 17:05:06 +03: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-12-21 12:35:27 +03:00
|
|
|
def filter_qmp(qmsg, filter_fn):
|
|
|
|
'''Given a string filter, filter a QMP object's values.
|
|
|
|
filter_fn takes a (key, value) pair.'''
|
|
|
|
# Iterate through either lists or dicts;
|
|
|
|
if isinstance(qmsg, list):
|
|
|
|
items = enumerate(qmsg)
|
|
|
|
else:
|
|
|
|
items = qmsg.items()
|
|
|
|
|
|
|
|
for k, v in items:
|
|
|
|
if isinstance(v, list) or isinstance(v, dict):
|
|
|
|
qmsg[k] = filter_qmp(v, filter_fn)
|
|
|
|
else:
|
|
|
|
qmsg[k] = filter_fn(k, v)
|
|
|
|
return qmsg
|
|
|
|
|
2018-05-23 19:17:45 +03:00
|
|
|
def filter_testfiles(msg):
|
|
|
|
prefix = os.path.join(test_dir, "%s-" % (os.getpid()))
|
|
|
|
return msg.replace(prefix, 'TEST_DIR/PID-')
|
|
|
|
|
2018-12-21 12:35:27 +03:00
|
|
|
def filter_qmp_testfiles(qmsg):
|
|
|
|
def _filter(key, value):
|
2019-02-10 17:57:33 +03:00
|
|
|
if is_str(value):
|
2018-12-21 12:35:27 +03:00
|
|
|
return filter_testfiles(value)
|
|
|
|
return value
|
|
|
|
return filter_qmp(qmsg, _filter)
|
|
|
|
|
2018-12-21 12:35:24 +03:00
|
|
|
def filter_generated_node_ids(msg):
|
|
|
|
return re.sub("#block[0-9]+", "NODE_NAME", msg)
|
|
|
|
|
2018-05-24 14:12:56 +03: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)
|
2018-05-15 18:36:33 +03:00
|
|
|
line = re.sub('cid: [0-9]+', 'cid: XXXXXXXXXX', line)
|
2018-05-24 14:12:56 +03:00
|
|
|
lines.append(line)
|
|
|
|
return '\n'.join(lines)
|
|
|
|
|
2019-02-01 22:29:10 +03:00
|
|
|
def filter_imgfmt(msg):
|
|
|
|
return msg.replace(imgfmt, 'IMGFMT')
|
|
|
|
|
|
|
|
def filter_qmp_imgfmt(qmsg):
|
|
|
|
def _filter(key, value):
|
|
|
|
if is_str(value):
|
|
|
|
return filter_imgfmt(value)
|
|
|
|
return value
|
|
|
|
return filter_qmp(qmsg, _filter)
|
|
|
|
|
2018-12-21 12:35:28 +03:00
|
|
|
def log(msg, filters=[], indent=None):
|
|
|
|
'''Logs either a string message or a JSON serializable message (like QMP).
|
|
|
|
If indent is provided, JSON serializable messages are pretty-printed.'''
|
2016-03-21 17:11:46 +03:00
|
|
|
for flt in filters:
|
|
|
|
msg = flt(msg)
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
if isinstance(msg, dict) or isinstance(msg, list):
|
2018-12-21 12:35:28 +03:00
|
|
|
# Python < 3.4 needs to know not to add whitespace when pretty-printing:
|
|
|
|
separators = (', ', ': ') if indent is None else (',', ': ')
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
# Don't sort if it's already sorted
|
|
|
|
do_sort = not isinstance(msg, OrderedDict)
|
2018-12-21 12:35:28 +03:00
|
|
|
print(json.dumps(msg, sort_keys=do_sort,
|
|
|
|
indent=indent, separators=separators))
|
iotests: Unify log outputs between Python 2 and 3
When dumping an object into the log, there are differences between
Python 2 and 3. First, unicode strings are prefixed by 'u' in Python 2
(they are no longer in 3, because unicode strings are the default
there). Second, the order of keys in dicts may differ. Third,
especially long numbers are longs in Python 2 and thus get an 'L'
suffix, which does not happen in Python 3.
We can get around all of these differences by dumping objects (lists and
dicts) in a language-independent format, namely JSON. The JSON
generator even allows emitting dicts with their keys sorted
alphabetically.
This changes the output of all tests that use these logging functions
(dict keys are ordered now, strings in dicts are now enclosed in double
quotes instead of single quotes, the 'L' suffix of large integers is
dropped, and "true" and "false" are now in lower case).
The quote change necessitates a small change to a filter used in test
207.
Suggested-by: Eduardo Habkost <ehabkost@redhat.com>
Signed-off-by: Max Reitz <mreitz@redhat.com>
Reviewed-by: Cleber Rosa <crosa@redhat.com>
Message-Id: <20181022135307.14398-10-mreitz@redhat.com>
Signed-off-by: Eduardo Habkost <ehabkost@redhat.com>
2018-10-22 16:53:07 +03:00
|
|
|
else:
|
|
|
|
print(msg)
|
2016-03-21 17:11:46 +03:00
|
|
|
|
2017-07-21 17:41:21 +03: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)
|
|
|
|
|
2019-07-29 23:35:54 +03:00
|
|
|
def file_pattern(name):
|
|
|
|
return "{0}-{1}".format(os.getpid(), name)
|
2017-08-24 10:22:01 +03:00
|
|
|
|
2019-07-29 23:35:54 +03:00
|
|
|
class FilePaths(object):
|
|
|
|
"""
|
|
|
|
FilePaths is an auto-generated filename that cleans itself up.
|
2017-08-24 10:22:01 +03:00
|
|
|
|
|
|
|
Use this context manager to generate filenames and ensure that the file
|
|
|
|
gets deleted::
|
|
|
|
|
2019-07-29 23:35:54 +03:00
|
|
|
with FilePaths(['test.img']) as img_path:
|
2017-08-24 10:22:01 +03:00
|
|
|
qemu_img('create', img_path, '1G')
|
|
|
|
# migration_sock_path is automatically deleted
|
2019-07-29 23:35:54 +03:00
|
|
|
"""
|
|
|
|
def __init__(self, names):
|
|
|
|
self.paths = []
|
|
|
|
for name in names:
|
|
|
|
self.paths.append(os.path.join(test_dir, file_pattern(name)))
|
2017-08-24 10:22:01 +03:00
|
|
|
|
|
|
|
def __enter__(self):
|
2019-07-29 23:35:54 +03:00
|
|
|
return self.paths
|
2017-08-24 10:22:01 +03:00
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
try:
|
2019-07-29 23:35:54 +03:00
|
|
|
for path in self.paths:
|
|
|
|
os.remove(path)
|
2017-08-24 10:22:01 +03:00
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
return False
|
|
|
|
|
2019-07-29 23:35:54 +03:00
|
|
|
class FilePath(FilePaths):
|
|
|
|
"""
|
|
|
|
FilePath is a specialization of FilePaths that takes a single filename.
|
|
|
|
"""
|
|
|
|
def __init__(self, name):
|
|
|
|
super(FilePath, self).__init__([name])
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self.paths[0]
|
2017-08-24 10:22:01 +03:00
|
|
|
|
2018-03-12 18:21:25 +03: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:
|
2019-07-29 23:35:54 +03:00
|
|
|
filename = file_pattern(name)
|
2018-03-12 18:21:25 +03:00
|
|
|
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 22:44:47 +03:00
|
|
|
def remote_filename(path):
|
|
|
|
if imgproto == 'file':
|
|
|
|
return path
|
|
|
|
elif imgproto == 'ssh':
|
2019-02-25 22:08:27 +03:00
|
|
|
return "ssh://%s@127.0.0.1:22%s" % (os.environ.get('USER'), path)
|
2018-05-29 22:44:47 +03:00
|
|
|
else:
|
|
|
|
raise Exception("Protocol %s not supported" % (imgproto))
|
2018-03-12 18:21:25 +03:00
|
|
|
|
2016-07-26 19:16:07 +03:00
|
|
|
class VM(qtest.QEMUQtestMachine):
|
2012-02-29 17:25:21 +04:00
|
|
|
'''A QEMU VM'''
|
|
|
|
|
2016-10-25 16:11:38 +03: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 19:16:07 +03:00
|
|
|
socket_scm_helper=socket_scm_helper)
|
2012-02-29 17:25:21 +04:00
|
|
|
self._num_drives = 0
|
2013-09-06 07:24:33 +04:00
|
|
|
|
2017-12-07 23:13:18 +03:00
|
|
|
def add_object(self, opts):
|
|
|
|
self._args.append('-object')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2016-09-20 14:38:49 +03:00
|
|
|
def add_device(self, opts):
|
|
|
|
self._args.append('-device')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2015-12-01 12:36:29 +03:00
|
|
|
def add_drive_raw(self, opts):
|
|
|
|
self._args.append('-drive')
|
|
|
|
self._args.append(opts)
|
|
|
|
return self
|
|
|
|
|
2016-07-22 11:17:54 +03:00
|
|
|
def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
|
2012-02-29 17:25:21 +04:00
|
|
|
'''Add a virtio-blk drive to the VM'''
|
2015-09-02 21:52:25 +03:00
|
|
|
options = ['if=%s' % interface,
|
2012-02-29 17:25:21 +04:00
|
|
|
'id=drive%d' % self._num_drives]
|
2015-09-02 21:52:25 +03:00
|
|
|
|
|
|
|
if path is not None:
|
|
|
|
options.append('file=%s' % path)
|
2016-07-22 11:17:54 +03:00
|
|
|
options.append('format=%s' % format)
|
2015-05-07 15:41:30 +03:00
|
|
|
options.append('cache=%s' % cachemode)
|
2015-09-02 21:52:25 +03:00
|
|
|
|
2012-02-29 17:25:21 +04:00
|
|
|
if opts:
|
|
|
|
options.append(opts)
|
|
|
|
|
2018-02-06 21:25:07 +03: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 17:25:21 +04:00
|
|
|
self._args.append('-drive')
|
|
|
|
self._args.append(','.join(options))
|
|
|
|
self._num_drives += 1
|
|
|
|
return self
|
|
|
|
|
2017-04-03 20:51:50 +03: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 17:05:06 +03:00
|
|
|
def add_incoming(self, addr):
|
|
|
|
self._args.append('-incoming')
|
|
|
|
self._args.append(addr)
|
|
|
|
return self
|
|
|
|
|
2013-11-20 06:01:55 +04: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 22:39:05 +04: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 19:10:16 +03: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)
|
|
|
|
|
2019-05-23 20:06:40 +03:00
|
|
|
def get_qmp_events_filtered(self, wait=60.0):
|
2018-05-23 18:59:46 +03:00
|
|
|
result = []
|
|
|
|
for ev in self.get_qmp_events(wait=wait):
|
|
|
|
result.append(filter_qmp_event(ev))
|
|
|
|
return result
|
2018-05-08 19:10:16 +03:00
|
|
|
|
2018-12-21 12:35:28 +03:00
|
|
|
def qmp_log(self, cmd, filters=[], indent=None, **kwargs):
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
full_cmd = OrderedDict((
|
|
|
|
("execute", cmd),
|
2019-01-31 05:26:48 +03:00
|
|
|
("arguments", ordered_qmp(kwargs))
|
iotests: add qmp recursive sorting function
Python before 3.6 does not sort dictionaries (including kwargs).
Therefore, printing QMP objects involves sorting the keys to have
a predictable ordering in the iotests output. This means that
iotests output will sometimes show arguments in an order not
specified by the test author.
Presently, we accomplish this by using json.dumps' sort_keys argument,
where we only serialize the arguments dictionary, but not the command.
However, if we want to pretty-print QMP objects being sent to the
QEMU process, we need to build the entire command before logging it.
Ordinarily, this would then involve "arguments" being sorted above
"execute", which would necessitate a rather ugly and harder-to-read
change to many iotests outputs.
To facilitate pretty-printing AND maintaining predictable output AND
having "arguments" sort after "execute", add a custom sort function
that takes a dictionary and recursively builds an OrderedDict that
maintains the specific key order we wish to see in iotests output.
The qmp_log function uses this to build a QMP object that keeps
"execute" above "arguments", but sorts all keys and keys in any
subdicts in "arguments" lexicographically to maintain consistent
iotests output, with no incompatible changes to any current test.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Reviewed-by: Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
Message-Id: <20181221093529.23855-8-jsnow@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2018-12-21 12:35:25 +03:00
|
|
|
))
|
2018-12-21 12:35:28 +03:00
|
|
|
log(full_cmd, filters, indent=indent)
|
2018-05-23 19:17:45 +03:00
|
|
|
result = self.qmp(cmd, **kwargs)
|
2018-12-21 12:35:28 +03:00
|
|
|
log(result, filters, indent=indent)
|
2018-05-23 19:17:45 +03:00
|
|
|
return result
|
|
|
|
|
2019-02-18 21:06:46 +03:00
|
|
|
# Returns None on success, and an error string on failure
|
2019-05-21 21:35:52 +03:00
|
|
|
def run_job(self, job, auto_finalize=True, auto_dismiss=False,
|
2019-07-29 23:35:53 +03:00
|
|
|
pre_finalize=None, cancel=False, use_log=True, wait=60.0):
|
|
|
|
"""
|
|
|
|
run_job moves a job from creation through to dismissal.
|
|
|
|
|
|
|
|
:param job: String. ID of recently-launched job
|
|
|
|
:param auto_finalize: Bool. True if the job was launched with
|
|
|
|
auto_finalize. Defaults to True.
|
|
|
|
:param auto_dismiss: Bool. True if the job was launched with
|
|
|
|
auto_dismiss=True. Defaults to False.
|
|
|
|
:param pre_finalize: Callback. A callable that takes no arguments to be
|
|
|
|
invoked prior to issuing job-finalize, if any.
|
|
|
|
:param cancel: Bool. When true, cancels the job after the pre_finalize
|
|
|
|
callback.
|
|
|
|
:param use_log: Bool. When false, does not log QMP messages.
|
|
|
|
:param wait: Float. Timeout value specifying how long to wait for any
|
|
|
|
event, in seconds. Defaults to 60.0.
|
|
|
|
"""
|
2019-05-23 20:06:42 +03:00
|
|
|
match_device = {'data': {'device': job}}
|
|
|
|
match_id = {'data': {'id': job}}
|
|
|
|
events = [
|
|
|
|
('BLOCK_JOB_COMPLETED', match_device),
|
|
|
|
('BLOCK_JOB_CANCELLED', match_device),
|
|
|
|
('BLOCK_JOB_ERROR', match_device),
|
|
|
|
('BLOCK_JOB_READY', match_device),
|
|
|
|
('BLOCK_JOB_PENDING', match_id),
|
|
|
|
('JOB_STATUS_CHANGE', match_id)
|
|
|
|
]
|
2019-02-18 21:06:46 +03:00
|
|
|
error = None
|
2018-05-29 21:52:57 +03:00
|
|
|
while True:
|
2019-05-23 20:06:42 +03:00
|
|
|
ev = filter_qmp_event(self.events_wait(events))
|
|
|
|
if ev['event'] != 'JOB_STATUS_CHANGE':
|
2019-07-03 20:28:10 +03:00
|
|
|
if use_log:
|
|
|
|
log(ev)
|
2019-05-23 20:06:42 +03:00
|
|
|
continue
|
|
|
|
status = ev['data']['status']
|
|
|
|
if status == 'aborting':
|
|
|
|
result = self.qmp('query-jobs')
|
|
|
|
for j in result['return']:
|
|
|
|
if j['id'] == job:
|
|
|
|
error = j['error']
|
2019-07-03 20:28:10 +03:00
|
|
|
if use_log:
|
|
|
|
log('Job failed: %s' % (j['error']))
|
2019-05-23 20:06:42 +03:00
|
|
|
elif status == 'pending' and not auto_finalize:
|
|
|
|
if pre_finalize:
|
|
|
|
pre_finalize()
|
2019-07-29 23:35:53 +03:00
|
|
|
if cancel and use_log:
|
|
|
|
self.qmp_log('job-cancel', id=job)
|
|
|
|
elif cancel:
|
|
|
|
self.qmp('job-cancel', id=job)
|
|
|
|
elif use_log:
|
2019-07-03 20:28:10 +03:00
|
|
|
self.qmp_log('job-finalize', id=job)
|
|
|
|
else:
|
|
|
|
self.qmp('job-finalize', id=job)
|
2019-05-23 20:06:42 +03:00
|
|
|
elif status == 'concluded' and not auto_dismiss:
|
2019-07-03 20:28:10 +03:00
|
|
|
if use_log:
|
|
|
|
self.qmp_log('job-dismiss', id=job)
|
|
|
|
else:
|
|
|
|
self.qmp('job-dismiss', id=job)
|
2019-05-23 20:06:42 +03:00
|
|
|
elif status == 'null':
|
|
|
|
return error
|
2018-05-29 21:52:57 +03:00
|
|
|
|
2019-08-01 14:14:09 +03:00
|
|
|
def enable_migration_events(self, name):
|
|
|
|
log('Enabling migration QMP events on %s...' % name)
|
|
|
|
log(self.qmp('migrate-set-capabilities', capabilities=[
|
|
|
|
{
|
|
|
|
'capability': 'events',
|
|
|
|
'state': True
|
|
|
|
}
|
|
|
|
]))
|
|
|
|
|
|
|
|
def wait_migration(self):
|
|
|
|
while True:
|
|
|
|
event = self.event_wait('MIGRATION')
|
|
|
|
log(event, filters=[filter_qmp_event])
|
|
|
|
if event['data']['status'] == 'completed':
|
|
|
|
break
|
|
|
|
|
2019-02-01 22:29:11 +03:00
|
|
|
def node_info(self, node_name):
|
|
|
|
nodes = self.qmp('query-named-block-nodes')
|
|
|
|
for x in nodes['return']:
|
|
|
|
if x['node-name'] == node_name:
|
|
|
|
return x
|
|
|
|
return None
|
|
|
|
|
2015-04-18 02:50:06 +03:00
|
|
|
|
2012-02-29 17:25:21 +04: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 19:23:02 +04: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 17:25:21 +04:00
|
|
|
def assert_qmp(self, d, path, value):
|
2019-05-15 23:15:01 +03:00
|
|
|
'''Assert that the value for a specific path in a QMP dict
|
|
|
|
matches. When given a list of values, assert that any of
|
|
|
|
them matches.'''
|
|
|
|
|
2012-02-29 17:25:21 +04:00
|
|
|
result = self.dictpath(d, path)
|
2019-05-15 23:15:01 +03:00
|
|
|
|
|
|
|
# [] makes no sense as a list of valid values, so treat it as
|
|
|
|
# an actual single value.
|
|
|
|
if isinstance(value, list) and value != []:
|
|
|
|
for v in value:
|
|
|
|
if result == v:
|
|
|
|
return
|
|
|
|
self.fail('no match for "%s" in %s' % (str(result), str(value)))
|
|
|
|
else:
|
|
|
|
self.assertEqual(result, value,
|
|
|
|
'values not equal "%s" and "%s"'
|
|
|
|
% (str(result), str(value)))
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2013-05-28 19:11:34 +04:00
|
|
|
def assert_no_active_block_jobs(self):
|
|
|
|
result = self.vm.qmp('query-block-jobs')
|
|
|
|
self.assert_qmp(result, 'return', [])
|
|
|
|
|
2016-04-13 06:43:15 +03: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 16:11:40 +03: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 19:10:16 +03:00
|
|
|
self.assertEqual(self.vm.flatten_qmp_object(json.loads(json_filename[5:])),
|
|
|
|
self.vm.flatten_qmp_object(reference))
|
2016-10-25 16:11:40 +03:00
|
|
|
|
2019-05-23 20:06:40 +03:00
|
|
|
def cancel_and_wait(self, drive='drive0', force=False, resume=False, wait=60.0):
|
2013-05-28 19:11:35 +04: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 06:01:55 +04:00
|
|
|
if resume:
|
|
|
|
self.vm.resume_drive(drive)
|
|
|
|
|
2013-05-28 19:11:35 +04:00
|
|
|
cancelled = False
|
|
|
|
result = None
|
|
|
|
while not cancelled:
|
2019-05-23 20:06:40 +03:00
|
|
|
for event in self.vm.get_qmp_events(wait=wait):
|
2013-05-28 19:11:35 +04:00
|
|
|
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 20:09:46 +03:00
|
|
|
elif event['event'] == 'JOB_STATUS_CHANGE':
|
|
|
|
self.assert_qmp(event, 'data/id', drive)
|
|
|
|
|
2013-05-28 19:11:35 +04:00
|
|
|
|
|
|
|
self.assert_no_active_block_jobs()
|
|
|
|
return result
|
|
|
|
|
2019-05-23 20:06:40 +03:00
|
|
|
def wait_until_completed(self, drive='drive0', check_offset=True, wait=60.0):
|
2013-06-24 19:13:19 +04:00
|
|
|
'''Wait for a block job to finish, returning the event'''
|
2018-04-08 06:05:42 +03:00
|
|
|
while True:
|
2019-05-23 20:06:40 +03:00
|
|
|
for event in self.vm.get_qmp_events(wait=wait):
|
2013-06-24 19:13:19 +04:00
|
|
|
if event['event'] == 'BLOCK_JOB_COMPLETED':
|
|
|
|
self.assert_qmp(event, 'data/device', drive)
|
|
|
|
self.assert_qmp_absent(event, 'data/error')
|
2014-04-02 09:54:07 +04:00
|
|
|
if check_offset:
|
2014-10-24 17:57:35 +04:00
|
|
|
self.assert_qmp(event, 'data/offset', event['data']['len'])
|
2018-04-08 06:05:42 +03:00
|
|
|
self.assert_no_active_block_jobs()
|
|
|
|
return event
|
2018-04-30 20:09:46 +03:00
|
|
|
elif event['event'] == 'JOB_STATUS_CHANGE':
|
|
|
|
self.assert_qmp(event, 'data/id', drive)
|
2013-06-24 19:13:19 +04:00
|
|
|
|
2015-06-08 08:56:12 +03:00
|
|
|
def wait_ready(self, drive='drive0'):
|
|
|
|
'''Wait until a block job BLOCK_JOB_READY event'''
|
2015-06-08 08:56:14 +03:00
|
|
|
f = {'data': {'type': 'mirror', 'device': drive } }
|
|
|
|
event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
|
2015-06-08 08:56:12 +03:00
|
|
|
|
|
|
|
def wait_ready_and_cancel(self, drive='drive0'):
|
|
|
|
self.wait_ready(drive=drive)
|
|
|
|
event = self.cancel_and_wait(drive=drive)
|
2018-11-20 20:12:21 +03:00
|
|
|
self.assertEqual(event['event'], 'BLOCK_JOB_COMPLETED')
|
2015-06-08 08:56:12 +03:00
|
|
|
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 11:27:31 +03:00
|
|
|
def pause_wait(self, job_id='job0'):
|
2017-07-21 17:41:21 +03:00
|
|
|
with Timeout(1, "Timeout waiting for job to pause"):
|
|
|
|
while True:
|
|
|
|
result = self.vm.qmp('query-block-jobs')
|
2018-06-01 14:59:23 +03:00
|
|
|
found = False
|
2017-07-21 17:41:21 +03:00
|
|
|
for job in result['return']:
|
2018-06-01 14:59:23 +03:00
|
|
|
if job['device'] == job_id:
|
|
|
|
found = True
|
|
|
|
if job['paused'] == True and job['busy'] == False:
|
|
|
|
return job
|
|
|
|
break
|
|
|
|
assert found
|
2017-07-21 17:41:21 +03:00
|
|
|
|
2018-03-10 11:27:31 +03: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 17:41:21 +03:00
|
|
|
|
2012-02-29 17:25:21 +04:00
|
|
|
def notrun(reason):
|
|
|
|
'''Skip this test suite'''
|
|
|
|
# Each test in qemu-iotests has a number ("seq")
|
|
|
|
seq = os.path.basename(sys.argv[0])
|
|
|
|
|
2019-03-07 16:33:57 +03:00
|
|
|
open('%s/%s.notrun' % (output_dir, seq), 'w').write(reason + '\n')
|
2018-06-08 15:29:43 +03:00
|
|
|
print('%s not run: %s' % (seq, reason))
|
2012-02-29 17:25:21 +04:00
|
|
|
sys.exit(0)
|
|
|
|
|
2019-03-07 16:33:59 +03:00
|
|
|
def case_notrun(reason):
|
|
|
|
'''Skip this test case'''
|
|
|
|
# Each test in qemu-iotests has a number ("seq")
|
|
|
|
seq = os.path.basename(sys.argv[0])
|
|
|
|
|
|
|
|
open('%s/%s.casenotrun' % (output_dir, seq), 'a').write(
|
|
|
|
' [case not run] ' + reason + '\n')
|
|
|
|
|
2017-09-01 13:54:34 +03:00
|
|
|
def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
|
2018-04-09 14:44:17 +03: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 13:54:34 +03:00
|
|
|
notrun('not suitable for this image format: %s' % imgfmt)
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2018-05-29 22:44:47 +03: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 17:11:45 +03:00
|
|
|
def verify_platform(supported_oses=['linux']):
|
2015-01-16 04:38:42 +03:00
|
|
|
if True not in [sys.platform.startswith(x) for x in supported_oses]:
|
2015-01-04 04:53:52 +03:00
|
|
|
notrun('not suitable for this OS: %s' % sys.platform)
|
|
|
|
|
2018-03-13 22:34:01 +03: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 10:08:17 +03:00
|
|
|
def supports_quorum():
|
|
|
|
return 'quorum' in qemu_img_pipe('--help')
|
|
|
|
|
2016-04-05 12:21:46 +03:00
|
|
|
def verify_quorum():
|
|
|
|
'''Skip test suite if quorum support is not available'''
|
2016-10-28 10:08:17 +03:00
|
|
|
if not supports_quorum():
|
2016-04-05 12:21:46 +03:00
|
|
|
notrun('quorum support missing')
|
|
|
|
|
2019-03-07 16:33:59 +03:00
|
|
|
def qemu_pipe(*args):
|
|
|
|
'''Run qemu with an option to print something and exit (e.g. a help option),
|
|
|
|
and return its output'''
|
|
|
|
args = [qemu_prog] + qemu_opts + list(args)
|
|
|
|
subp = subprocess.Popen(args, stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
universal_newlines=True)
|
|
|
|
exitcode = subp.wait()
|
|
|
|
if exitcode < 0:
|
|
|
|
sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode,
|
|
|
|
' '.join(args)))
|
|
|
|
return subp.communicate()[0]
|
|
|
|
|
|
|
|
def supported_formats(read_only=False):
|
|
|
|
'''Set 'read_only' to True to check ro-whitelist
|
|
|
|
Otherwise, rw-whitelist is checked'''
|
|
|
|
format_message = qemu_pipe("-drive", "format=help")
|
|
|
|
line = 1 if read_only else 0
|
|
|
|
return format_message.splitlines()[line].split(":")[1].split()
|
|
|
|
|
|
|
|
def skip_if_unsupported(required_formats=[], read_only=False):
|
|
|
|
'''Skip Test Decorator
|
|
|
|
Runs the test if all the required formats are whitelisted'''
|
|
|
|
def skip_test_decorator(func):
|
|
|
|
def func_wrapper(*args, **kwargs):
|
|
|
|
usf_list = list(set(required_formats) -
|
|
|
|
set(supported_formats(read_only)))
|
|
|
|
if usf_list:
|
|
|
|
case_notrun('{}: formats {} are not whitelisted'.format(
|
|
|
|
args[0], usf_list))
|
|
|
|
else:
|
|
|
|
return func(*args, **kwargs)
|
|
|
|
return func_wrapper
|
|
|
|
return skip_test_decorator
|
|
|
|
|
2019-07-29 23:35:53 +03:00
|
|
|
def execute_unittest(output, verbosity, debug):
|
|
|
|
runner = unittest.TextTestRunner(stream=output, descriptions=True,
|
|
|
|
verbosity=verbosity)
|
|
|
|
try:
|
|
|
|
# unittest.main() will use sys.exit(); so expect a SystemExit
|
|
|
|
# exception
|
|
|
|
unittest.main(testRunner=runner)
|
|
|
|
finally:
|
|
|
|
if not debug:
|
|
|
|
sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s',
|
|
|
|
r'Ran \1 tests', output.getvalue()))
|
2016-03-21 17:11:45 +03:00
|
|
|
|
2019-07-29 23:35:53 +03:00
|
|
|
def execute_test(test_function=None,
|
|
|
|
supported_fmts=[], supported_oses=['linux'],
|
2019-09-02 22:33:17 +03:00
|
|
|
supported_cache_modes=[], unsupported_fmts=[],
|
|
|
|
supported_protocols=[], unsupported_protocols=[]):
|
2019-07-29 23:35:53 +03:00
|
|
|
"""Run either unittest or script-style tests."""
|
2016-08-23 17:44:03 +03:00
|
|
|
|
2016-04-19 22:34:02 +03: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 17:11:45 +03:00
|
|
|
debug = '-d' in sys.argv
|
|
|
|
verbosity = 1
|
2018-03-30 18:16:35 +03:00
|
|
|
verify_image_format(supported_fmts, unsupported_fmts)
|
2019-09-02 22:33:17 +03:00
|
|
|
verify_protocol(supported_protocols, unsupported_protocols)
|
2016-03-21 17:11:45 +03:00
|
|
|
verify_platform(supported_oses)
|
2018-03-13 22:34:01 +03:00
|
|
|
verify_cache_mode(supported_cache_modes)
|
2016-03-21 17:11:45 +03:00
|
|
|
|
2015-05-18 04:39:12 +03:00
|
|
|
if debug:
|
|
|
|
output = sys.stdout
|
|
|
|
verbosity = 2
|
|
|
|
sys.argv.remove('-d')
|
|
|
|
else:
|
2018-10-22 16:53:06 +03:00
|
|
|
# We need to filter out the time taken from the output so that
|
|
|
|
# qemu-iotest can reliably diff the results against master output.
|
2019-09-19 19:18:31 +03:00
|
|
|
output = io.StringIO()
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2017-09-27 16:03:36 +03:00
|
|
|
logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
|
|
|
|
|
2019-07-29 23:35:53 +03:00
|
|
|
if not test_function:
|
|
|
|
execute_unittest(output, verbosity, debug)
|
|
|
|
else:
|
|
|
|
test_function()
|
|
|
|
|
|
|
|
def script_main(test_function, *args, **kwargs):
|
|
|
|
"""Run script-style tests outside of the unittest framework"""
|
|
|
|
execute_test(test_function, *args, **kwargs)
|
2012-02-29 17:25:21 +04:00
|
|
|
|
2019-07-29 23:35:53 +03:00
|
|
|
def main(*args, **kwargs):
|
|
|
|
"""Run tests using the unittest framework"""
|
|
|
|
execute_test(None, *args, **kwargs)
|