parallel-vm.py 18 KB

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