parallel-vm.py 19 KB

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