parallel-vm.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. #!/usr/bin/env python2
  2. #
  3. # Parallel VM test case executor
  4. # Copyright (c) 2014-2015, Jouni Malinen <j@w1.fi>
  5. #
  6. # This software may be distributed under the terms of the BSD license.
  7. # See README for more details.
  8. import curses
  9. import fcntl
  10. import logging
  11. import os
  12. import subprocess
  13. import sys
  14. import time
  15. logger = logging.getLogger()
  16. # Test cases that take significantly longer time to execute than average.
  17. long_tests = [ "ap_roam_open",
  18. "wpas_mesh_password_mismatch_retry",
  19. "wpas_mesh_password_mismatch",
  20. "hostapd_oom_wpa2_psk_connect",
  21. "ap_hs20_fetch_osu_stop",
  22. "ap_roam_wpa2_psk",
  23. "ibss_wpa_none_ccmp",
  24. "nfc_wps_er_handover_pk_hash_mismatch_sta",
  25. "go_neg_peers_force_diff_freq",
  26. "p2p_cli_invite",
  27. "sta_ap_scan_2b",
  28. "ap_pmf_sta_unprot_deauth_burst",
  29. "ap_bss_add_remove_during_ht_scan",
  30. "wext_scan_hidden",
  31. "autoscan_exponential",
  32. "nfc_p2p_client",
  33. "wnm_bss_keep_alive",
  34. "ap_inactivity_disconnect",
  35. "scan_bss_expiration_age",
  36. "autoscan_periodic",
  37. "discovery_group_client",
  38. "concurrent_p2pcli",
  39. "ap_bss_add_remove",
  40. "wpas_ap_wps",
  41. "wext_pmksa_cache",
  42. "ibss_wpa_none",
  43. "ap_ht_40mhz_intolerant_ap",
  44. "ibss_rsn",
  45. "discovery_pd_retries",
  46. "ap_wps_setup_locked_timeout",
  47. "ap_vht160",
  48. "dfs_radar",
  49. "dfs",
  50. "grpform_cred_ready_timeout",
  51. "hostapd_oom_wpa2_eap_connect",
  52. "wpas_ap_dfs",
  53. "autogo_many",
  54. "hostapd_oom_wpa2_eap",
  55. "ibss_open",
  56. "proxyarp_open_ebtables",
  57. "radius_failover",
  58. "obss_scan_40_intolerant",
  59. "dbus_connect_oom",
  60. "proxyarp_open",
  61. "ap_wps_iteration",
  62. "ap_wps_iteration_error",
  63. "ap_wps_pbc_timeout" ]
  64. def get_failed(vm):
  65. failed = []
  66. for i in range(num_servers):
  67. failed += vm[i]['failed']
  68. return failed
  69. def vm_read_stdout(vm, i):
  70. global total_started, total_passed, total_failed, total_skipped
  71. global rerun_failures
  72. ready = False
  73. try:
  74. out = vm['proc'].stdout.read()
  75. except:
  76. return False
  77. logger.debug("VM[%d] stdout.read[%s]" % (i, out))
  78. pending = vm['pending'] + out
  79. lines = []
  80. while True:
  81. pos = pending.find('\n')
  82. if pos < 0:
  83. break
  84. line = pending[0:pos].rstrip()
  85. pending = pending[(pos + 1):]
  86. logger.debug("VM[%d] stdout full line[%s]" % (i, line))
  87. if line.startswith("READY"):
  88. ready = True
  89. elif line.startswith("PASS"):
  90. ready = True
  91. total_passed += 1
  92. elif line.startswith("FAIL"):
  93. ready = True
  94. total_failed += 1
  95. vals = line.split(' ')
  96. if len(vals) < 2:
  97. logger.info("VM[%d] incomplete FAIL line: %s" % (i, line))
  98. name = line
  99. else:
  100. name = vals[1]
  101. logger.debug("VM[%d] test case failed: %s" % (i, name))
  102. vm['failed'].append(name)
  103. elif line.startswith("NOT-FOUND"):
  104. ready = True
  105. total_failed += 1
  106. logger.info("VM[%d] test case not found" % i)
  107. elif line.startswith("SKIP"):
  108. ready = True
  109. total_skipped += 1
  110. elif line.startswith("START"):
  111. total_started += 1
  112. if len(vm['failed']) == 0:
  113. vals = line.split(' ')
  114. if len(vals) >= 2:
  115. vm['fail_seq'].append(vals[1])
  116. vm['out'] += line + '\n'
  117. lines.append(line)
  118. vm['pending'] = pending
  119. return ready
  120. def show_progress(scr):
  121. global num_servers
  122. global vm
  123. global dir
  124. global timestamp
  125. global tests
  126. global first_run_failures
  127. global total_started, total_passed, total_failed, total_skipped
  128. total_tests = len(tests)
  129. logger.info("Total tests: %d" % total_tests)
  130. scr.leaveok(1)
  131. scr.addstr(0, 0, "Parallel test execution status", curses.A_BOLD)
  132. for i in range(0, num_servers):
  133. scr.addstr(i + 1, 0, "VM %d:" % (i + 1), curses.A_BOLD)
  134. scr.addstr(i + 1, 10, "starting VM")
  135. scr.addstr(num_servers + 1, 0, "Total:", curses.A_BOLD)
  136. scr.addstr(num_servers + 1, 20, "TOTAL={} STARTED=0 PASS=0 FAIL=0 SKIP=0".format(total_tests))
  137. scr.refresh()
  138. completed_first_pass = False
  139. rerun_tests = []
  140. while True:
  141. running = False
  142. first_running = False
  143. updated = False
  144. for i in range(0, num_servers):
  145. if completed_first_pass:
  146. continue
  147. if vm[i]['first_run_done']:
  148. continue
  149. if not vm[i]['proc']:
  150. continue
  151. if vm[i]['proc'].poll() is not None:
  152. vm[i]['proc'] = None
  153. scr.move(i + 1, 10)
  154. scr.clrtoeol()
  155. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  156. with open(log, 'r') as f:
  157. if "Kernel panic" in f.read():
  158. scr.addstr("kernel panic")
  159. logger.info("VM[%d] kernel panic" % i)
  160. else:
  161. scr.addstr("unexpected exit")
  162. logger.info("VM[%d] unexpected exit" % i)
  163. updated = True
  164. continue
  165. running = True
  166. first_running = True
  167. try:
  168. err = vm[i]['proc'].stderr.read()
  169. vm[i]['err'] += err
  170. logger.debug("VM[%d] stderr.read[%s]" % (i, err))
  171. except:
  172. pass
  173. if vm_read_stdout(vm[i], i):
  174. scr.move(i + 1, 10)
  175. scr.clrtoeol()
  176. updated = True
  177. if not tests:
  178. vm[i]['first_run_done'] = True
  179. scr.addstr("completed first round")
  180. logger.info("VM[%d] completed first round" % i)
  181. continue
  182. else:
  183. name = tests.pop(0)
  184. vm[i]['proc'].stdin.write(name + '\n')
  185. scr.addstr(name)
  186. logger.debug("VM[%d] start test %s" % (i, name))
  187. if not first_running and not completed_first_pass:
  188. logger.info("First round of testing completed")
  189. if tests:
  190. logger.info("Unexpected test cases remaining from first round: " + str(tests))
  191. raise Exception("Unexpected test cases remaining from first round")
  192. completed_first_pass = True
  193. for name in get_failed(vm):
  194. if rerun_failures:
  195. rerun_tests.append(name)
  196. first_run_failures.append(name)
  197. for i in range(num_servers):
  198. if not completed_first_pass:
  199. continue
  200. if not vm[i]['proc']:
  201. continue
  202. if vm[i]['proc'].poll() is not None:
  203. vm[i]['proc'] = None
  204. scr.move(i + 1, 10)
  205. scr.clrtoeol()
  206. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  207. with open(log, 'r') as f:
  208. if "Kernel panic" in f.read():
  209. scr.addstr("kernel panic")
  210. logger.info("VM[%d] kernel panic" % i)
  211. else:
  212. scr.addstr("completed run")
  213. logger.info("VM[%d] completed run" % i)
  214. updated = True
  215. continue
  216. running = True
  217. try:
  218. err = vm[i]['proc'].stderr.read()
  219. vm[i]['err'] += err
  220. logger.debug("VM[%d] stderr.read[%s]" % (i, err))
  221. except:
  222. pass
  223. ready = False
  224. if vm[i]['first_run_done']:
  225. vm[i]['first_run_done'] = False
  226. ready = True
  227. else:
  228. ready = vm_read_stdout(vm[i], i)
  229. if ready:
  230. scr.move(i + 1, 10)
  231. scr.clrtoeol()
  232. updated = True
  233. if not rerun_tests:
  234. vm[i]['proc'].stdin.write('\n')
  235. scr.addstr("shutting down")
  236. logger.info("VM[%d] shutting down" % i)
  237. else:
  238. name = rerun_tests.pop(0)
  239. vm[i]['proc'].stdin.write(name + '\n')
  240. scr.addstr(name + "(*)")
  241. logger.debug("VM[%d] start test %s (*)" % (i, name))
  242. if not running:
  243. break
  244. if updated:
  245. scr.move(num_servers + 1, 10)
  246. scr.clrtoeol()
  247. scr.addstr("{} %".format(int(100.0 * (total_passed + total_failed + total_skipped) / total_tests)))
  248. scr.addstr(num_servers + 1, 20, "TOTAL={} STARTED={} PASS={} FAIL={} SKIP={}".format(total_tests, total_started, total_passed, total_failed, total_skipped))
  249. failed = get_failed(vm)
  250. if len(failed) > 0:
  251. scr.move(num_servers + 2, 0)
  252. scr.clrtoeol()
  253. scr.addstr("Failed test cases: ")
  254. count = 0
  255. for f in failed:
  256. count += 1
  257. if count > 30:
  258. scr.addstr('...')
  259. scr.clrtoeol()
  260. break
  261. scr.addstr(f)
  262. scr.addstr(' ')
  263. scr.move(0, 35)
  264. scr.clrtoeol()
  265. if rerun_tests:
  266. scr.addstr("(RETRY FAILED %d)" % len(rerun_tests))
  267. elif rerun_failures:
  268. pass
  269. elif first_run_failures:
  270. scr.addstr("(RETRY FAILED)")
  271. scr.refresh()
  272. time.sleep(0.25)
  273. scr.refresh()
  274. time.sleep(0.3)
  275. def main():
  276. import argparse
  277. import os
  278. global num_servers
  279. global vm
  280. global dir
  281. global timestamp
  282. global tests
  283. global first_run_failures
  284. global total_started, total_passed, total_failed, total_skipped
  285. global rerun_failures
  286. total_started = 0
  287. total_passed = 0
  288. total_failed = 0
  289. total_skipped = 0
  290. debug_level = logging.INFO
  291. rerun_failures = True
  292. timestamp = int(time.time())
  293. scriptsdir = os.path.dirname(os.path.realpath(sys.argv[0]))
  294. p = argparse.ArgumentParser(description='run multiple testing VMs in parallel')
  295. p.add_argument('num_servers', metavar='number of VMs', type=int, choices=range(1, 100),
  296. help="number of VMs to start")
  297. p.add_argument('-f', dest='testmodules', metavar='<test module>',
  298. help='execute only tests from these test modules',
  299. type=str, nargs='+')
  300. p.add_argument('-1', dest='no_retry', action='store_const', const=True, default=False,
  301. help="don't retry failed tests automatically")
  302. p.add_argument('--debug', dest='debug', action='store_const', const=True, default=False,
  303. help="enable debug logging")
  304. p.add_argument('--codecov', dest='codecov', action='store_const', const=True, default=False,
  305. help="enable code coverage collection")
  306. p.add_argument('--shuffle-tests', dest='shuffle', action='store_const', const=True, default=False,
  307. help="shuffle test cases to randomize order")
  308. p.add_argument('--short', dest='short', action='store_const', const=True,
  309. default=False,
  310. help="only run short-duration test cases")
  311. p.add_argument('--long', dest='long', action='store_const', const=True,
  312. default=False,
  313. help="include long-duration test cases")
  314. p.add_argument('--valgrind', dest='valgrind', action='store_const',
  315. const=True, default=False,
  316. help="run tests under valgrind")
  317. p.add_argument('params', nargs='*')
  318. args = p.parse_args()
  319. num_servers = args.num_servers
  320. rerun_failures = not args.no_retry
  321. if args.debug:
  322. debug_level = logging.DEBUG
  323. extra_args = []
  324. if args.valgrind:
  325. extra_args += [ '--valgrind' ]
  326. if args.long:
  327. extra_args += [ '--long' ]
  328. if args.codecov:
  329. print "Code coverage - build separate binaries"
  330. logdir = "/tmp/hwsim-test-logs/" + str(timestamp)
  331. os.makedirs(logdir)
  332. subprocess.check_call([os.path.join(scriptsdir, 'build-codecov.sh'),
  333. logdir])
  334. codecov_args = ['--codecov_dir', logdir]
  335. codecov = True
  336. else:
  337. codecov_args = []
  338. codecov = False
  339. first_run_failures = []
  340. if args.params:
  341. tests = args.params
  342. else:
  343. tests = []
  344. cmd = [ os.path.join(os.path.dirname(scriptsdir), 'run-tests.py'),
  345. '-L' ]
  346. if args.testmodules:
  347. cmd += [ "-f" ]
  348. cmd += args.testmodules
  349. lst = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  350. for l in lst.stdout.readlines():
  351. name = l.split(' ')[0]
  352. tests.append(name)
  353. if len(tests) == 0:
  354. sys.exit("No test cases selected")
  355. dir = '/tmp/hwsim-test-logs'
  356. try:
  357. os.mkdir(dir)
  358. except:
  359. pass
  360. if args.shuffle:
  361. from random import shuffle
  362. shuffle(tests)
  363. elif num_servers > 2 and len(tests) > 100:
  364. # Move test cases with long duration to the beginning as an
  365. # optimization to avoid last part of the test execution running a long
  366. # duration test case on a single VM while all other VMs have already
  367. # completed their work.
  368. for l in long_tests:
  369. if l in tests:
  370. tests.remove(l)
  371. tests.insert(0, l)
  372. if args.short:
  373. tests = [t for t in tests if t not in long_tests]
  374. logger.setLevel(debug_level)
  375. log_handler = logging.FileHandler('parallel-vm.log')
  376. log_handler.setLevel(debug_level)
  377. fmt = "%(asctime)s %(levelname)s %(message)s"
  378. log_formatter = logging.Formatter(fmt)
  379. log_handler.setFormatter(log_formatter)
  380. logger.addHandler(log_handler)
  381. vm = {}
  382. for i in range(0, num_servers):
  383. print("\rStarting virtual machine {}/{}".format(i + 1, num_servers)),
  384. logger.info("Starting virtual machine {}/{}".format(i + 1, num_servers))
  385. cmd = [os.path.join(scriptsdir, 'vm-run.sh'), '--delay', str(i),
  386. '--timestamp', str(timestamp),
  387. '--ext', 'srv.%d' % (i + 1),
  388. '-i'] + codecov_args + extra_args
  389. vm[i] = {}
  390. vm[i]['first_run_done'] = False
  391. vm[i]['proc'] = subprocess.Popen(cmd,
  392. stdin=subprocess.PIPE,
  393. stdout=subprocess.PIPE,
  394. stderr=subprocess.PIPE)
  395. vm[i]['out'] = ""
  396. vm[i]['pending'] = ""
  397. vm[i]['err'] = ""
  398. vm[i]['failed'] = []
  399. vm[i]['fail_seq'] = []
  400. for stream in [ vm[i]['proc'].stdout, vm[i]['proc'].stderr ]:
  401. fd = stream.fileno()
  402. fl = fcntl.fcntl(fd, fcntl.F_GETFL)
  403. fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  404. print
  405. curses.wrapper(show_progress)
  406. with open('{}/{}-parallel.log'.format(dir, timestamp), 'w') as f:
  407. for i in range(0, num_servers):
  408. f.write('VM {}\n{}\n{}\n'.format(i, vm[i]['out'], vm[i]['err']))
  409. failed = get_failed(vm)
  410. if first_run_failures:
  411. print "To re-run same failure sequence(s):"
  412. for i in range(0, num_servers):
  413. if len(vm[i]['failed']) == 0:
  414. continue
  415. print "./parallel-vm.py -1 1",
  416. skip = len(vm[i]['fail_seq'])
  417. skip -= min(skip, 30)
  418. for t in vm[i]['fail_seq']:
  419. if skip > 0:
  420. skip -= 1
  421. continue
  422. print t,
  423. print
  424. print "Failed test cases:"
  425. for f in first_run_failures:
  426. print f,
  427. logger.info("Failed: " + f)
  428. print
  429. double_failed = []
  430. for name in failed:
  431. double_failed.append(name)
  432. for test in first_run_failures:
  433. double_failed.remove(test)
  434. if not rerun_failures:
  435. pass
  436. elif failed and not double_failed:
  437. print "All failed cases passed on retry"
  438. logger.info("All failed cases passed on retry")
  439. elif double_failed:
  440. print "Failed even on retry:"
  441. for f in double_failed:
  442. print f,
  443. logger.info("Failed on retry: " + f)
  444. print
  445. res = "TOTAL={} PASS={} FAIL={} SKIP={}".format(total_started,
  446. total_passed,
  447. total_failed,
  448. total_skipped)
  449. print(res)
  450. logger.info(res)
  451. print "Logs: " + dir + '/' + str(timestamp)
  452. logger.info("Logs: " + dir + '/' + str(timestamp))
  453. for i in range(0, num_servers):
  454. if len(vm[i]['pending']) > 0:
  455. logger.info("Unprocessed stdout from VM[%d]: '%s'" %
  456. (i, vm[i]['pending']))
  457. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  458. with open(log, 'r') as f:
  459. if "Kernel panic" in f.read():
  460. print "Kernel panic in " + log
  461. logger.info("Kernel panic in " + log)
  462. if codecov:
  463. print "Code coverage - preparing report"
  464. for i in range(num_servers):
  465. subprocess.check_call([os.path.join(scriptsdir,
  466. 'process-codecov.sh'),
  467. logdir + ".srv.%d" % (i + 1),
  468. str(i)])
  469. subprocess.check_call([os.path.join(scriptsdir, 'combine-codecov.sh'),
  470. logdir])
  471. print "file://%s/index.html" % logdir
  472. logger.info("Code coverage report: file://%s/index.html" % logdir)
  473. if double_failed or (failed and not rerun_failures):
  474. logger.info("Test run complete - failures found")
  475. sys.exit(2)
  476. if failed:
  477. logger.info("Test run complete - failures found on first run; passed on retry")
  478. sys.exit(1)
  479. logger.info("Test run complete - no failures")
  480. sys.exit(0)
  481. if __name__ == "__main__":
  482. main()