device-crash-test 25 KB

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