framework_test.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. from benchmark.fortune_html_parser import FortuneHTMLParser
  2. from setup.linux import setup_util
  3. from benchmark.test_types import *
  4. import importlib
  5. import os
  6. import subprocess
  7. import time
  8. import re
  9. from pprint import pprint
  10. import sys
  11. import traceback
  12. import json
  13. import logging
  14. import csv
  15. import shlex
  16. import math
  17. from threading import Thread
  18. from threading import Event
  19. from utils import header
  20. class FrameworkTest:
  21. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  22. # Used for test types that do not require a database -
  23. # These tests are run at multiple concurrency levels
  24. concurrency_template = """
  25. echo ""
  26. echo "---------------------------------------------------------"
  27. echo " Running Primer {name}"
  28. echo " {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}\""
  29. echo "---------------------------------------------------------"
  30. echo ""
  31. {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}"
  32. sleep 5
  33. echo ""
  34. echo "---------------------------------------------------------"
  35. echo " Running Warmup {name}"
  36. echo " {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  37. echo "---------------------------------------------------------"
  38. echo ""
  39. {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  40. sleep 5
  41. echo ""
  42. echo "---------------------------------------------------------"
  43. echo " Synchronizing time"
  44. echo "---------------------------------------------------------"
  45. echo ""
  46. ntpdate -s pool.ntp.org
  47. for c in {interval}
  48. do
  49. echo ""
  50. echo "---------------------------------------------------------"
  51. echo " Concurrency: $c for {name}"
  52. echo " {wrk} {headers} -d {duration} -c $c --timeout $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\" -s ~/pipeline.lua -- {pipeline}"
  53. echo "---------------------------------------------------------"
  54. echo ""
  55. STARTTIME=$(date +"%s")
  56. {wrk} {headers} -d {duration} -c $c --timeout $c -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url} -s ~/pipeline.lua -- {pipeline}
  57. echo "STARTTIME $STARTTIME"
  58. echo "ENDTIME $(date +"%s")"
  59. sleep 2
  60. done
  61. """
  62. # Used for test types that require a database -
  63. # These tests run at a static concurrency level and vary the size of
  64. # the query sent with each request
  65. query_template = """
  66. echo ""
  67. echo "---------------------------------------------------------"
  68. echo " Running Primer {name}"
  69. echo " wrk {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}2\""
  70. echo "---------------------------------------------------------"
  71. echo ""
  72. wrk {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}2"
  73. sleep 5
  74. echo ""
  75. echo "---------------------------------------------------------"
  76. echo " Running Warmup {name}"
  77. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  78. echo "---------------------------------------------------------"
  79. echo ""
  80. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  81. sleep 5
  82. echo ""
  83. echo "---------------------------------------------------------"
  84. echo " Synchronizing time"
  85. echo "---------------------------------------------------------"
  86. echo ""
  87. ntpdate -s pool.ntp.org
  88. for c in {interval}
  89. do
  90. echo ""
  91. echo "---------------------------------------------------------"
  92. echo " Queries: $c for {name}"
  93. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  94. echo "---------------------------------------------------------"
  95. echo ""
  96. STARTTIME=$(date +"%s")
  97. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  98. echo "STARTTIME $STARTTIME"
  99. echo "ENDTIME $(date +"%s")"
  100. sleep 2
  101. done
  102. """
  103. ############################################################
  104. # Test Variables
  105. ############################################################
  106. JSON = "json"
  107. DB = "db"
  108. QUERY = "query"
  109. FORTUNE = "fortune"
  110. UPDATE = "update"
  111. PLAINTEXT = "plaintext"
  112. ##########################################################################################
  113. # Public Methods
  114. ##########################################################################################
  115. ############################################################
  116. # Parses the given HTML string and asks a FortuneHTMLParser
  117. # whether the parsed string is a valid fortune return.
  118. ############################################################
  119. def validateFortune(self, htmlString, out, err):
  120. err_str = ""
  121. if htmlString is None or len(htmlString) == 0:
  122. err_str += "Empty Response"
  123. return (False, err_str)
  124. try:
  125. parser = FortuneHTMLParser()
  126. parser.feed(htmlString)
  127. valid = parser.isValidFortune(out)
  128. return (valid, '' if valid else 'Did not pass validation')
  129. except:
  130. print "Got exception when trying to validate the fortune test: {exception} ".format(exception=traceback.format_exc())
  131. return (False, err_str)
  132. ############################################################
  133. # Validates the jsonString is an array with a length of
  134. # 2, that each entry in the array is a JSON object, that
  135. # each object has an "id" and a "randomNumber" key, and that
  136. # both keys map to integers.
  137. ############################################################
  138. def validateUpdate(self, jsonString, out, err):
  139. err_str = ""
  140. if jsonString is None or len(jsonString) == 0:
  141. err_str += "Empty Response"
  142. return (False, err_str)
  143. try:
  144. arr = [{k.lower(): v for k,v in d.iteritems()} for d in json.loads(jsonString)]
  145. if len(arr) != 2:
  146. err_str += "Expected array of length 2. Got length {length}.\n".format(length=len(arr))
  147. for obj in arr:
  148. id_ret_val = True
  149. random_num_ret_val = True
  150. if "id" not in obj or "randomnumber" not in obj:
  151. err_str += "Expected keys id and randomNumber to be in JSON string.\n"
  152. return (False, err_str)
  153. try:
  154. if not isinstance(float(obj["id"]), float):
  155. id_ret_val=False
  156. except:
  157. id_ret_val=False
  158. if not id_ret_val:
  159. err_str += "Expected id to be type int or float, got '{rand}'.\n".format(rand=obj["randomnumber"])
  160. try:
  161. if not isinstance(float(obj["randomnumber"]), float):
  162. random_num_ret_val=False
  163. except:
  164. random_num_ret_val=False
  165. if not random_num_ret_val:
  166. err_str += "Expected randomNumber to be type int or float, got '{rand}'.\n".format(rand=obj["randomnumber"])
  167. except:
  168. err_str += "Got exception when trying to validate the update test: {exception}\n".format(exception=traceback.format_exc())
  169. return (True, ) if len(err_str) == 0 else (False, err_str)
  170. ############################################################
  171. # start(benchmarker)
  172. # Start the test using it's setup file
  173. ############################################################
  174. def start(self, out, err):
  175. # Load profile for this installation
  176. profile="%s/bash_profile.sh" % self.directory
  177. if not os.path.exists(profile):
  178. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  179. profile="$FWROOT/config/benchmark_profile"
  180. # Setup variables for TROOT and IROOT
  181. setup_util.replace_environ(config=profile,
  182. command='export TROOT=%s && export IROOT=%s' %
  183. (self.directory, self.install_root))
  184. # Because start can take so long, we print a dot to let the user know
  185. # we are working
  186. class ProgressPrinterThread(Thread):
  187. def __init__(self, event):
  188. Thread.__init__(self)
  189. self.stopped = event
  190. def run(self):
  191. while not self.stopped.wait(20):
  192. sys.stderr.write("Waiting for start to return...\n")
  193. stopFlag = Event()
  194. thread = ProgressPrinterThread(stopFlag)
  195. thread.start()
  196. # Run the module start (inside parent of TROOT)
  197. # - we use the parent as a historical accident - a lot of tests
  198. # use subprocess's cwd argument already
  199. previousDir = os.getcwd()
  200. os.chdir(os.path.dirname(self.troot))
  201. logging.info("Running setup module start (cwd=%s)", os.path.dirname(self.troot))
  202. try:
  203. retcode = self.setup_module.start(self, out, err)
  204. if retcode == None:
  205. retcode = 0
  206. except Exception:
  207. retcode = 1
  208. st = traceback.format_exc()
  209. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  210. st = "Start exception:\n%s" % st
  211. logging.info(st)
  212. err.write(st + '\n')
  213. os.chdir(previousDir)
  214. # Stop the progress printer
  215. stopFlag.set()
  216. logging.info("Called setup.py start")
  217. return retcode
  218. ############################################################
  219. # End start
  220. ############################################################
  221. ############################################################
  222. # stop(benchmarker)
  223. # Stops the test using it's setup file
  224. ############################################################
  225. def stop(self, out, err):
  226. # Load profile for this installation
  227. profile="%s/bash_profile.sh" % self.directory
  228. if not os.path.exists(profile):
  229. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  230. profile="$FWROOT/config/benchmark_profile"
  231. setup_util.replace_environ(config=profile,
  232. command='export TROOT=%s && export IROOT=%s' %
  233. (self.directory, self.install_root))
  234. # Run the module stop (inside parent of TROOT)
  235. # - we use the parent as a historical accident - a lot of tests
  236. # use subprocess's cwd argument already
  237. previousDir = os.getcwd()
  238. os.chdir(os.path.dirname(self.troot))
  239. logging.info("Running setup module stop (cwd=%s)", os.path.dirname(self.troot))
  240. try:
  241. retcode = self.setup_module.stop(out, err)
  242. if retcode == None:
  243. retcode = 0
  244. except Exception:
  245. retcode = 1
  246. st = traceback.format_exc()
  247. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  248. st = "Stop exception:\n%s\n" % st
  249. logging.info(st)
  250. err.write(st + '\n')
  251. os.chdir(previousDir)
  252. # Give processes sent a SIGTERM a moment to shut down gracefully
  253. time.sleep(5)
  254. return retcode
  255. ############################################################
  256. # End stop
  257. ############################################################
  258. ############################################################
  259. # verify_urls
  260. # Verifys each of the URLs for this test. THis will sinply
  261. # curl the URL and check for it's return status.
  262. # For each url, a flag will be set on this object for whether
  263. # or not it passed
  264. # Returns True if all verifications succeeded
  265. ############################################################
  266. def verify_urls(self, out, err):
  267. result = True
  268. def verify_type(test_type):
  269. test = self.runTests[test_type]
  270. out.write(header("VERIFYING %s" % test_type.upper()))
  271. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  272. try:
  273. results = test.verify(base_url)
  274. except Exception as e:
  275. results = [('fail',"""Caused Exception in TFB
  276. This almost certainly means your return value is incorrect,
  277. but also that you have found a bug. Please submit an issue
  278. including this message: %s\n%s""" % (e, traceback.format_exc()),
  279. base_url)]
  280. logging.warning("Verifying test %s for %s caused an exception: %s", test_type, self.name, e)
  281. traceback.format_exc()
  282. test.failed = any(result is 'fail' for (result, reason, url) in results)
  283. test.warned = any(result is 'warn' for (result, reason, url) in results)
  284. test.passed = all(result is 'pass' for (result, reason, url) in results)
  285. def output_result(result, reason, url):
  286. out.write(" %s for %s\n" % (result.upper(), url))
  287. print " %s for %s" % (result.upper(), url)
  288. if reason is not None and len(reason) != 0:
  289. for line in reason.splitlines():
  290. out.write(" " + line + '\n')
  291. print " " + line
  292. [output_result(r1,r2,url) for (r1, r2, url) in results]
  293. if test.failed:
  294. self.benchmarker.report_verify_results(self, test_type, 'fail')
  295. elif test.warned:
  296. self.benchmarker.report_verify_results(self, test_type, 'warn')
  297. elif test.passed:
  298. self.benchmarker.report_verify_results(self, test_type, 'pass')
  299. else:
  300. raise Exception("What the hell")
  301. # JSON
  302. if self.runTests[self.JSON]:
  303. out.write(header("VERIFYING JSON (%s)" % self.json_url))
  304. out.flush()
  305. url = self.benchmarker.generate_url(self.json_url, self.port)
  306. output = self.__curl_url(url, self.JSON, out, err)
  307. out.write("VALIDATING JSON ... ")
  308. ret_tuple = self.validateJson(output, out, err)
  309. if ret_tuple[0]:
  310. self.json_url_passed = True
  311. out.write("PASS\n\n")
  312. self.benchmarker.report_verify_results(self, self.JSON, 'pass')
  313. else:
  314. self.json_url_passed = False
  315. out.write("\nFAIL" + ret_tuple[1] + "\n\n")
  316. self.benchmarker.report_verify_results(self, self.JSON, 'fail')
  317. result = False
  318. out.flush()
  319. # DB
  320. if self.runTests[self.DB]:
  321. out.write(header("VERIFYING DB (%s)" % self.db_url))
  322. out.flush()
  323. url = self.benchmarker.generate_url(self.db_url, self.port)
  324. output = self.__curl_url(url, self.DB, out, err)
  325. validate_ret_tuple = self.validateDb(output, out, err)
  326. validate_strict_ret_tuple = self.validateDbStrict(output, out, err)
  327. if validate_ret_tuple[0]:
  328. self.db_url_passed = True
  329. else:
  330. self.db_url_passed = False
  331. if validate_strict_ret_tuple:
  332. self.db_url_warn = False
  333. else:
  334. self.db_url_warn = True
  335. out.write("VALIDATING DB ... ")
  336. if self.db_url_passed:
  337. out.write("PASS")
  338. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  339. if self.db_url_warn:
  340. out.write(" (with warnings) " + validate_strict_ret_tuple[1])
  341. self.benchmarker.report_verify_results(self, self.DB, 'warn')
  342. out.write("\n\n")
  343. else:
  344. self.benchmarker.report_verify_results(self, self.DB, 'fail')
  345. out.write("\nFAIL" + validate_ret_tuple[1])
  346. result = False
  347. out.flush()
  348. # Query
  349. if self.runTests[self.QUERY]:
  350. out.write(header("VERIFYING QUERY (%s)" % self.query_url+"2"))
  351. out.flush()
  352. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  353. output = self.__curl_url(url, self.QUERY, out, err)
  354. ret_tuple = self.validateQuery(output, out, err)
  355. if ret_tuple[0]:
  356. self.query_url_passed = True
  357. out.write(self.query_url + "2 - PASS\n\n")
  358. else:
  359. self.query_url_passed = False
  360. out.write(self.query_url + "2 - FAIL " + ret_tuple[1] + "\n\n")
  361. out.write("-----------------------------------------------------\n\n")
  362. out.flush()
  363. self.query_url_warn = False
  364. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  365. output2 = self.__curl_url(url2, self.QUERY, out, err)
  366. ret_tuple = self.validateQueryOneOrLess(output2, out, err)
  367. if not ret_tuple[0]:
  368. self.query_url_warn = True
  369. out.write(self.query_url + "0 - WARNING " + ret_tuple[1] + "\n\n")
  370. else:
  371. out.write(self.query_url + "0 - PASS\n\n")
  372. out.write("-----------------------------------------------------\n\n")
  373. out.flush()
  374. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  375. output3 = self.__curl_url(url3, self.QUERY, out, err)
  376. ret_tuple = self.validateQueryOneOrLess(output3, out, err)
  377. if not ret_tuple[0]:
  378. self.query_url_warn = True
  379. out.write(self.query_url + "foo - WARNING " + ret_tuple[1] + "\n\n")
  380. else:
  381. out.write(self.query_url + "foo - PASS\n\n")
  382. out.write("-----------------------------------------------------\n\n")
  383. out.flush()
  384. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  385. output4 = self.__curl_url(url4, self.QUERY, out, err)
  386. ret_tuple = self.validateQueryFiveHundredOrMore(output4, out, err)
  387. if not ret_tuple[0]:
  388. self.query_url_warn = True
  389. out.write(self.query_url + "501 - WARNING " + ret_tuple[1] + "\n\n")
  390. else:
  391. out.write(self.query_url + "501 - PASS\n\n")
  392. out.write("-----------------------------------------------------\n\n\n")
  393. out.flush()
  394. out.write("VALIDATING QUERY ... ")
  395. if self.query_url_passed:
  396. out.write("PASS")
  397. self.benchmarker.report_verify_results(self, self.QUERY, 'pass')
  398. if self.query_url_warn:
  399. out.write(" (with warnings)")
  400. self.benchmarker.report_verify_results(self, self.QUERY, 'warn')
  401. out.write("\n\n")
  402. else:
  403. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  404. self.benchmarker.report_verify_results(self, self.QUERY, 'fail')
  405. result = False
  406. out.flush()
  407. # Fortune
  408. if self.runTests[self.FORTUNE]:
  409. out.write(header("VERIFYING FORTUNE (%s)" % self.fortune_url))
  410. out.flush()
  411. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  412. output = self.__curl_url(url, self.FORTUNE, out, err)
  413. out.write("VALIDATING FORTUNE ... ")
  414. ret_tuple = self.validateFortune(output, out, err)
  415. if ret_tuple[0]:
  416. self.fortune_url_passed = True
  417. out.write("PASS\n\n")
  418. self.benchmarker.report_verify_results(self, self.FORTUNE, 'pass')
  419. else:
  420. self.fortune_url_passed = False
  421. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  422. self.benchmarker.report_verify_results(self, self.FORTUNE, 'fail')
  423. result = False
  424. out.flush()
  425. # Update
  426. if self.runTests[self.UPDATE]:
  427. out.write(header("VERIFYING UPDATE (%s)" % self.update_url))
  428. out.flush()
  429. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  430. output = self.__curl_url(url, self.UPDATE, out, err)
  431. out.write("VALIDATING UPDATE ... ")
  432. ret_tuple = self.validateUpdate(output, out, err)
  433. if ret_tuple[0]:
  434. self.update_url_passed = True
  435. out.write("PASS\n\n")
  436. self.benchmarker.report_verify_results(self, self.UPDATE, 'pass')
  437. else:
  438. self.update_url_passed = False
  439. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  440. self.benchmarker.report_verify_results(self, self.UPDATE, 'fail')
  441. result = False
  442. out.flush()
  443. # plaintext
  444. if self.runTests[self.PLAINTEXT]:
  445. out.write(header("VERIFYING PLAINTEXT (%s)" % self.plaintext_url))
  446. out.flush()
  447. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  448. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  449. out.write("VALIDATING PLAINTEXT ... ")
  450. ret_tuple = self.validatePlaintext(output, out, err)
  451. if ret_tuple[0]:
  452. self.plaintext_url_passed = True
  453. out.write("PASS\n\n")
  454. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'pass')
  455. else:
  456. self.plaintext_url_passed = False
  457. out.write("\nFAIL\n\n" + ret_tuple[1] + "\n\n")
  458. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'fail')
  459. result = False
  460. out.flush()
  461. return result
  462. ############################################################
  463. # End verify_urls
  464. ############################################################
  465. ############################################################
  466. # benchmark
  467. # Runs the benchmark for each type of test that it implements
  468. # JSON/DB/Query.
  469. ############################################################
  470. def benchmark(self, out, err):
  471. def benchmark_type(test_type):
  472. out.write("BENCHMARKING %s ... " % test_type.upper())
  473. test = self.runTests[test_type]
  474. output_file = self.benchmarker.output_file(self.name, test_type)
  475. if not os.path.exists(output_file):
  476. # Open to create the empty file
  477. with open(output_file, 'w'):
  478. pass
  479. if test.passed:
  480. if test.requires_db:
  481. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  482. else:
  483. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  484. self.__begin_logging(test_type)
  485. self.__run_benchmark(remote_script, output_file, err)
  486. self.__end_logging()
  487. results = self.__parse_test(test_type)
  488. print "Benchmark results:"
  489. pprint(results)
  490. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  491. out.write( "Complete\n" )
  492. out.flush()
  493. # JSON
  494. if self.runTests[self.JSON]:
  495. try:
  496. out.write("BENCHMARKING JSON ... ")
  497. out.flush()
  498. results = None
  499. output_file = self.benchmarker.output_file(self.name, self.JSON)
  500. if not os.path.exists(output_file):
  501. with open(output_file, 'w'):
  502. # Simply opening the file in write mode should create the empty file.
  503. pass
  504. if self.json_url_passed:
  505. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  506. self.__begin_logging(self.JSON)
  507. self.__run_benchmark(remote_script, output_file, err)
  508. self.__end_logging()
  509. results = self.__parse_test(self.JSON)
  510. print results
  511. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  512. out.write( "Complete\n" )
  513. out.flush()
  514. except AttributeError:
  515. pass
  516. # DB
  517. if self.runTests[self.DB]:
  518. try:
  519. out.write("BENCHMARKING DB ... ")
  520. out.flush()
  521. results = None
  522. output_file = self.benchmarker.output_file(self.name, self.DB)
  523. if not os.path.exists(output_file):
  524. with open(output_file, 'w'):
  525. # Simply opening the file in write mode should create the empty file.
  526. pass
  527. if self.db_url_passed:
  528. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  529. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  530. self.__begin_logging(self.DB)
  531. self.__run_benchmark(remote_script, output_file, err)
  532. self.__end_logging()
  533. results = self.__parse_test(self.DB)
  534. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  535. out.write( "Complete\n" )
  536. except AttributeError:
  537. pass
  538. # Query
  539. if self.runTests[self.QUERY]:
  540. try:
  541. out.write("BENCHMARKING Query ... ")
  542. out.flush()
  543. results = None
  544. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  545. if not os.path.exists(output_file):
  546. with open(output_file, 'w'):
  547. # Simply opening the file in write mode should create the empty file.
  548. pass
  549. if self.query_url_passed:
  550. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  551. self.__begin_logging(self.QUERY)
  552. self.__run_benchmark(remote_script, output_file, err)
  553. self.__end_logging()
  554. results = self.__parse_test(self.QUERY)
  555. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  556. out.write( "Complete\n" )
  557. out.flush()
  558. except AttributeError:
  559. pass
  560. # fortune
  561. if self.runTests[self.FORTUNE]:
  562. try:
  563. out.write("BENCHMARKING Fortune ... ")
  564. out.flush()
  565. results = None
  566. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  567. if not os.path.exists(output_file):
  568. with open(output_file, 'w'):
  569. # Simply opening the file in write mode should create the empty file.
  570. pass
  571. if self.fortune_url_passed:
  572. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  573. self.__begin_logging(self.FORTUNE)
  574. self.__run_benchmark(remote_script, output_file, err)
  575. self.__end_logging()
  576. results = self.__parse_test(self.FORTUNE)
  577. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  578. out.write( "Complete\n" )
  579. out.flush()
  580. except AttributeError:
  581. pass
  582. # update
  583. if self.runTests[self.UPDATE]:
  584. try:
  585. out.write("BENCHMARKING Update ... ")
  586. out.flush()
  587. results = None
  588. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  589. if not os.path.exists(output_file):
  590. with open(output_file, 'w'):
  591. # Simply opening the file in write mode should create the empty file.
  592. pass
  593. if self.update_url_passed:
  594. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  595. self.__begin_logging(self.UPDATE)
  596. self.__run_benchmark(remote_script, output_file, err)
  597. self.__end_logging()
  598. results = self.__parse_test(self.UPDATE)
  599. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  600. out.write( "Complete\n" )
  601. out.flush()
  602. except AttributeError:
  603. pass
  604. # plaintext
  605. if self.runTests[self.PLAINTEXT]:
  606. try:
  607. out.write("BENCHMARKING Plaintext ... ")
  608. out.flush()
  609. results = None
  610. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  611. if not os.path.exists(output_file):
  612. with open(output_file, 'w'):
  613. # Simply opening the file in write mode should create the empty file.
  614. pass
  615. if self.plaintext_url_passed:
  616. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  617. self.__begin_logging(self.PLAINTEXT)
  618. self.__run_benchmark(remote_script, output_file, err)
  619. self.__end_logging()
  620. results = self.__parse_test(self.PLAINTEXT)
  621. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  622. out.write( "Complete\n" )
  623. out.flush()
  624. except AttributeError:
  625. traceback.print_exc()
  626. pass
  627. ############################################################
  628. # End benchmark
  629. ############################################################
  630. ############################################################
  631. # parse_all
  632. # Method meant to be run for a given timestamp
  633. ############################################################
  634. def parse_all(self):
  635. # JSON
  636. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  637. results = self.__parse_test(self.JSON)
  638. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  639. # DB
  640. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  641. results = self.__parse_test(self.DB)
  642. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  643. # Query
  644. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  645. results = self.__parse_test(self.QUERY)
  646. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  647. # Fortune
  648. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  649. results = self.__parse_test(self.FORTUNE)
  650. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  651. # Update
  652. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  653. results = self.__parse_test(self.UPDATE)
  654. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  655. # Plaintext
  656. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  657. results = self.__parse_test(self.PLAINTEXT)
  658. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  659. ############################################################
  660. # End parse_all
  661. ############################################################
  662. ############################################################
  663. # __parse_test(test_type)
  664. ############################################################
  665. def __parse_test(self, test_type):
  666. try:
  667. results = dict()
  668. results['results'] = []
  669. stats = []
  670. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  671. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  672. is_warmup = True
  673. rawData = None
  674. for line in raw_data:
  675. if "Queries:" in line or "Concurrency:" in line:
  676. is_warmup = False
  677. rawData = None
  678. continue
  679. if "Warmup" in line or "Primer" in line:
  680. is_warmup = True
  681. continue
  682. if not is_warmup:
  683. if rawData == None:
  684. rawData = dict()
  685. results['results'].append(rawData)
  686. #if "Requests/sec:" in line:
  687. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  688. # rawData['reportedResults'] = m.group(1)
  689. # search for weighttp data such as succeeded and failed.
  690. if "Latency" in line:
  691. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  692. if len(m) == 4:
  693. rawData['latencyAvg'] = m[0]
  694. rawData['latencyStdev'] = m[1]
  695. rawData['latencyMax'] = m[2]
  696. # rawData['latencyStdevPercent'] = m[3]
  697. #if "Req/Sec" in line:
  698. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  699. # if len(m) == 4:
  700. # rawData['requestsAvg'] = m[0]
  701. # rawData['requestsStdev'] = m[1]
  702. # rawData['requestsMax'] = m[2]
  703. # rawData['requestsStdevPercent'] = m[3]
  704. #if "requests in" in line:
  705. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  706. # if m != None:
  707. # # parse out the raw time, which may be in minutes or seconds
  708. # raw_time = m.group(1)
  709. # if "ms" in raw_time:
  710. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  711. # elif "s" in raw_time:
  712. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  713. # elif "m" in raw_time:
  714. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  715. # elif "h" in raw_time:
  716. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  717. if "requests in" in line:
  718. m = re.search("([0-9]+) requests in", line)
  719. if m != None:
  720. rawData['totalRequests'] = int(m.group(1))
  721. if "Socket errors" in line:
  722. if "connect" in line:
  723. m = re.search("connect ([0-9]+)", line)
  724. rawData['connect'] = int(m.group(1))
  725. if "read" in line:
  726. m = re.search("read ([0-9]+)", line)
  727. rawData['read'] = int(m.group(1))
  728. if "write" in line:
  729. m = re.search("write ([0-9]+)", line)
  730. rawData['write'] = int(m.group(1))
  731. if "timeout" in line:
  732. m = re.search("timeout ([0-9]+)", line)
  733. rawData['timeout'] = int(m.group(1))
  734. if "Non-2xx" in line:
  735. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  736. if m != None:
  737. rawData['5xx'] = int(m.group(1))
  738. if "STARTTIME" in line:
  739. m = re.search("[0-9]+", line)
  740. rawData["startTime"] = int(m.group(0))
  741. if "ENDTIME" in line:
  742. m = re.search("[0-9]+", line)
  743. rawData["endTime"] = int(m.group(0))
  744. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  745. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  746. stats.append(test_stats)
  747. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  748. json.dump(stats, stats_file)
  749. return results
  750. except IOError:
  751. return None
  752. ############################################################
  753. # End benchmark
  754. ############################################################
  755. ##########################################################################################
  756. # Private Methods
  757. ##########################################################################################
  758. ############################################################
  759. # __run_benchmark(script, output_file)
  760. # Runs a single benchmark using the script which is a bash
  761. # template that uses weighttp to run the test. All the results
  762. # outputed to the output_file.
  763. ############################################################
  764. def __run_benchmark(self, script, output_file, err):
  765. with open(output_file, 'w') as raw_file:
  766. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  767. p.communicate(script)
  768. err.flush()
  769. ############################################################
  770. # End __run_benchmark
  771. ############################################################
  772. ############################################################
  773. # __generate_concurrency_script(url, port)
  774. # Generates the string containing the bash script that will
  775. # be run on the client to benchmark a single test. This
  776. # specifically works for the variable concurrency tests (JSON
  777. # and DB)
  778. ############################################################
  779. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  780. if len(intervals) == 0:
  781. intervals = self.benchmarker.concurrency_levels
  782. headers = self.__get_request_headers(accept_header)
  783. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  784. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  785. interval=" ".join("{}".format(item) for item in intervals),
  786. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  787. pipeline=pipeline)
  788. ############################################################
  789. # End __generate_concurrency_script
  790. ############################################################
  791. ############################################################
  792. # __generate_query_script(url, port)
  793. # Generates the string containing the bash script that will
  794. # be run on the client to benchmark a single test. This
  795. # specifically works for the variable query tests (Query)
  796. ############################################################
  797. def __generate_query_script(self, url, port, accept_header):
  798. headers = self.__get_request_headers(accept_header)
  799. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  800. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  801. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  802. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  803. ############################################################
  804. # End __generate_query_script
  805. ############################################################
  806. ############################################################
  807. # __get_request_headers(accept_header)
  808. # Generates the complete HTTP header string
  809. ############################################################
  810. def __get_request_headers(self, accept_header):
  811. return self.headers_template.format(accept=accept_header)
  812. ############################################################
  813. # End __format_request_headers
  814. ############################################################
  815. ############################################################
  816. # __curl_url
  817. # Dump HTTP response and headers. Throw exception if there
  818. # is an HTTP error.
  819. ############################################################
  820. def __curl_url(self, url, testType, out, err):
  821. output = None
  822. try:
  823. # Use -m 15 to make curl stop trying after 15sec.
  824. # Use -i to output response with headers.
  825. # Don't use -f so that the HTTP response code is ignored.
  826. # Use --stderr - to redirect stderr to stdout so we get
  827. # error output for sure in stdout.
  828. # Use -sS to hide progress bar, but show errors.
  829. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  830. # HTTP output may not end in a newline, so add that here.
  831. out.write( "\n\n" )
  832. out.flush()
  833. err.flush()
  834. # We need to get the respond body from the curl and return it.
  835. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  836. output = p.communicate()
  837. except:
  838. pass
  839. if output:
  840. # We have the response body - return it
  841. return output[0]
  842. ##############################################################
  843. # End __curl_url
  844. ##############################################################
  845. def requires_database(self):
  846. '''Returns True/False if this test requires a database'''
  847. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  848. ############################################################
  849. # __begin_logging
  850. # Starts a thread to monitor the resource usage, to be synced with the client's time
  851. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  852. ############################################################
  853. def __begin_logging(self, test_name):
  854. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_name))
  855. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  856. --raw --socket --tcp --udp --unix --vm --disk-util \
  857. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  858. cmd = shlex.split(dstat_string)
  859. dev_null = open(os.devnull, "w")
  860. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  861. ##############################################################
  862. # End __begin_logging
  863. ##############################################################
  864. ##############################################################
  865. # Begin __end_logging
  866. # Stops the logger thread and blocks until shutdown is complete.
  867. ##############################################################
  868. def __end_logging(self):
  869. self.subprocess_handle.terminate()
  870. self.subprocess_handle.communicate()
  871. ##############################################################
  872. # End __end_logging
  873. ##############################################################
  874. ##############################################################
  875. # Begin __parse_stats
  876. # For each test type, process all the statistics, and return a multi-layered dictionary
  877. # that has a structure as follows:
  878. # (timestamp)
  879. # | (main header) - group that the stat is in
  880. # | | (sub header) - title of the stat
  881. # | | | (stat) - the stat itself, usually a floating point number
  882. ##############################################################
  883. def __parse_stats(self, test_type, start_time, end_time, interval):
  884. stats_dict = dict()
  885. stats_file = self.benchmarker.stats_file(self.name, test_type)
  886. with open(stats_file) as stats:
  887. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  888. pass
  889. stats_reader = csv.reader(stats)
  890. main_header = stats_reader.next()
  891. sub_header = stats_reader.next()
  892. time_row = sub_header.index("epoch")
  893. int_counter = 0
  894. for row in stats_reader:
  895. time = float(row[time_row])
  896. int_counter+=1
  897. if time < start_time:
  898. continue
  899. elif time > end_time:
  900. return stats_dict
  901. if int_counter % interval != 0:
  902. continue
  903. row_dict = dict()
  904. for nextheader in main_header:
  905. if nextheader != "":
  906. row_dict[nextheader] = dict()
  907. header = ""
  908. for item_num, column in enumerate(row):
  909. if(len(main_header[item_num]) != 0):
  910. header = main_header[item_num]
  911. row_dict[header][sub_header[item_num]] = float(column) # all the stats are numbers, so we want to make sure that they stay that way in json
  912. stats_dict[time] = row_dict
  913. return stats_dict
  914. ##############################################################
  915. # End __parse_stats
  916. ##############################################################
  917. def __getattr__(self, name):
  918. """For backwards compatibility, we used to pass benchmarker
  919. as the argument to the setup.py files"""
  920. try:
  921. x = getattr(self.benchmarker, name)
  922. except AttributeError:
  923. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  924. print "This is probably a bug"
  925. raise
  926. return x
  927. ##############################################################
  928. # Begin __calculate_average_stats
  929. # We have a large amount of raw data for the statistics that
  930. # may be useful for the stats nerds, but most people care about
  931. # a couple of numbers. For now, we're only going to supply:
  932. # * Average CPU
  933. # * Average Memory
  934. # * Total network use
  935. # * Total disk use
  936. # More may be added in the future. If they are, please update
  937. # the above list.
  938. # Note: raw_stats is directly from the __parse_stats method.
  939. # Recall that this consists of a dictionary of timestamps,
  940. # each of which contain a dictionary of stat categories which
  941. # contain a dictionary of stats
  942. ##############################################################
  943. def __calculate_average_stats(self, raw_stats):
  944. raw_stat_collection = dict()
  945. for timestamp, time_dict in raw_stats.items():
  946. for main_header, sub_headers in time_dict.items():
  947. item_to_append = None
  948. if 'cpu' in main_header:
  949. # We want to take the idl stat and subtract it from 100
  950. # to get the time that the CPU is NOT idle.
  951. item_to_append = sub_headers['idl'] - 100.0
  952. elif main_header == 'memory usage':
  953. item_to_append = sub_headers['used']
  954. elif 'net' in main_header:
  955. # Network stats have two parts - recieve and send. We'll use a tuple of
  956. # style (recieve, send)
  957. item_to_append = (sub_headers['recv'], sub_headers['send'])
  958. elif 'dsk' or 'io' in main_header:
  959. # Similar for network, except our tuple looks like (read, write)
  960. item_to_append = (sub_headers['read'], sub_headers['writ'])
  961. if item_to_append is not None:
  962. if main_header not in raw_stat_collection:
  963. raw_stat_collection[main_header] = list()
  964. raw_stat_collection[main_header].append(item_to_append)
  965. # Simple function to determine human readable size
  966. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  967. def sizeof_fmt(num):
  968. # We'll assume that any number we get is convertable to a float, just in case
  969. num = float(num)
  970. for x in ['bytes','KB','MB','GB']:
  971. if num < 1024.0 and num > -1024.0:
  972. return "%3.1f%s" % (num, x)
  973. num /= 1024.0
  974. return "%3.1f%s" % (num, 'TB')
  975. # Now we have our raw stats in a readable format - we need to format it for display
  976. # We need a floating point sum, so the built in sum doesn't cut it
  977. display_stat_collection = dict()
  978. for header, values in raw_stat_collection.items():
  979. display_stat = None
  980. if 'cpu' in header:
  981. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  982. elif main_header == 'memory usage':
  983. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  984. elif 'net' in main_header:
  985. receive, send = zip(*values) # unzip
  986. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  987. else: # if 'dsk' or 'io' in header:
  988. read, write = zip(*values) # unzip
  989. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  990. display_stat_collection[header] = display_stat
  991. return display_stat
  992. ###########################################################################################
  993. # End __calculate_average_stats
  994. #########################################################################################
  995. ##########################################################################################
  996. # Constructor
  997. ##########################################################################################
  998. def __init__(self, name, directory, benchmarker, runTests, args):
  999. self.name = name
  1000. self.directory = directory
  1001. self.benchmarker = benchmarker
  1002. self.runTests = runTests
  1003. self.fwroot = benchmarker.fwroot
  1004. # setup logging
  1005. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  1006. self.install_root="%s/%s" % (self.fwroot, "installs")
  1007. if benchmarker.install_strategy is 'pertest':
  1008. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1009. # Used in setup.py scripts for consistency with
  1010. # the bash environment variables
  1011. self.troot = self.directory
  1012. self.iroot = self.install_root
  1013. self.__dict__.update(args)
  1014. # ensure directory has __init__.py file so that we can use it as a Python package
  1015. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1016. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  1017. open(os.path.join(directory, "__init__.py"), 'w').close()
  1018. # Import the module (TODO - consider using sys.meta_path)
  1019. # Note: You can see the log output if you really want to, but it's a *ton*
  1020. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  1021. if dir_rel_to_fwroot != ".":
  1022. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1023. logging.log(0, "Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  1024. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1025. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1026. else:
  1027. logging.log(0, "Importing %s.%s", directory, self.setup_file)
  1028. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1029. ############################################################
  1030. # End __init__
  1031. ############################################################
  1032. ############################################################
  1033. # End FrameworkTest
  1034. ############################################################
  1035. ##########################################################################################
  1036. # Static methods
  1037. ##########################################################################################
  1038. ##############################################################
  1039. # parse_config(config, directory, benchmarker)
  1040. # parses a config file and returns a list of FrameworkTest
  1041. # objects based on that config file.
  1042. ##############################################################
  1043. def parse_config(config, directory, benchmarker):
  1044. tests = []
  1045. # The config object can specify multiple tests
  1046. # Loop over them and parse each into a FrameworkTest
  1047. for test in config['tests']:
  1048. for test_name, test_keys in test.iteritems():
  1049. # Prefix all test names with framework except 'default' test
  1050. if test_name == 'default':
  1051. test_name = config['framework']
  1052. else:
  1053. test_name = "%s-%s" % (config['framework'], test_name)
  1054. # Ensure FrameworkTest.framework is available
  1055. if not test_keys['framework']:
  1056. test_keys['framework'] = config['framework']
  1057. #if test_keys['framework'].lower() != config['framework'].lower():
  1058. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  1059. # (test_name, test_keys['framework'], config['framework']))
  1060. # Confirm required keys are present
  1061. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  1062. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  1063. if not all (key in test_keys for key in required):
  1064. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  1065. # Map test type to a parsed FrameworkTestType object
  1066. runTests = dict()
  1067. for type_name, type_obj in benchmarker.types.iteritems():
  1068. try:
  1069. runTests[type_name] = type_obj.copy().parse(test_keys)
  1070. except AttributeError as ae:
  1071. # This is quite common - most tests don't support all types
  1072. # Quitely log it and move on
  1073. logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  1074. pass
  1075. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  1076. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, test_keys))
  1077. return tests
  1078. ##############################################################
  1079. # End parse_config
  1080. ##############################################################