parallel-vm.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #!/usr/bin/env python2
  2. #
  3. # Parallel VM test case executor
  4. # Copyright (c) 2014, 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. def get_results():
  17. global vm
  18. started = []
  19. passed = []
  20. failed = []
  21. skipped = []
  22. for i in range(0, num_servers):
  23. lines = vm[i]['out'].splitlines()
  24. started += [ l for l in lines if l.startswith('START ') ]
  25. passed += [ l for l in lines if l.startswith('PASS ') ]
  26. failed += [ l for l in lines if l.startswith('FAIL ') ]
  27. skipped += [ l for l in lines if l.startswith('SKIP ') ]
  28. return (started, passed, failed, skipped)
  29. def show_progress(scr):
  30. global num_servers
  31. global vm
  32. global dir
  33. global timestamp
  34. global tests
  35. global first_run_failures
  36. total_tests = len(tests)
  37. logger.info("Total tests: %d" % total_tests)
  38. scr.leaveok(1)
  39. scr.addstr(0, 0, "Parallel test execution status", curses.A_BOLD)
  40. for i in range(0, num_servers):
  41. scr.addstr(i + 1, 0, "VM %d:" % (i + 1), curses.A_BOLD)
  42. scr.addstr(i + 1, 10, "starting VM")
  43. scr.addstr(num_servers + 1, 0, "Total:", curses.A_BOLD)
  44. scr.addstr(num_servers + 1, 20, "TOTAL={} STARTED=0 PASS=0 FAIL=0 SKIP=0".format(total_tests))
  45. scr.refresh()
  46. completed_first_pass = False
  47. rerun_tests = []
  48. while True:
  49. running = False
  50. first_running = False
  51. updated = False
  52. for i in range(0, num_servers):
  53. if completed_first_pass:
  54. continue
  55. if vm[i]['first_run_done']:
  56. continue
  57. if not vm[i]['proc']:
  58. continue
  59. if vm[i]['proc'].poll() is not None:
  60. vm[i]['proc'] = None
  61. scr.move(i + 1, 10)
  62. scr.clrtoeol()
  63. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  64. with open(log, 'r') as f:
  65. if "Kernel panic" in f.read():
  66. scr.addstr("kernel panic")
  67. logger.info("VM[%d] kernel panic" % i)
  68. else:
  69. scr.addstr("unexpected exit")
  70. logger.info("VM[%d] unexpected exit" % i)
  71. updated = True
  72. continue
  73. running = True
  74. first_running = True
  75. try:
  76. err = vm[i]['proc'].stderr.read()
  77. vm[i]['err'] += err
  78. logger.debug("VM[%d] stderr.read[%s]" % (i, err))
  79. except:
  80. pass
  81. try:
  82. out = vm[i]['proc'].stdout.read()
  83. vm[i]['out'] += out
  84. logger.debug("VM[%d] stdout.read[%s]" % (i, out))
  85. if "READY" in out or "PASS" in out or "FAIL" in out or "SKIP" in out:
  86. scr.move(i + 1, 10)
  87. scr.clrtoeol()
  88. updated = True
  89. if not tests:
  90. vm[i]['first_run_done'] = True
  91. scr.addstr("completed first round")
  92. logger.info("VM[%d] completed first round" % i)
  93. continue
  94. else:
  95. name = tests.pop(0)
  96. vm[i]['proc'].stdin.write(name + '\n')
  97. scr.addstr(name)
  98. logger.debug("VM[%d] start test %s" % (i, name))
  99. except:
  100. pass
  101. if not first_running and not completed_first_pass:
  102. logger.info("First round of testing completed")
  103. if tests:
  104. logger.info("Unexpected test cases remaining from first round: " + str(tests))
  105. raise Exception("Unexpected test cases remaining from first round")
  106. completed_first_pass = True
  107. (started, passed, failed, skipped) = get_results()
  108. for f in failed:
  109. name = f.split(' ')[1]
  110. rerun_tests.append(name)
  111. first_run_failures.append(name)
  112. for i in range(num_servers):
  113. if not completed_first_pass:
  114. continue
  115. if not vm[i]['proc']:
  116. continue
  117. if vm[i]['proc'].poll() is not None:
  118. vm[i]['proc'] = None
  119. scr.move(i + 1, 10)
  120. scr.clrtoeol()
  121. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  122. with open(log, 'r') as f:
  123. if "Kernel panic" in f.read():
  124. scr.addstr("kernel panic")
  125. logger.info("VM[%d] kernel panic" % i)
  126. else:
  127. scr.addstr("completed run")
  128. logger.info("VM[%d] completed run" % i)
  129. updated = True
  130. continue
  131. running = True
  132. try:
  133. err = vm[i]['proc'].stderr.read()
  134. vm[i]['err'] += err
  135. logger.debug("VM[%d] stderr.read[%s]" % (i, err))
  136. except:
  137. pass
  138. try:
  139. ready = False
  140. if vm[i]['first_run_done']:
  141. vm[i]['first_run_done'] = False
  142. ready = True
  143. else:
  144. out = vm[i]['proc'].stdout.read()
  145. vm[i]['out'] += out
  146. logger.debug("VM[%d] stdout.read[%s]" % (i, out))
  147. if "READY" in out or "PASS" in out or "FAIL" in out or "SKIP" in out:
  148. ready = True
  149. if ready:
  150. scr.move(i + 1, 10)
  151. scr.clrtoeol()
  152. updated = True
  153. if not rerun_tests:
  154. vm[i]['proc'].stdin.write('\n')
  155. scr.addstr("shutting down")
  156. logger.info("VM[%d] shutting down" % i)
  157. else:
  158. name = rerun_tests.pop(0)
  159. vm[i]['proc'].stdin.write(name + '\n')
  160. scr.addstr(name + "(*)")
  161. logger.debug("VM[%d] start test %s (*)" % (i, name))
  162. except:
  163. pass
  164. if not running:
  165. break
  166. if updated:
  167. (started, passed, failed, skipped) = get_results()
  168. scr.move(num_servers + 1, 10)
  169. scr.clrtoeol()
  170. scr.addstr("{} %".format(int(100.0 * (len(passed) + len(failed) + len(skipped)) / total_tests)))
  171. scr.addstr(num_servers + 1, 20, "TOTAL={} STARTED={} PASS={} FAIL={} SKIP={}".format(total_tests, len(started), len(passed), len(failed), len(skipped)))
  172. if len(failed) > 0:
  173. scr.move(num_servers + 2, 0)
  174. scr.clrtoeol()
  175. scr.addstr("Failed test cases: ")
  176. for f in failed:
  177. scr.addstr(f.split(' ')[1])
  178. scr.addstr(' ')
  179. scr.move(0, 35)
  180. scr.clrtoeol()
  181. if rerun_tests:
  182. scr.addstr("(RETRY FAILED %d)" % len(rerun_tests))
  183. elif first_run_failures:
  184. scr.addstr("(RETRY FAILED)")
  185. scr.refresh()
  186. time.sleep(0.25)
  187. scr.refresh()
  188. time.sleep(0.3)
  189. def main():
  190. global num_servers
  191. global vm
  192. global dir
  193. global timestamp
  194. global tests
  195. global first_run_failures
  196. debug_level = logging.INFO
  197. if len(sys.argv) < 2:
  198. sys.exit("Usage: %s <number of VMs> [--debug] [--codecov] [params..]" % sys.argv[0])
  199. num_servers = int(sys.argv[1])
  200. if num_servers < 1:
  201. sys.exit("Too small number of VMs")
  202. timestamp = int(time.time())
  203. idx = 2
  204. if len(sys.argv) > idx and sys.argv[idx] == "--debug":
  205. idx += 1
  206. debug_level = logging.DEBUG
  207. if len(sys.argv) > idx and sys.argv[idx] == "--codecov":
  208. idx += 1
  209. print "Code coverage - build separate binaries"
  210. logdir = "/tmp/hwsim-test-logs/" + str(timestamp)
  211. os.makedirs(logdir)
  212. subprocess.check_call(['./build-codecov.sh', logdir])
  213. codecov_args = ['--codecov_dir', logdir]
  214. codecov = True
  215. else:
  216. codecov_args = []
  217. codecov = False
  218. first_run_failures = []
  219. tests = []
  220. cmd = [ '../run-tests.py', '-L' ] + sys.argv[idx:]
  221. lst = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  222. for l in lst.stdout.readlines():
  223. name = l.split(' ')[0]
  224. tests.append(name)
  225. if len(tests) == 0:
  226. sys.exit("No test cases selected")
  227. if '-f' in sys.argv[idx:]:
  228. extra_args = sys.argv[idx:]
  229. else:
  230. extra_args = [x for x in sys.argv[idx:] if x not in tests]
  231. dir = '/tmp/hwsim-test-logs'
  232. try:
  233. os.mkdir(dir)
  234. except:
  235. pass
  236. if num_servers > 2 and len(tests) > 100:
  237. # Move test cases with long duration to the beginning as an
  238. # optimization to avoid last part of the test execution running a long
  239. # duration test case on a single VM while all other VMs have already
  240. # completed their work.
  241. long = [ "ap_roam_open",
  242. "ap_hs20_fetch_osu_stop",
  243. "ap_roam_wpa2_psk",
  244. "ibss_wpa_none_ccmp",
  245. "nfc_wps_er_handover_pk_hash_mismatch_sta",
  246. "go_neg_peers_force_diff_freq",
  247. "p2p_cli_invite",
  248. "sta_ap_scan_2b",
  249. "ap_pmf_sta_unprot_deauth_burst",
  250. "ap_bss_add_remove_during_ht_scan",
  251. "wext_scan_hidden",
  252. "autoscan_exponential",
  253. "nfc_p2p_client",
  254. "wnm_bss_keep_alive",
  255. "ap_inactivity_disconnect",
  256. "scan_bss_expiration_age",
  257. "autoscan_periodic",
  258. "discovery_group_client",
  259. "concurrent_p2pcli",
  260. "ap_bss_add_remove",
  261. "wpas_ap_wps",
  262. "wext_pmksa_cache",
  263. "ibss_wpa_none",
  264. "ap_ht_40mhz_intolerant_ap",
  265. "ibss_rsn",
  266. "discovery_pd_retries",
  267. "ap_wps_setup_locked_timeout",
  268. "ap_vht160",
  269. "dfs_radar",
  270. "dfs",
  271. "grpform_cred_ready_timeout",
  272. "ap_wps_pbc_timeout" ]
  273. for l in long:
  274. if l in tests:
  275. tests.remove(l)
  276. tests.insert(0, l)
  277. logger.setLevel(debug_level)
  278. log_handler = logging.FileHandler('parallel-vm.log')
  279. log_handler.setLevel(debug_level)
  280. fmt = "%(asctime)s %(levelname)s %(message)s"
  281. log_formatter = logging.Formatter(fmt)
  282. log_handler.setFormatter(log_formatter)
  283. logger.addHandler(log_handler)
  284. vm = {}
  285. for i in range(0, num_servers):
  286. print("\rStarting virtual machine {}/{}".format(i + 1, num_servers)),
  287. logger.info("Starting virtual machine {}/{}".format(i + 1, num_servers))
  288. cmd = ['./vm-run.sh', '--delay', str(i), '--timestamp', str(timestamp),
  289. '--ext', 'srv.%d' % (i + 1),
  290. '-i'] + codecov_args + extra_args
  291. vm[i] = {}
  292. vm[i]['first_run_done'] = False
  293. vm[i]['proc'] = subprocess.Popen(cmd,
  294. stdin=subprocess.PIPE,
  295. stdout=subprocess.PIPE,
  296. stderr=subprocess.PIPE)
  297. vm[i]['out'] = ""
  298. vm[i]['err'] = ""
  299. for stream in [ vm[i]['proc'].stdout, vm[i]['proc'].stderr ]:
  300. fd = stream.fileno()
  301. fl = fcntl.fcntl(fd, fcntl.F_GETFL)
  302. fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
  303. print
  304. curses.wrapper(show_progress)
  305. with open('{}/{}-parallel.log'.format(dir, timestamp), 'w') as f:
  306. for i in range(0, num_servers):
  307. f.write('VM {}\n{}\n{}\n'.format(i, vm[i]['out'], vm[i]['err']))
  308. (started, passed, failed, skipped) = get_results()
  309. if first_run_failures:
  310. print "Failed test cases:"
  311. for f in first_run_failures:
  312. print f,
  313. logger.info("Failed: " + f)
  314. print
  315. double_failed = []
  316. for f in failed:
  317. name = f.split(' ')[1]
  318. double_failed.append(name)
  319. for test in first_run_failures:
  320. double_failed.remove(test)
  321. if failed and not double_failed:
  322. print "All failed cases passed on retry"
  323. logger.info("All failed cases passed on retry")
  324. elif double_failed:
  325. print "Failed even on retry:"
  326. for f in double_failed:
  327. print f,
  328. logger.info("Failed on retry: " + f)
  329. print
  330. res = "TOTAL={} PASS={} FAIL={} SKIP={}".format(len(started), len(passed), len(failed), len(skipped))
  331. print(res)
  332. logger.info(res)
  333. print "Logs: " + dir + '/' + str(timestamp)
  334. logger.info("Logs: " + dir + '/' + str(timestamp))
  335. for i in range(0, num_servers):
  336. log = '{}/{}.srv.{}/console'.format(dir, timestamp, i + 1)
  337. with open(log, 'r') as f:
  338. if "Kernel panic" in f.read():
  339. print "Kernel panic in " + log
  340. logger.info("Kernel panic in " + log)
  341. if codecov:
  342. print "Code coverage - preparing report"
  343. for i in range(num_servers):
  344. subprocess.check_call(['./process-codecov.sh',
  345. logdir + ".srv.%d" % (i + 1),
  346. str(i)])
  347. subprocess.check_call(['./combine-codecov.sh', logdir])
  348. print "file://%s/index.html" % logdir
  349. logger.info("Code coverage report: file://%s/index.html" % logdir)
  350. if double_failed:
  351. logger.info("Test run complete - failures found")
  352. sys.exit(2)
  353. if failed:
  354. logger.info("Test run complete - failures found on first run; passed on retry")
  355. sys.exit(1)
  356. logger.info("Test run complete - no failures")
  357. sys.exit(0)
  358. if __name__ == "__main__":
  359. main()