parallel-vm.py 19 KB

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