2
0

device-crash-test 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2017 Red Hat Inc
  4. #
  5. # Author:
  6. # Eduardo Habkost <ehabkost@redhat.com>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. Run QEMU with all combinations of -machine and -device types,
  23. check for crashes and unexpected errors.
  24. """
  25. import os
  26. import sys
  27. import glob
  28. import logging
  29. import traceback
  30. import re
  31. import random
  32. import argparse
  33. from itertools import chain
  34. sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'python'))
  35. from qemu.machine import QEMUMachine
  36. from qemu.qmp import ConnectError
  37. logger = logging.getLogger('device-crash-test')
  38. dbg = logger.debug
  39. # Purposes of the following rule list:
  40. # * Avoiding verbose log messages when we find known non-fatal
  41. # (exitcode=1) errors
  42. # * Avoiding fatal errors when we find known crashes
  43. # * Skipping machines/devices that are known not to work out of
  44. # the box, when running in --quick mode
  45. #
  46. # Keeping the rule list updated is desirable, but not required,
  47. # because unexpected cases where QEMU exits with exitcode=1 will
  48. # just trigger a INFO message.
  49. # Valid error rule keys:
  50. # * accel: regexp, full match only
  51. # * machine: regexp, full match only
  52. # * device: regexp, full match only
  53. # * log: regexp, partial match allowed
  54. # * exitcode: if not present, defaults to 1. If None, matches any exitcode
  55. # * warn: if True, matching failures will be logged as warnings
  56. # * expected: if True, QEMU is expected to always fail every time
  57. # when testing the corresponding test case
  58. # * loglevel: log level of log output when there's a match.
  59. ERROR_RULE_LIST = [
  60. # Machines that won't work out of the box:
  61. # MACHINE | ERROR MESSAGE
  62. {'machine':'niagara', 'expected':True}, # Unable to load a firmware for -M niagara
  63. {'machine':'boston', 'expected':True}, # Please provide either a -kernel or -bios argument
  64. {'machine':'leon3_generic', 'expected':True}, # Can't read bios image (null)
  65. # devices that don't work out of the box because they require extra options to "-device DEV":
  66. # DEVICE | ERROR MESSAGE
  67. {'device':'.*-(i386|x86_64)-cpu', 'expected':True}, # CPU socket-id is not set
  68. {'device':'icp', 'expected':True}, # icp_realize: required link 'xics' not found: Property '.xics' not found
  69. {'device':'ics', 'expected':True}, # ics_base_realize: required link 'xics' not found: Property '.xics' not found
  70. # "-device ide-cd" does work on more recent QEMU versions, so it doesn't have expected=True
  71. {'device':'ide-cd'}, # No drive specified
  72. {'device':'ide-hd', 'expected':True}, # No drive specified
  73. {'device':'ipmi-bmc-extern', 'expected':True}, # IPMI external bmc requires chardev attribute
  74. {'device':'isa-debugcon', 'expected':True}, # Can't create serial device, empty char device
  75. {'device':'isa-ipmi-bt', 'expected':True}, # IPMI device requires a bmc attribute to be set
  76. {'device':'isa-ipmi-kcs', 'expected':True}, # IPMI device requires a bmc attribute to be set
  77. {'device':'isa-parallel', 'expected':True}, # Can't create serial device, empty char device
  78. {'device':'ivshmem-doorbell', 'expected':True}, # You must specify a 'chardev'
  79. {'device':'ivshmem-plain', 'expected':True}, # You must specify a 'memdev'
  80. {'device':'loader', 'expected':True}, # please include valid arguments
  81. {'device':'nand', 'expected':True}, # Unsupported NAND block size 0x1
  82. {'device':'nvdimm', 'expected':True}, # 'memdev' property is not set
  83. {'device':'nvme', 'expected':True}, # Device initialization failed
  84. {'device':'pc-dimm', 'expected':True}, # 'memdev' property is not set
  85. {'device':'pci-bridge', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  86. {'device':'pci-bridge-seat', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  87. {'device':'pxb', 'expected':True}, # Bridge chassis not specified. Each bridge is required to be assigned a unique chassis id > 0.
  88. {'device':'scsi-block', 'expected':True}, # drive property not set
  89. {'device':'scsi-generic', 'expected':True}, # drive property not set
  90. {'device':'scsi-hd', 'expected':True}, # drive property not set
  91. {'device':'spapr-pci-host-bridge', 'expected':True}, # BUID not specified for PHB
  92. {'device':'spapr-rng', 'expected':True}, # spapr-rng needs an RNG backend!
  93. {'device':'spapr-vty', 'expected':True}, # chardev property not set
  94. {'device':'tpm-tis', 'expected':True}, # tpm_tis: backend driver with id (null) could not be found
  95. {'device':'unimplemented-device', 'expected':True}, # property 'size' not specified or zero
  96. {'device':'usb-braille', 'expected':True}, # Property chardev is required
  97. {'device':'usb-mtp', 'expected':True}, # rootdir property must be configured
  98. {'device':'usb-redir', 'expected':True}, # Parameter 'chardev' is missing
  99. {'device':'usb-serial', 'expected':True}, # Property chardev is required
  100. {'device':'usb-storage', 'expected':True}, # drive property not set
  101. {'device':'vfio-amd-xgbe', 'expected':True}, # -device vfio-amd-xgbe: vfio error: wrong host device name
  102. {'device':'vfio-calxeda-xgmac', 'expected':True}, # -device vfio-calxeda-xgmac: vfio error: wrong host device name
  103. {'device':'vfio-pci', 'expected':True}, # No provided host device
  104. {'device':'vfio-pci-igd-lpc-bridge', 'expected':True}, # VFIO dummy ISA/LPC bridge must have address 1f.0
  105. {'device':'vhost-scsi.*', 'expected':True}, # vhost-scsi: missing wwpn
  106. {'device':'vhost-vsock-device', 'expected':True}, # guest-cid property must be greater than 2
  107. {'device':'vhost-vsock-pci', 'expected':True}, # guest-cid property must be greater than 2
  108. {'device':'virtio-9p-ccw', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  109. {'device':'virtio-9p-device', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  110. {'device':'virtio-9p-pci', 'expected':True}, # 9pfs device couldn't find fsdev with the id = NULL
  111. {'device':'virtio-blk-ccw', 'expected':True}, # drive property not set
  112. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  113. {'device':'virtio-blk-device', 'expected':True}, # drive property not set
  114. {'device':'virtio-blk-pci', 'expected':True}, # drive property not set
  115. {'device':'virtio-crypto-ccw', 'expected':True}, # 'cryptodev' parameter expects a valid object
  116. {'device':'virtio-crypto-device', 'expected':True}, # 'cryptodev' parameter expects a valid object
  117. {'device':'virtio-crypto-pci', 'expected':True}, # 'cryptodev' parameter expects a valid object
  118. {'device':'virtio-input-host-device', 'expected':True}, # evdev property is required
  119. {'device':'virtio-input-host-pci', 'expected':True}, # evdev property is required
  120. {'device':'xen-pvdevice', 'expected':True}, # Device ID invalid, it must always be supplied
  121. {'device':'vhost-vsock-ccw', 'expected':True}, # guest-cid property must be greater than 2
  122. {'device':'zpci', 'expected':True}, # target must be defined
  123. {'device':'pnv-(occ|icp|lpc)', 'expected':True}, # required link 'xics' not found: Property '.xics' not found
  124. {'device':'powernv-cpu-.*', 'expected':True}, # pnv_core_realize: required link 'xics' not found: Property '.xics' not found
  125. # ioapic devices are already created by pc and will fail:
  126. {'machine':'q35|pc.*', 'device':'kvm-ioapic', 'expected':True}, # Only 1 ioapics allowed
  127. {'machine':'q35|pc.*', 'device':'ioapic', 'expected':True}, # Only 1 ioapics allowed
  128. # "spapr-cpu-core needs a pseries machine"
  129. {'machine':'(?!pseries).*', 'device':'.*-spapr-cpu-core', 'expected':True},
  130. # KVM-specific devices shouldn't be tried without accel=kvm:
  131. {'accel':'(?!kvm).*', 'device':'kvmclock', 'expected':True},
  132. # xen-specific machines and devices:
  133. {'accel':'(?!xen).*', 'machine':'xen.*', 'expected':True},
  134. {'accel':'(?!xen).*', 'device':'xen-.*', 'expected':True},
  135. # this fails on some machine-types, but not all, so they don't have expected=True:
  136. {'device':'vmgenid'}, # vmgenid requires DMA write support in fw_cfg, which this machine type does not provide
  137. # Silence INFO messages for errors that are common on multiple
  138. # devices/machines:
  139. {'log':r"No '[\w-]+' bus found for device '[\w-]+'"},
  140. {'log':r"images* must be given with the 'pflash' parameter"},
  141. {'log':r"(Guest|ROM|Flash|Kernel) image must be specified"},
  142. {'log':r"[cC]ould not load [\w ]+ (BIOS|bios) '[\w-]+\.bin'"},
  143. {'log':r"Couldn't find rom image '[\w-]+\.bin'"},
  144. {'log':r"speed mismatch trying to attach usb device"},
  145. {'log':r"Can't create a second ISA bus"},
  146. {'log':r"duplicate fw_cfg file name"},
  147. # sysbus-related error messages: most machines reject most dynamic sysbus devices:
  148. {'log':r"Option '-device [\w.,-]+' cannot be handled by this machine"},
  149. {'log':r"Device [\w.,-]+ is not supported by this machine yet"},
  150. {'log':r"Device [\w.,-]+ can not be dynamically instantiated"},
  151. {'log':r"Platform Bus: Can not fit MMIO region of size "},
  152. # other more specific errors we will ignore:
  153. {'device':'.*-spapr-cpu-core', 'log':r"CPU core type should be"},
  154. {'log':r"MSI(-X)? is not supported by interrupt controller"},
  155. {'log':r"pxb-pcie? devices cannot reside on a PCIe? bus"},
  156. {'log':r"Ignoring smp_cpus value"},
  157. {'log':r"sd_init failed: Drive 'sd0' is already in use because it has been automatically connected to another device"},
  158. {'log':r"This CPU requires a smaller page size than the system is using"},
  159. {'log':r"MSI-X support is mandatory in the S390 architecture"},
  160. {'log':r"rom check and register reset failed"},
  161. {'log':r"Unable to initialize GIC, CPUState for CPU#0 not valid"},
  162. {'log':r"Multiple VT220 operator consoles are not supported"},
  163. {'log':r"core 0 already populated"},
  164. {'log':r"could not find stage1 bootloader"},
  165. # other exitcode=1 failures not listed above will just generate INFO messages:
  166. {'exitcode':1, 'loglevel':logging.INFO},
  167. # everything else (including SIGABRT and SIGSEGV) will be a fatal error:
  168. {'exitcode':None, 'fatal':True, 'loglevel':logging.FATAL},
  169. ]
  170. def errorRuleTestCaseMatch(rule, t):
  171. """Check if a test case specification can match a error rule
  172. This only checks if a error rule is a candidate match
  173. for a given test case, it won't check if the test case
  174. results/output match the rule. See ruleListResultMatch().
  175. """
  176. return (('machine' not in rule or
  177. 'machine' not in t or
  178. re.match(rule['machine'] + '$', t['machine'])) and
  179. ('accel' not in rule or
  180. 'accel' not in t or
  181. re.match(rule['accel'] + '$', t['accel'])) and
  182. ('device' not in rule or
  183. 'device' not in t or
  184. re.match(rule['device'] + '$', t['device'])))
  185. def ruleListCandidates(t):
  186. """Generate the list of candidates that can match a test case"""
  187. for i, rule in enumerate(ERROR_RULE_LIST):
  188. if errorRuleTestCaseMatch(rule, t):
  189. yield (i, rule)
  190. def findExpectedResult(t):
  191. """Check if there's an expected=True error rule for a test case
  192. Returns (i, rule) tuple, where i is the index in
  193. ERROR_RULE_LIST and rule is the error rule itself.
  194. """
  195. for i, rule in ruleListCandidates(t):
  196. if rule.get('expected'):
  197. return (i, rule)
  198. def ruleListResultMatch(rule, r):
  199. """Check if test case results/output match a error rule
  200. It is valid to call this function only if
  201. errorRuleTestCaseMatch() is True for the rule (e.g. on
  202. rules returned by ruleListCandidates())
  203. """
  204. assert errorRuleTestCaseMatch(rule, r['testcase'])
  205. return ((rule.get('exitcode', 1) is None or
  206. r['exitcode'] == rule.get('exitcode', 1)) and
  207. ('log' not in rule or
  208. re.search(rule['log'], r['log'], re.MULTILINE)))
  209. def checkResultRuleList(r):
  210. """Look up error rule for a given test case result
  211. Returns (i, rule) tuple, where i is the index in
  212. ERROR_RULE_LIST and rule is the error rule itself.
  213. """
  214. for i, rule in ruleListCandidates(r['testcase']):
  215. if ruleListResultMatch(rule, r):
  216. return i, rule
  217. raise Exception("this should never happen")
  218. def qemuOptsEscape(s):
  219. """Escape option value QemuOpts"""
  220. return s.replace(",", ",,")
  221. def formatTestCase(t):
  222. """Format test case info as "key=value key=value" for prettier logging output"""
  223. return ' '.join('%s=%s' % (k, v) for k, v in t.items())
  224. def qomListTypeNames(vm, **kwargs):
  225. """Run qom-list-types QMP command, return type names"""
  226. types = vm.command('qom-list-types', **kwargs)
  227. return [t['name'] for t in types]
  228. def infoQDM(vm):
  229. """Parse 'info qdm' output"""
  230. args = {'command-line': 'info qdm'}
  231. devhelp = vm.command('human-monitor-command', **args)
  232. for l in devhelp.split('\n'):
  233. l = l.strip()
  234. if l == '' or l.endswith(':'):
  235. continue
  236. d = {'name': re.search(r'name "([^"]+)"', l).group(1),
  237. 'no-user': (re.search(', no-user', l) is not None)}
  238. yield d
  239. class QemuBinaryInfo(object):
  240. def __init__(self, binary, devtype):
  241. if devtype is None:
  242. devtype = 'device'
  243. self.binary = binary
  244. self._machine_info = {}
  245. dbg("devtype: %r", devtype)
  246. args = ['-S', '-machine', 'none,accel=kvm:tcg']
  247. dbg("querying info for QEMU binary: %s", binary)
  248. vm = QEMUMachine(binary=binary, args=args)
  249. vm.launch()
  250. try:
  251. self.alldevs = set(qomListTypeNames(vm, implements=devtype, abstract=False))
  252. # there's no way to query DeviceClass::user_creatable using QMP,
  253. # so use 'info qdm':
  254. self.no_user_devs = set([d['name'] for d in infoQDM(vm, ) if d['no-user']])
  255. self.machines = list(m['name'] for m in vm.command('query-machines'))
  256. self.user_devs = self.alldevs.difference(self.no_user_devs)
  257. self.kvm_available = vm.command('query-kvm')['enabled']
  258. finally:
  259. vm.shutdown()
  260. def machineInfo(self, machine):
  261. """Query for information on a specific machine-type
  262. Results are cached internally, in case the same machine-
  263. type is queried multiple times.
  264. """
  265. if machine in self._machine_info:
  266. return self._machine_info[machine]
  267. mi = {}
  268. args = ['-S', '-machine', '%s' % (machine)]
  269. dbg("querying machine info for binary=%s machine=%s", self.binary, machine)
  270. vm = QEMUMachine(binary=self.binary, args=args)
  271. try:
  272. vm.launch()
  273. mi['runnable'] = True
  274. except Exception:
  275. dbg("exception trying to run binary=%s machine=%s", self.binary, machine, exc_info=sys.exc_info())
  276. dbg("log: %r", vm.get_log())
  277. mi['runnable'] = False
  278. vm.shutdown()
  279. self._machine_info[machine] = mi
  280. return mi
  281. BINARY_INFO = {}
  282. def getBinaryInfo(args, binary):
  283. if binary not in BINARY_INFO:
  284. BINARY_INFO[binary] = QemuBinaryInfo(binary, args.devtype)
  285. return BINARY_INFO[binary]
  286. def checkOneCase(args, testcase):
  287. """Check one specific case
  288. Returns a dictionary containing failure information on error,
  289. or None on success
  290. """
  291. binary = testcase['binary']
  292. accel = testcase['accel']
  293. machine = testcase['machine']
  294. device = testcase['device']
  295. dbg("will test: %r", testcase)
  296. args = ['-S', '-machine', '%s,accel=%s' % (machine, accel),
  297. '-device', qemuOptsEscape(device)]
  298. cmdline = ' '.join([binary] + args)
  299. dbg("will launch QEMU: %s", cmdline)
  300. vm = QEMUMachine(binary=binary, args=args, qmp_timer=15)
  301. exc = None
  302. exc_traceback = None
  303. try:
  304. vm.launch()
  305. except Exception as this_exc:
  306. exc = this_exc
  307. exc_traceback = traceback.format_exc()
  308. dbg("Exception while running test case")
  309. finally:
  310. vm.shutdown()
  311. ec = vm.exitcode()
  312. log = vm.get_log()
  313. if exc is not None or ec != 0:
  314. return {'exc': exc,
  315. 'exc_traceback':exc_traceback,
  316. 'exitcode':ec,
  317. 'log':log,
  318. 'testcase':testcase,
  319. 'cmdline':cmdline}
  320. def binariesToTest(args, testcase):
  321. if args.qemu:
  322. r = args.qemu
  323. else:
  324. r = [f.path for f in os.scandir('.')
  325. if f.name.startswith('qemu-system-') and
  326. f.is_file() and os.access(f, os.X_OK)]
  327. return r
  328. def accelsToTest(args, testcase):
  329. if getBinaryInfo(args, testcase['binary']).kvm_available:
  330. yield 'kvm'
  331. yield 'tcg'
  332. def machinesToTest(args, testcase):
  333. return getBinaryInfo(args, testcase['binary']).machines
  334. def devicesToTest(args, testcase):
  335. return getBinaryInfo(args, testcase['binary']).user_devs
  336. TESTCASE_VARIABLES = [
  337. ('binary', binariesToTest),
  338. ('accel', accelsToTest),
  339. ('machine', machinesToTest),
  340. ('device', devicesToTest),
  341. ]
  342. def genCases1(args, testcases, var, fn):
  343. """Generate new testcases for one variable
  344. If an existing item already has a variable set, don't
  345. generate new items and just return it directly. This
  346. allows the "-t" command-line option to be used to choose
  347. a specific test case.
  348. """
  349. for testcase in testcases:
  350. if var in testcase:
  351. yield testcase.copy()
  352. else:
  353. for i in fn(args, testcase):
  354. t = testcase.copy()
  355. t[var] = i
  356. yield t
  357. def genCases(args, testcase):
  358. """Generate test cases for all variables
  359. """
  360. cases = [testcase.copy()]
  361. for var, fn in TESTCASE_VARIABLES:
  362. dbg("var: %r, fn: %r", var, fn)
  363. cases = genCases1(args, cases, var, fn)
  364. return cases
  365. def casesToTest(args, testcase):
  366. cases = genCases(args, testcase)
  367. if args.random:
  368. cases = list(cases)
  369. cases = random.sample(cases, min(args.random, len(cases)))
  370. if args.debug:
  371. cases = list(cases)
  372. dbg("%d test cases to test", len(cases))
  373. if args.shuffle:
  374. cases = list(cases)
  375. random.shuffle(cases)
  376. return cases
  377. def logFailure(f, level):
  378. t = f['testcase']
  379. logger.log(level, "failed: %s", formatTestCase(t))
  380. logger.log(level, "cmdline: %s", f['cmdline'])
  381. for l in f['log'].strip().split('\n'):
  382. logger.log(level, "log: %s", l)
  383. logger.log(level, "exit code: %r", f['exitcode'])
  384. # If the Exception is merely a QMP connect error,
  385. # reduce the logging level for its traceback to
  386. # improve visual clarity.
  387. if isinstance(f.get('exc'), ConnectError):
  388. logger.log(level, "%s.%s: %s",
  389. type(f['exc']).__module__,
  390. type(f['exc']).__qualname__,
  391. str(f['exc']))
  392. level = logging.DEBUG
  393. if f['exc_traceback']:
  394. logger.log(level, "exception:")
  395. for l in f['exc_traceback'].split('\n'):
  396. logger.log(level, " %s", l.rstrip('\n'))
  397. def main():
  398. parser = argparse.ArgumentParser(description="QEMU -device crash test")
  399. parser.add_argument('-t', metavar='KEY=VALUE', nargs='*',
  400. help="Limit test cases to KEY=VALUE",
  401. action='append', dest='testcases', default=[])
  402. parser.add_argument('-d', '--debug', action='store_true',
  403. help='debug output')
  404. parser.add_argument('-v', '--verbose', action='store_true', default=True,
  405. help='verbose output')
  406. parser.add_argument('-q', '--quiet', dest='verbose', action='store_false',
  407. help='non-verbose output')
  408. parser.add_argument('-r', '--random', type=int, metavar='COUNT',
  409. help='run a random sample of COUNT test cases',
  410. default=0)
  411. parser.add_argument('--shuffle', action='store_true',
  412. help='Run test cases in random order')
  413. parser.add_argument('--dry-run', action='store_true',
  414. help="Don't run any tests, just generate list")
  415. parser.add_argument('-D', '--devtype', metavar='TYPE',
  416. help="Test only device types that implement TYPE")
  417. parser.add_argument('-Q', '--quick', action='store_true', default=True,
  418. help="Quick mode: skip test cases that are expected to fail")
  419. parser.add_argument('-F', '--full', action='store_false', dest='quick',
  420. help="Full mode: test cases that are expected to fail")
  421. parser.add_argument('--strict', action='store_true', dest='strict',
  422. help="Treat all warnings as fatal")
  423. parser.add_argument('qemu', nargs='*', metavar='QEMU',
  424. help='QEMU binary to run')
  425. args = parser.parse_args()
  426. if args.debug:
  427. lvl = logging.DEBUG
  428. elif args.verbose:
  429. lvl = logging.INFO
  430. else:
  431. lvl = logging.WARN
  432. logging.basicConfig(stream=sys.stdout, level=lvl, format='%(levelname)s: %(message)s')
  433. if not args.debug:
  434. # Async QMP, when in use, is chatty about connection failures.
  435. # This script knowingly generates a ton of connection errors.
  436. # Silence this logger.
  437. logging.getLogger('qemu.qmp.qmp_client').setLevel(logging.CRITICAL)
  438. fatal_failures = []
  439. wl_stats = {}
  440. skipped = 0
  441. total = 0
  442. tc = {}
  443. dbg("testcases: %r", args.testcases)
  444. if args.testcases:
  445. for t in chain(*args.testcases):
  446. for kv in t.split():
  447. k, v = kv.split('=', 1)
  448. tc[k] = v
  449. if len(binariesToTest(args, tc)) == 0:
  450. print("No QEMU binary found", file=sys.stderr)
  451. parser.print_usage(sys.stderr)
  452. return 1
  453. for t in casesToTest(args, tc):
  454. logger.info("running test case: %s", formatTestCase(t))
  455. total += 1
  456. expected_match = findExpectedResult(t)
  457. if (args.quick and
  458. (expected_match or
  459. not getBinaryInfo(args, t['binary']).machineInfo(t['machine'])['runnable'])):
  460. dbg("skipped: %s", formatTestCase(t))
  461. skipped += 1
  462. continue
  463. if args.dry_run:
  464. continue
  465. try:
  466. f = checkOneCase(args, t)
  467. except KeyboardInterrupt:
  468. break
  469. if f:
  470. i, rule = checkResultRuleList(f)
  471. dbg("testcase: %r, rule list match: %r", t, rule)
  472. wl_stats.setdefault(i, []).append(f)
  473. level = rule.get('loglevel', logging.DEBUG)
  474. logFailure(f, level)
  475. if rule.get('fatal') or (args.strict and level >= logging.WARN):
  476. fatal_failures.append(f)
  477. else:
  478. dbg("success: %s", formatTestCase(t))
  479. if expected_match:
  480. logger.warn("Didn't fail as expected: %s", formatTestCase(t))
  481. logger.info("Total: %d test cases", total)
  482. if skipped:
  483. logger.info("Skipped %d test cases", skipped)
  484. if args.debug:
  485. stats = sorted([(len(wl_stats.get(i, [])), rule) for i, rule in
  486. enumerate(ERROR_RULE_LIST)], key=lambda x: x[0])
  487. for count, rule in stats:
  488. dbg("error rule stats: %d: %r", count, rule)
  489. if fatal_failures:
  490. for f in fatal_failures:
  491. t = f['testcase']
  492. logger.error("Fatal failure: %s", formatTestCase(t))
  493. logger.error("Fatal failures on some machine/device combinations")
  494. return 1
  495. if __name__ == '__main__':
  496. sys.exit(main())