parallel-vm.py 18 KB

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