parallel-vm.py 19 KB

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