run-tests.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. #!/usr/bin/env python2
  2. #
  3. # Test case executor
  4. # Copyright (c) 2013-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 os
  9. import re
  10. import sys
  11. import time
  12. from datetime import datetime
  13. import argparse
  14. import subprocess
  15. import termios
  16. import logging
  17. logger = logging.getLogger()
  18. scriptsdir = os.path.dirname(os.path.realpath(sys.modules[__name__].__file__))
  19. sys.path.append(os.path.join(scriptsdir, '..', '..', 'wpaspy'))
  20. from wpasupplicant import WpaSupplicant
  21. from hostapd import HostapdGlobal
  22. from check_kernel import check_kernel
  23. from wlantest import Wlantest
  24. from utils import HwsimSkip
  25. def set_term_echo(fd, enabled):
  26. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = termios.tcgetattr(fd)
  27. if enabled:
  28. lflag |= termios.ECHO
  29. else:
  30. lflag &= ~termios.ECHO
  31. termios.tcsetattr(fd, termios.TCSANOW,
  32. [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
  33. def reset_devs(dev, apdev):
  34. ok = True
  35. for d in dev:
  36. try:
  37. d.reset()
  38. except Exception, e:
  39. logger.info("Failed to reset device " + d.ifname)
  40. print str(e)
  41. ok = False
  42. wpas = None
  43. try:
  44. wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
  45. ifaces = wpas.global_request("INTERFACES").splitlines()
  46. for iface in ifaces:
  47. if iface.startswith("wlan"):
  48. wpas.interface_remove(iface)
  49. except Exception, e:
  50. pass
  51. if wpas:
  52. wpas.close_ctrl()
  53. try:
  54. hapd = HostapdGlobal()
  55. hapd.flush()
  56. hapd.remove('wlan3-3')
  57. hapd.remove('wlan3-2')
  58. for ap in apdev:
  59. hapd.remove(ap['ifname'])
  60. except Exception, e:
  61. logger.info("Failed to remove hostapd interface")
  62. print str(e)
  63. ok = False
  64. return ok
  65. def add_log_file(conn, test, run, type, path):
  66. if not os.path.exists(path):
  67. return
  68. contents = None
  69. with open(path, 'r') as f:
  70. contents = f.read()
  71. if contents is None:
  72. return
  73. sql = "INSERT INTO logs(test,run,type,contents) VALUES(?, ?, ?, ?)"
  74. params = (test, run, type, contents)
  75. try:
  76. conn.execute(sql, params)
  77. conn.commit()
  78. except Exception, e:
  79. print "sqlite: " + str(e)
  80. print "sql: %r" % (params, )
  81. def report(conn, prefill, build, commit, run, test, result, duration, logdir,
  82. sql_commit=True):
  83. if conn:
  84. if not build:
  85. build = ''
  86. if not commit:
  87. commit = ''
  88. if prefill:
  89. conn.execute('DELETE FROM results WHERE test=? AND run=? AND result=?', (test, run, 'NOTRUN'))
  90. sql = "INSERT INTO results(test,result,run,time,duration,build,commitid) VALUES(?, ?, ?, ?, ?, ?, ?)"
  91. params = (test, result, run, time.time(), duration, build, commit)
  92. try:
  93. conn.execute(sql, params)
  94. if sql_commit:
  95. conn.commit()
  96. except Exception, e:
  97. print "sqlite: " + str(e)
  98. print "sql: %r" % (params, )
  99. if result == "FAIL":
  100. for log in [ "log", "log0", "log1", "log2", "log3", "log5",
  101. "hostapd", "dmesg", "hwsim0", "hwsim0.pcapng" ]:
  102. add_log_file(conn, test, run, log,
  103. logdir + "/" + test + "." + log)
  104. class DataCollector(object):
  105. def __init__(self, logdir, testname, tracing, dmesg):
  106. self._logdir = logdir
  107. self._testname = testname
  108. self._tracing = tracing
  109. self._dmesg = dmesg
  110. def __enter__(self):
  111. if self._tracing:
  112. output = os.path.abspath(os.path.join(self._logdir, '%s.dat' % (self._testname, )))
  113. self._trace_cmd = subprocess.Popen(['trace-cmd', 'record', '-o', output, '-e', 'mac80211', '-e', 'cfg80211', '-e', 'printk', 'sh', '-c', 'echo STARTED ; read l'],
  114. stdin=subprocess.PIPE,
  115. stdout=subprocess.PIPE,
  116. stderr=open('/dev/null', 'w'),
  117. cwd=self._logdir)
  118. l = self._trace_cmd.stdout.read(7)
  119. while self._trace_cmd.poll() is None and not 'STARTED' in l:
  120. l += self._trace_cmd.stdout.read(1)
  121. res = self._trace_cmd.returncode
  122. if res:
  123. print "Failed calling trace-cmd: returned exit status %d" % res
  124. sys.exit(1)
  125. def __exit__(self, type, value, traceback):
  126. if self._tracing:
  127. self._trace_cmd.stdin.write('DONE\n')
  128. self._trace_cmd.wait()
  129. if self._dmesg:
  130. output = os.path.join(self._logdir, '%s.dmesg' % (self._testname, ))
  131. num = 0
  132. while os.path.exists(output):
  133. output = os.path.join(self._logdir, '%s.dmesg-%d' % (self._testname, num))
  134. num += 1
  135. subprocess.call(['dmesg', '-c'], stdout=open(output, 'w'))
  136. def rename_log(logdir, basename, testname, dev):
  137. try:
  138. import getpass
  139. srcname = os.path.join(logdir, basename)
  140. dstname = os.path.join(logdir, testname + '.' + basename)
  141. num = 0
  142. while os.path.exists(dstname):
  143. dstname = os.path.join(logdir,
  144. testname + '.' + basename + '-' + str(num))
  145. num = num + 1
  146. os.rename(srcname, dstname)
  147. if dev:
  148. dev.relog()
  149. subprocess.call(['chown', '-f', getpass.getuser(), srcname])
  150. except Exception, e:
  151. logger.info("Failed to rename log files")
  152. logger.info(e)
  153. def main():
  154. tests = []
  155. test_modules = []
  156. files = os.listdir(scriptsdir)
  157. for t in files:
  158. m = re.match(r'(test_.*)\.py$', t)
  159. if m:
  160. logger.debug("Import test cases from " + t)
  161. mod = __import__(m.group(1))
  162. test_modules.append(mod.__name__.replace('test_', '', 1))
  163. for key,val in mod.__dict__.iteritems():
  164. if key.startswith("test_"):
  165. tests.append(val)
  166. test_names = list(set([t.__name__.replace('test_', '', 1) for t in tests]))
  167. run = None
  168. parser = argparse.ArgumentParser(description='hwsim test runner')
  169. parser.add_argument('--logdir', metavar='<directory>',
  170. help='log output directory for all other options, ' +
  171. 'must be given if other log options are used')
  172. group = parser.add_mutually_exclusive_group()
  173. group.add_argument('-d', const=logging.DEBUG, action='store_const',
  174. dest='loglevel', default=logging.INFO,
  175. help="verbose debug output")
  176. group.add_argument('-q', const=logging.WARNING, action='store_const',
  177. dest='loglevel', help="be quiet")
  178. parser.add_argument('-S', metavar='<sqlite3 db>', dest='database',
  179. help='database to write results to')
  180. parser.add_argument('--prefill-tests', action='store_true', dest='prefill',
  181. help='prefill test database with NOTRUN before all tests')
  182. parser.add_argument('--commit', metavar='<commit id>',
  183. help='commit ID, only for database')
  184. parser.add_argument('-b', metavar='<build>', dest='build', help='build ID')
  185. parser.add_argument('-L', action='store_true', dest='update_tests_db',
  186. help='List tests (and update descriptions in DB)')
  187. parser.add_argument('-T', action='store_true', dest='tracing',
  188. help='collect tracing per test case (in log directory)')
  189. parser.add_argument('-D', action='store_true', dest='dmesg',
  190. help='collect dmesg per test case (in log directory)')
  191. parser.add_argument('--shuffle-tests', action='store_true',
  192. dest='shuffle_tests',
  193. help='Shuffle test cases to randomize order')
  194. parser.add_argument('--split', help='split tests for parallel execution (<server number>/<total servers>)')
  195. parser.add_argument('--no-reset', action='store_true', dest='no_reset',
  196. help='Do not reset devices at the end of the test')
  197. parser.add_argument('--long', action='store_true',
  198. help='Include test cases that take long time')
  199. parser.add_argument('-f', dest='testmodules', metavar='<test module>',
  200. help='execute only tests from these test modules',
  201. type=str, choices=[[]] + test_modules, nargs='+')
  202. parser.add_argument('-l', metavar='<modules file>', dest='mfile',
  203. help='test modules file name')
  204. parser.add_argument('-i', action='store_true', dest='stdin_ctrl',
  205. help='stdin-controlled test case execution')
  206. parser.add_argument('tests', metavar='<test>', nargs='*', type=str,
  207. help='tests to run (only valid without -f)',
  208. choices=[[]] + test_names)
  209. args = parser.parse_args()
  210. if (args.tests and args.testmodules) or (args.tests and args.mfile) or (args.testmodules and args.mfile):
  211. print 'Invalid arguments - only one of (test, test modules, modules file) can be given.'
  212. sys.exit(2)
  213. if args.database:
  214. import sqlite3
  215. conn = sqlite3.connect(args.database)
  216. conn.execute('CREATE TABLE IF NOT EXISTS results (test,result,run,time,duration,build,commitid)')
  217. conn.execute('CREATE TABLE IF NOT EXISTS tests (test,description)')
  218. conn.execute('CREATE TABLE IF NOT EXISTS logs (test,run,type,contents)')
  219. else:
  220. conn = None
  221. if conn:
  222. run = int(time.time())
  223. # read the modules from the modules file
  224. if args.mfile:
  225. args.testmodules = []
  226. with open(args.mfile) as f:
  227. for line in f.readlines():
  228. line = line.strip()
  229. if not line or line.startswith('#'):
  230. continue
  231. args.testmodules.append(line)
  232. tests_to_run = []
  233. if args.tests:
  234. for selected in args.tests:
  235. for t in tests:
  236. name = t.__name__.replace('test_', '', 1)
  237. if name == selected:
  238. tests_to_run.append(t)
  239. else:
  240. for t in tests:
  241. name = t.__name__.replace('test_', '', 1)
  242. if args.testmodules:
  243. if not t.__module__.replace('test_', '', 1) in args.testmodules:
  244. continue
  245. tests_to_run.append(t)
  246. if args.update_tests_db:
  247. for t in tests_to_run:
  248. name = t.__name__.replace('test_', '', 1)
  249. if t.__doc__ is None:
  250. print name + " - MISSING DESCRIPTION"
  251. else:
  252. print name + " - " + t.__doc__
  253. if conn:
  254. sql = 'INSERT OR REPLACE INTO tests(test,description) VALUES (?, ?)'
  255. params = (name, t.__doc__)
  256. try:
  257. conn.execute(sql, params)
  258. except Exception, e:
  259. print "sqlite: " + str(e)
  260. print "sql: %r" % (params,)
  261. if conn:
  262. conn.commit()
  263. conn.close()
  264. sys.exit(0)
  265. if not args.logdir:
  266. if os.path.exists('logs/current'):
  267. args.logdir = 'logs/current'
  268. else:
  269. args.logdir = 'logs'
  270. # Write debug level log to a file and configurable verbosity to stdout
  271. logger.setLevel(logging.DEBUG)
  272. stdout_handler = logging.StreamHandler()
  273. stdout_handler.setLevel(args.loglevel)
  274. logger.addHandler(stdout_handler)
  275. file_name = os.path.join(args.logdir, 'run-tests.log')
  276. log_handler = logging.FileHandler(file_name)
  277. log_handler.setLevel(logging.DEBUG)
  278. fmt = "%(asctime)s %(levelname)s %(message)s"
  279. log_formatter = logging.Formatter(fmt)
  280. log_handler.setFormatter(log_formatter)
  281. logger.addHandler(log_handler)
  282. dev0 = WpaSupplicant('wlan0', '/tmp/wpas-wlan0')
  283. dev1 = WpaSupplicant('wlan1', '/tmp/wpas-wlan1')
  284. dev2 = WpaSupplicant('wlan2', '/tmp/wpas-wlan2')
  285. dev = [ dev0, dev1, dev2 ]
  286. apdev = [ ]
  287. apdev.append({"ifname": 'wlan3', "bssid": "02:00:00:00:03:00"})
  288. apdev.append({"ifname": 'wlan4', "bssid": "02:00:00:00:04:00"})
  289. for d in dev:
  290. if not d.ping():
  291. logger.info(d.ifname + ": No response from wpa_supplicant")
  292. return
  293. logger.info("DEV: " + d.ifname + ": " + d.p2p_dev_addr())
  294. for ap in apdev:
  295. logger.info("APDEV: " + ap['ifname'])
  296. passed = []
  297. skipped = []
  298. failed = []
  299. # make sure nothing is left over from previous runs
  300. # (if there were any other manual runs or we crashed)
  301. if not reset_devs(dev, apdev):
  302. if conn:
  303. conn.close()
  304. conn = None
  305. sys.exit(1)
  306. if args.dmesg:
  307. subprocess.call(['dmesg', '-c'], stdout=open('/dev/null', 'w'))
  308. if conn and args.prefill:
  309. for t in tests_to_run:
  310. name = t.__name__.replace('test_', '', 1)
  311. report(conn, False, args.build, args.commit, run, name, 'NOTRUN', 0,
  312. args.logdir, sql_commit=False)
  313. conn.commit()
  314. if args.split:
  315. vals = args.split.split('/')
  316. split_server = int(vals[0])
  317. split_total = int(vals[1])
  318. logger.info("Parallel execution - %d/%d" % (split_server, split_total))
  319. split_server -= 1
  320. tests_to_run.sort(key=lambda t: t.__name__)
  321. tests_to_run = [x for i,x in enumerate(tests_to_run) if i % split_total == split_server]
  322. if args.shuffle_tests:
  323. from random import shuffle
  324. shuffle(tests_to_run)
  325. count = 0
  326. if args.stdin_ctrl:
  327. print "READY"
  328. sys.stdout.flush()
  329. num_tests = 0
  330. else:
  331. num_tests = len(tests_to_run)
  332. if args.stdin_ctrl:
  333. set_term_echo(sys.stdin.fileno(), False)
  334. while True:
  335. if args.stdin_ctrl:
  336. test = sys.stdin.readline()
  337. if not test:
  338. break
  339. test = test.splitlines()[0]
  340. if test == '':
  341. break
  342. t = None
  343. for tt in tests:
  344. name = tt.__name__.replace('test_', '', 1)
  345. if name == test:
  346. t = tt
  347. break
  348. if not t:
  349. print "NOT-FOUND"
  350. sys.stdout.flush()
  351. continue
  352. else:
  353. if len(tests_to_run) == 0:
  354. break
  355. t = tests_to_run.pop(0)
  356. name = t.__name__.replace('test_', '', 1)
  357. if log_handler:
  358. log_handler.stream.close()
  359. logger.removeHandler(log_handler)
  360. file_name = os.path.join(args.logdir, name + '.log')
  361. log_handler = logging.FileHandler(file_name)
  362. log_handler.setLevel(logging.DEBUG)
  363. log_handler.setFormatter(log_formatter)
  364. logger.addHandler(log_handler)
  365. reset_ok = True
  366. with DataCollector(args.logdir, name, args.tracing, args.dmesg):
  367. count = count + 1
  368. msg = "START {} {}/{}".format(name, count, num_tests)
  369. logger.info(msg)
  370. if args.loglevel == logging.WARNING:
  371. print msg
  372. sys.stdout.flush()
  373. if t.__doc__:
  374. logger.info("Test: " + t.__doc__)
  375. start = datetime.now()
  376. for d in dev:
  377. try:
  378. d.dump_monitor()
  379. if not d.ping():
  380. raise Exception("PING failed for {}".format(d.ifname))
  381. if not d.global_ping():
  382. raise Exception("Global PING failed for {}".format(d.ifname))
  383. d.request("NOTE TEST-START " + name)
  384. except Exception, e:
  385. logger.info("Failed to issue TEST-START before " + name + " for " + d.ifname)
  386. logger.info(e)
  387. print "FAIL " + name + " - could not start test"
  388. if conn:
  389. conn.close()
  390. conn = None
  391. if args.stdin_ctrl:
  392. set_term_echo(sys.stdin.fileno(), True)
  393. sys.exit(1)
  394. try:
  395. if t.func_code.co_argcount > 2:
  396. params = {}
  397. params['logdir'] = args.logdir
  398. params['long'] = args.long
  399. t(dev, apdev, params)
  400. elif t.func_code.co_argcount > 1:
  401. t(dev, apdev)
  402. else:
  403. t(dev)
  404. result = "PASS"
  405. except HwsimSkip, e:
  406. logger.info("Skip test case: %s" % e)
  407. result = "SKIP"
  408. except Exception, e:
  409. logger.info(e)
  410. if args.loglevel == logging.WARNING:
  411. print "Exception: " + str(e)
  412. result = "FAIL"
  413. for d in dev:
  414. try:
  415. d.dump_monitor()
  416. d.request("NOTE TEST-STOP " + name)
  417. except Exception, e:
  418. logger.info("Failed to issue TEST-STOP after {} for {}".format(name, d.ifname))
  419. logger.info(e)
  420. result = "FAIL"
  421. wpas = None
  422. try:
  423. wpas = WpaSupplicant(global_iface="/tmp/wpas-wlan5")
  424. rename_log(args.logdir, 'log5', name, wpas)
  425. if not args.no_reset:
  426. wpas.remove_ifname()
  427. except Exception, e:
  428. pass
  429. if wpas:
  430. wpas.close_ctrl()
  431. if args.no_reset:
  432. print "Leaving devices in current state"
  433. else:
  434. reset_ok = reset_devs(dev, apdev)
  435. for i in range(0, 3):
  436. rename_log(args.logdir, 'log' + str(i), name, dev[i])
  437. try:
  438. hapd = HostapdGlobal()
  439. except Exception, e:
  440. print "Failed to connect to hostapd interface"
  441. print str(e)
  442. reset_ok = False
  443. result = "FAIL"
  444. hapd = None
  445. rename_log(args.logdir, 'hostapd', name, hapd)
  446. if hapd:
  447. del hapd
  448. hapd = None
  449. wt = Wlantest()
  450. rename_log(args.logdir, 'hwsim0.pcapng', name, wt)
  451. rename_log(args.logdir, 'hwsim0', name, wt)
  452. if os.path.exists(os.path.join(args.logdir, 'fst-wpa_supplicant')):
  453. rename_log(args.logdir, 'fst-wpa_supplicant', name, None)
  454. if os.path.exists(os.path.join(args.logdir, 'fst-hostapd')):
  455. rename_log(args.logdir, 'fst-hostapd', name, None)
  456. end = datetime.now()
  457. diff = end - start
  458. if result == 'PASS' and args.dmesg:
  459. if not check_kernel(os.path.join(args.logdir, name + '.dmesg')):
  460. logger.info("Kernel issue found in dmesg - mark test failed")
  461. result = 'FAIL'
  462. if result == 'PASS':
  463. passed.append(name)
  464. elif result == 'SKIP':
  465. skipped.append(name)
  466. else:
  467. failed.append(name)
  468. report(conn, args.prefill, args.build, args.commit, run, name, result,
  469. diff.total_seconds(), args.logdir)
  470. result = "{} {} {} {}".format(result, name, diff.total_seconds(), end)
  471. logger.info(result)
  472. if args.loglevel == logging.WARNING:
  473. print result
  474. sys.stdout.flush()
  475. if not reset_ok:
  476. print "Terminating early due to device reset failure"
  477. break
  478. if args.stdin_ctrl:
  479. set_term_echo(sys.stdin.fileno(), True)
  480. if log_handler:
  481. log_handler.stream.close()
  482. logger.removeHandler(log_handler)
  483. file_name = os.path.join(args.logdir, 'run-tests.log')
  484. log_handler = logging.FileHandler(file_name)
  485. log_handler.setLevel(logging.DEBUG)
  486. log_handler.setFormatter(log_formatter)
  487. logger.addHandler(log_handler)
  488. if conn:
  489. conn.close()
  490. if len(failed):
  491. logger.info("passed {} test case(s)".format(len(passed)))
  492. logger.info("skipped {} test case(s)".format(len(skipped)))
  493. logger.info("failed tests: " + ' '.join(failed))
  494. if args.loglevel == logging.WARNING:
  495. print "failed tests: " + ' '.join(failed)
  496. sys.exit(1)
  497. logger.info("passed all {} test case(s)".format(len(passed)))
  498. if len(skipped):
  499. logger.info("skipped {} test case(s)".format(len(skipped)))
  500. if args.loglevel == logging.WARNING:
  501. print "passed all {} test case(s)".format(len(passed))
  502. if len(skipped):
  503. print "skipped {} test case(s)".format(len(skipped))
  504. if __name__ == "__main__":
  505. main()