framework_test.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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. test.setup_out_err(out, err)
  271. out.write(header("VERIFYING %s" % test_type.upper()))
  272. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  273. try:
  274. results = test.verify(base_url)
  275. except Exception as e:
  276. results = [('fail',"""Caused Exception in TFB
  277. This almost certainly means your return value is incorrect,
  278. but also that you have found a bug. Please submit an issue
  279. including this message: %s\n%s""" % (e, traceback.format_exc()),
  280. base_url)]
  281. logging.warning("Verifying test %s for %s caused an exception: %s", test_type, self.name, e)
  282. traceback.format_exc()
  283. test.failed = any(result is 'fail' for (result, reason, url) in results)
  284. test.warned = any(result is 'warn' for (result, reason, url) in results)
  285. test.passed = all(result is 'pass' for (result, reason, url) in results)
  286. def output_result(result, reason, url):
  287. out.write(" %s for %s\n" % (result.upper(), url))
  288. print " %s for %s" % (result.upper(), url)
  289. if reason is not None and len(reason) != 0:
  290. for line in reason.splitlines():
  291. out.write(" " + line + '\n')
  292. print " " + line
  293. [output_result(r1,r2,url) for (r1, r2, url) in results]
  294. if test.failed:
  295. self.benchmarker.report_verify_results(self, test_type, 'fail')
  296. elif test.warned:
  297. self.benchmarker.report_verify_results(self, test_type, 'warn')
  298. elif test.passed:
  299. self.benchmarker.report_verify_results(self, test_type, 'pass')
  300. else:
  301. raise Exception("What the hell")
  302. # JSON
  303. if self.runTests[self.JSON]:
  304. out.write(header("VERIFYING JSON (%s)" % self.json_url))
  305. out.flush()
  306. url = self.benchmarker.generate_url(self.json_url, self.port)
  307. output = self.__curl_url(url, self.JSON, out, err)
  308. out.write("VALIDATING JSON ... ")
  309. ret_tuple = self.validateJson(output, out, err)
  310. if ret_tuple[0]:
  311. self.json_url_passed = True
  312. out.write("PASS\n\n")
  313. self.benchmarker.report_verify_results(self, self.JSON, 'pass')
  314. else:
  315. self.json_url_passed = False
  316. out.write("\nFAIL" + ret_tuple[1] + "\n\n")
  317. self.benchmarker.report_verify_results(self, self.JSON, 'fail')
  318. result = False
  319. out.flush()
  320. # DB
  321. if self.runTests[self.DB]:
  322. out.write(header("VERIFYING DB (%s)" % self.db_url))
  323. out.flush()
  324. url = self.benchmarker.generate_url(self.db_url, self.port)
  325. output = self.__curl_url(url, self.DB, out, err)
  326. validate_ret_tuple = self.validateDb(output, out, err)
  327. validate_strict_ret_tuple = self.validateDbStrict(output, out, err)
  328. if validate_ret_tuple[0]:
  329. self.db_url_passed = True
  330. else:
  331. self.db_url_passed = False
  332. if validate_strict_ret_tuple:
  333. self.db_url_warn = False
  334. else:
  335. self.db_url_warn = True
  336. out.write("VALIDATING DB ... ")
  337. if self.db_url_passed:
  338. out.write("PASS")
  339. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  340. if self.db_url_warn:
  341. out.write(" (with warnings) " + validate_strict_ret_tuple[1])
  342. self.benchmarker.report_verify_results(self, self.DB, 'warn')
  343. out.write("\n\n")
  344. else:
  345. self.benchmarker.report_verify_results(self, self.DB, 'fail')
  346. out.write("\nFAIL" + validate_ret_tuple[1])
  347. result = False
  348. out.flush()
  349. # Query
  350. if self.runTests[self.QUERY]:
  351. out.write(header("VERIFYING QUERY (%s)" % self.query_url+"2"))
  352. out.flush()
  353. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  354. output = self.__curl_url(url, self.QUERY, out, err)
  355. ret_tuple = self.validateQuery(output, out, err)
  356. if ret_tuple[0]:
  357. self.query_url_passed = True
  358. out.write(self.query_url + "2 - PASS\n\n")
  359. else:
  360. self.query_url_passed = False
  361. out.write(self.query_url + "2 - FAIL " + ret_tuple[1] + "\n\n")
  362. out.write("-----------------------------------------------------\n\n")
  363. out.flush()
  364. self.query_url_warn = False
  365. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  366. output2 = self.__curl_url(url2, self.QUERY, out, err)
  367. ret_tuple = self.validateQueryOneOrLess(output2, out, err)
  368. if not ret_tuple[0]:
  369. self.query_url_warn = True
  370. out.write(self.query_url + "0 - WARNING " + ret_tuple[1] + "\n\n")
  371. else:
  372. out.write(self.query_url + "0 - PASS\n\n")
  373. out.write("-----------------------------------------------------\n\n")
  374. out.flush()
  375. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  376. output3 = self.__curl_url(url3, self.QUERY, out, err)
  377. ret_tuple = self.validateQueryOneOrLess(output3, out, err)
  378. if not ret_tuple[0]:
  379. self.query_url_warn = True
  380. out.write(self.query_url + "foo - WARNING " + ret_tuple[1] + "\n\n")
  381. else:
  382. out.write(self.query_url + "foo - PASS\n\n")
  383. out.write("-----------------------------------------------------\n\n")
  384. out.flush()
  385. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  386. output4 = self.__curl_url(url4, self.QUERY, out, err)
  387. ret_tuple = self.validateQueryFiveHundredOrMore(output4, out, err)
  388. if not ret_tuple[0]:
  389. self.query_url_warn = True
  390. out.write(self.query_url + "501 - WARNING " + ret_tuple[1] + "\n\n")
  391. else:
  392. out.write(self.query_url + "501 - PASS\n\n")
  393. out.write("-----------------------------------------------------\n\n\n")
  394. out.flush()
  395. out.write("VALIDATING QUERY ... ")
  396. if self.query_url_passed:
  397. out.write("PASS")
  398. self.benchmarker.report_verify_results(self, self.QUERY, 'pass')
  399. if self.query_url_warn:
  400. out.write(" (with warnings)")
  401. self.benchmarker.report_verify_results(self, self.QUERY, 'warn')
  402. out.write("\n\n")
  403. else:
  404. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  405. self.benchmarker.report_verify_results(self, self.QUERY, 'fail')
  406. result = False
  407. out.flush()
  408. # Fortune
  409. if self.runTests[self.FORTUNE]:
  410. out.write(header("VERIFYING FORTUNE (%s)" % self.fortune_url))
  411. out.flush()
  412. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  413. output = self.__curl_url(url, self.FORTUNE, out, err)
  414. out.write("VALIDATING FORTUNE ... ")
  415. ret_tuple = self.validateFortune(output, out, err)
  416. if ret_tuple[0]:
  417. self.fortune_url_passed = True
  418. out.write("PASS\n\n")
  419. self.benchmarker.report_verify_results(self, self.FORTUNE, 'pass')
  420. else:
  421. self.fortune_url_passed = False
  422. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  423. self.benchmarker.report_verify_results(self, self.FORTUNE, 'fail')
  424. result = False
  425. out.flush()
  426. # Update
  427. if self.runTests[self.UPDATE]:
  428. out.write(header("VERIFYING UPDATE (%s)" % self.update_url))
  429. out.flush()
  430. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  431. output = self.__curl_url(url, self.UPDATE, out, err)
  432. out.write("VALIDATING UPDATE ... ")
  433. ret_tuple = self.validateUpdate(output, out, err)
  434. if ret_tuple[0]:
  435. self.update_url_passed = True
  436. out.write("PASS\n\n")
  437. self.benchmarker.report_verify_results(self, self.UPDATE, 'pass')
  438. else:
  439. self.update_url_passed = False
  440. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  441. self.benchmarker.report_verify_results(self, self.UPDATE, 'fail')
  442. result = False
  443. out.flush()
  444. # plaintext
  445. if self.runTests[self.PLAINTEXT]:
  446. out.write(header("VERIFYING PLAINTEXT (%s)" % self.plaintext_url))
  447. out.flush()
  448. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  449. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  450. out.write("VALIDATING PLAINTEXT ... ")
  451. ret_tuple = self.validatePlaintext(output, out, err)
  452. if ret_tuple[0]:
  453. self.plaintext_url_passed = True
  454. out.write("PASS\n\n")
  455. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'pass')
  456. else:
  457. self.plaintext_url_passed = False
  458. out.write("\nFAIL\n\n" + ret_tuple[1] + "\n\n")
  459. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'fail')
  460. result = False
  461. out.flush()
  462. return result
  463. ############################################################
  464. # End verify_urls
  465. ############################################################
  466. ############################################################
  467. # benchmark
  468. # Runs the benchmark for each type of test that it implements
  469. # JSON/DB/Query.
  470. ############################################################
  471. def benchmark(self, out, err):
  472. def benchmark_type(test_type):
  473. out.write("BENCHMARKING %s ... " % test_type.upper())
  474. test = self.runTests[test_type]
  475. test.setup_out_err(out, err)
  476. output_file = self.benchmarker.output_file(self.name, test_type)
  477. if not os.path.exists(output_file):
  478. # Open to create the empty file
  479. with open(output_file, 'w'):
  480. pass
  481. if test.passed:
  482. if test.requires_db:
  483. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  484. else:
  485. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  486. self.__begin_logging(test_type)
  487. self.__run_benchmark(remote_script, output_file, err)
  488. self.__end_logging()
  489. results = self.__parse_test(test_type)
  490. print "Benchmark results:"
  491. pprint(results)
  492. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  493. out.write( "Complete\n" )
  494. out.flush()
  495. # JSON
  496. if self.runTests[self.JSON]:
  497. try:
  498. out.write("BENCHMARKING JSON ... ")
  499. out.flush()
  500. results = None
  501. output_file = self.benchmarker.output_file(self.name, self.JSON)
  502. if not os.path.exists(output_file):
  503. with open(output_file, 'w'):
  504. # Simply opening the file in write mode should create the empty file.
  505. pass
  506. if self.json_url_passed:
  507. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  508. self.__begin_logging(self.JSON)
  509. self.__run_benchmark(remote_script, output_file, err)
  510. self.__end_logging()
  511. results = self.__parse_test(self.JSON)
  512. print results
  513. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  514. out.write( "Complete\n" )
  515. out.flush()
  516. except AttributeError:
  517. pass
  518. # DB
  519. if self.runTests[self.DB]:
  520. try:
  521. out.write("BENCHMARKING DB ... ")
  522. out.flush()
  523. results = None
  524. output_file = self.benchmarker.output_file(self.name, self.DB)
  525. if not os.path.exists(output_file):
  526. with open(output_file, 'w'):
  527. # Simply opening the file in write mode should create the empty file.
  528. pass
  529. if self.db_url_passed:
  530. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  531. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  532. self.__begin_logging(self.DB)
  533. self.__run_benchmark(remote_script, output_file, err)
  534. self.__end_logging()
  535. results = self.__parse_test(self.DB)
  536. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  537. out.write( "Complete\n" )
  538. except AttributeError:
  539. pass
  540. # Query
  541. if self.runTests[self.QUERY]:
  542. try:
  543. out.write("BENCHMARKING Query ... ")
  544. out.flush()
  545. results = None
  546. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  547. if not os.path.exists(output_file):
  548. with open(output_file, 'w'):
  549. # Simply opening the file in write mode should create the empty file.
  550. pass
  551. if self.query_url_passed:
  552. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  553. self.__begin_logging(self.QUERY)
  554. self.__run_benchmark(remote_script, output_file, err)
  555. self.__end_logging()
  556. results = self.__parse_test(self.QUERY)
  557. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  558. out.write( "Complete\n" )
  559. out.flush()
  560. except AttributeError:
  561. pass
  562. # fortune
  563. if self.runTests[self.FORTUNE]:
  564. try:
  565. out.write("BENCHMARKING Fortune ... ")
  566. out.flush()
  567. results = None
  568. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  569. if not os.path.exists(output_file):
  570. with open(output_file, 'w'):
  571. # Simply opening the file in write mode should create the empty file.
  572. pass
  573. if self.fortune_url_passed:
  574. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  575. self.__begin_logging(self.FORTUNE)
  576. self.__run_benchmark(remote_script, output_file, err)
  577. self.__end_logging()
  578. results = self.__parse_test(self.FORTUNE)
  579. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  580. out.write( "Complete\n" )
  581. out.flush()
  582. except AttributeError:
  583. pass
  584. # update
  585. if self.runTests[self.UPDATE]:
  586. try:
  587. out.write("BENCHMARKING Update ... ")
  588. out.flush()
  589. results = None
  590. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  591. if not os.path.exists(output_file):
  592. with open(output_file, 'w'):
  593. # Simply opening the file in write mode should create the empty file.
  594. pass
  595. if self.update_url_passed:
  596. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  597. self.__begin_logging(self.UPDATE)
  598. self.__run_benchmark(remote_script, output_file, err)
  599. self.__end_logging()
  600. results = self.__parse_test(self.UPDATE)
  601. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  602. out.write( "Complete\n" )
  603. out.flush()
  604. except AttributeError:
  605. pass
  606. # plaintext
  607. if self.runTests[self.PLAINTEXT]:
  608. try:
  609. out.write("BENCHMARKING Plaintext ... ")
  610. out.flush()
  611. results = None
  612. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  613. if not os.path.exists(output_file):
  614. with open(output_file, 'w'):
  615. # Simply opening the file in write mode should create the empty file.
  616. pass
  617. if self.plaintext_url_passed:
  618. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  619. self.__begin_logging(self.PLAINTEXT)
  620. self.__run_benchmark(remote_script, output_file, err)
  621. self.__end_logging()
  622. results = self.__parse_test(self.PLAINTEXT)
  623. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  624. out.write( "Complete\n" )
  625. out.flush()
  626. except AttributeError:
  627. traceback.print_exc()
  628. pass
  629. ############################################################
  630. # End benchmark
  631. ############################################################
  632. ############################################################
  633. # parse_all
  634. # Method meant to be run for a given timestamp
  635. ############################################################
  636. def parse_all(self):
  637. # JSON
  638. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  639. results = self.__parse_test(self.JSON)
  640. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  641. # DB
  642. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  643. results = self.__parse_test(self.DB)
  644. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  645. # Query
  646. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  647. results = self.__parse_test(self.QUERY)
  648. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  649. # Fortune
  650. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  651. results = self.__parse_test(self.FORTUNE)
  652. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  653. # Update
  654. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  655. results = self.__parse_test(self.UPDATE)
  656. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  657. # Plaintext
  658. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  659. results = self.__parse_test(self.PLAINTEXT)
  660. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  661. ############################################################
  662. # End parse_all
  663. ############################################################
  664. ############################################################
  665. # __parse_test(test_type)
  666. ############################################################
  667. def __parse_test(self, test_type):
  668. try:
  669. results = dict()
  670. results['results'] = []
  671. stats = []
  672. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  673. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  674. is_warmup = True
  675. rawData = None
  676. for line in raw_data:
  677. if "Queries:" in line or "Concurrency:" in line:
  678. is_warmup = False
  679. rawData = None
  680. continue
  681. if "Warmup" in line or "Primer" in line:
  682. is_warmup = True
  683. continue
  684. if not is_warmup:
  685. if rawData == None:
  686. rawData = dict()
  687. results['results'].append(rawData)
  688. #if "Requests/sec:" in line:
  689. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  690. # rawData['reportedResults'] = m.group(1)
  691. # search for weighttp data such as succeeded and failed.
  692. if "Latency" in line:
  693. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  694. if len(m) == 4:
  695. rawData['latencyAvg'] = m[0]
  696. rawData['latencyStdev'] = m[1]
  697. rawData['latencyMax'] = m[2]
  698. # rawData['latencyStdevPercent'] = m[3]
  699. #if "Req/Sec" in line:
  700. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  701. # if len(m) == 4:
  702. # rawData['requestsAvg'] = m[0]
  703. # rawData['requestsStdev'] = m[1]
  704. # rawData['requestsMax'] = m[2]
  705. # rawData['requestsStdevPercent'] = m[3]
  706. #if "requests in" in line:
  707. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  708. # if m != None:
  709. # # parse out the raw time, which may be in minutes or seconds
  710. # raw_time = m.group(1)
  711. # if "ms" in raw_time:
  712. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  713. # elif "s" in raw_time:
  714. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  715. # elif "m" in raw_time:
  716. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  717. # elif "h" in raw_time:
  718. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  719. if "requests in" in line:
  720. m = re.search("([0-9]+) requests in", line)
  721. if m != None:
  722. rawData['totalRequests'] = int(m.group(1))
  723. if "Socket errors" in line:
  724. if "connect" in line:
  725. m = re.search("connect ([0-9]+)", line)
  726. rawData['connect'] = int(m.group(1))
  727. if "read" in line:
  728. m = re.search("read ([0-9]+)", line)
  729. rawData['read'] = int(m.group(1))
  730. if "write" in line:
  731. m = re.search("write ([0-9]+)", line)
  732. rawData['write'] = int(m.group(1))
  733. if "timeout" in line:
  734. m = re.search("timeout ([0-9]+)", line)
  735. rawData['timeout'] = int(m.group(1))
  736. if "Non-2xx" in line:
  737. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  738. if m != None:
  739. rawData['5xx'] = int(m.group(1))
  740. if "STARTTIME" in line:
  741. m = re.search("[0-9]+", line)
  742. rawData["startTime"] = int(m.group(0))
  743. if "ENDTIME" in line:
  744. m = re.search("[0-9]+", line)
  745. rawData["endTime"] = int(m.group(0))
  746. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  747. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  748. stats.append(test_stats)
  749. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  750. json.dump(stats, stats_file)
  751. return results
  752. except IOError:
  753. return None
  754. ############################################################
  755. # End benchmark
  756. ############################################################
  757. ##########################################################################################
  758. # Private Methods
  759. ##########################################################################################
  760. ############################################################
  761. # __run_benchmark(script, output_file)
  762. # Runs a single benchmark using the script which is a bash
  763. # template that uses weighttp to run the test. All the results
  764. # outputed to the output_file.
  765. ############################################################
  766. def __run_benchmark(self, script, output_file, err):
  767. with open(output_file, 'w') as raw_file:
  768. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  769. p.communicate(script)
  770. err.flush()
  771. ############################################################
  772. # End __run_benchmark
  773. ############################################################
  774. ############################################################
  775. # __generate_concurrency_script(url, port)
  776. # Generates the string containing the bash script that will
  777. # be run on the client to benchmark a single test. This
  778. # specifically works for the variable concurrency tests (JSON
  779. # and DB)
  780. ############################################################
  781. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  782. if len(intervals) == 0:
  783. intervals = self.benchmarker.concurrency_levels
  784. headers = self.__get_request_headers(accept_header)
  785. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  786. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  787. interval=" ".join("{}".format(item) for item in intervals),
  788. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  789. pipeline=pipeline)
  790. ############################################################
  791. # End __generate_concurrency_script
  792. ############################################################
  793. ############################################################
  794. # __generate_query_script(url, port)
  795. # Generates the string containing the bash script that will
  796. # be run on the client to benchmark a single test. This
  797. # specifically works for the variable query tests (Query)
  798. ############################################################
  799. def __generate_query_script(self, url, port, accept_header):
  800. headers = self.__get_request_headers(accept_header)
  801. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  802. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  803. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  804. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  805. ############################################################
  806. # End __generate_query_script
  807. ############################################################
  808. ############################################################
  809. # __get_request_headers(accept_header)
  810. # Generates the complete HTTP header string
  811. ############################################################
  812. def __get_request_headers(self, accept_header):
  813. return self.headers_template.format(accept=accept_header)
  814. ############################################################
  815. # End __format_request_headers
  816. ############################################################
  817. ############################################################
  818. # __curl_url
  819. # Dump HTTP response and headers. Throw exception if there
  820. # is an HTTP error.
  821. ############################################################
  822. def __curl_url(self, url, testType, out, err):
  823. output = None
  824. try:
  825. # Use -m 15 to make curl stop trying after 15sec.
  826. # Use -i to output response with headers.
  827. # Don't use -f so that the HTTP response code is ignored.
  828. # Use --stderr - to redirect stderr to stdout so we get
  829. # error output for sure in stdout.
  830. # Use -sS to hide progress bar, but show errors.
  831. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  832. # HTTP output may not end in a newline, so add that here.
  833. out.write( "\n\n" )
  834. out.flush()
  835. err.flush()
  836. # We need to get the respond body from the curl and return it.
  837. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  838. output = p.communicate()
  839. except:
  840. pass
  841. if output:
  842. # We have the response body - return it
  843. return output[0]
  844. ##############################################################
  845. # End __curl_url
  846. ##############################################################
  847. def requires_database(self):
  848. '''Returns True/False if this test requires a database'''
  849. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  850. ############################################################
  851. # __begin_logging
  852. # Starts a thread to monitor the resource usage, to be synced with the client's time
  853. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  854. ############################################################
  855. def __begin_logging(self, test_type):
  856. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_type))
  857. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  858. --raw --socket --tcp --udp --unix --vm --disk-util \
  859. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  860. cmd = shlex.split(dstat_string)
  861. dev_null = open(os.devnull, "w")
  862. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  863. ##############################################################
  864. # End __begin_logging
  865. ##############################################################
  866. ##############################################################
  867. # Begin __end_logging
  868. # Stops the logger thread and blocks until shutdown is complete.
  869. ##############################################################
  870. def __end_logging(self):
  871. self.subprocess_handle.terminate()
  872. self.subprocess_handle.communicate()
  873. ##############################################################
  874. # End __end_logging
  875. ##############################################################
  876. ##############################################################
  877. # Begin __parse_stats
  878. # For each test type, process all the statistics, and return a multi-layered dictionary
  879. # that has a structure as follows:
  880. # (timestamp)
  881. # | (main header) - group that the stat is in
  882. # | | (sub header) - title of the stat
  883. # | | | (stat) - the stat itself, usually a floating point number
  884. ##############################################################
  885. def __parse_stats(self, test_type, start_time, end_time, interval):
  886. stats_dict = dict()
  887. stats_file = self.benchmarker.stats_file(self.name, test_type)
  888. with open(stats_file) as stats:
  889. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  890. pass
  891. stats_reader = csv.reader(stats)
  892. main_header = stats_reader.next()
  893. sub_header = stats_reader.next()
  894. time_row = sub_header.index("epoch")
  895. int_counter = 0
  896. for row in stats_reader:
  897. time = float(row[time_row])
  898. int_counter+=1
  899. if time < start_time:
  900. continue
  901. elif time > end_time:
  902. return stats_dict
  903. if int_counter % interval != 0:
  904. continue
  905. row_dict = dict()
  906. for nextheader in main_header:
  907. if nextheader != "":
  908. row_dict[nextheader] = dict()
  909. header = ""
  910. for item_num, column in enumerate(row):
  911. if(len(main_header[item_num]) != 0):
  912. header = main_header[item_num]
  913. 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
  914. stats_dict[time] = row_dict
  915. return stats_dict
  916. ##############################################################
  917. # End __parse_stats
  918. ##############################################################
  919. def __getattr__(self, name):
  920. """For backwards compatibility, we used to pass benchmarker
  921. as the argument to the setup.py files"""
  922. try:
  923. x = getattr(self.benchmarker, name)
  924. except AttributeError:
  925. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  926. print "This is probably a bug"
  927. raise
  928. return x
  929. ##############################################################
  930. # Begin __calculate_average_stats
  931. # We have a large amount of raw data for the statistics that
  932. # may be useful for the stats nerds, but most people care about
  933. # a couple of numbers. For now, we're only going to supply:
  934. # * Average CPU
  935. # * Average Memory
  936. # * Total network use
  937. # * Total disk use
  938. # More may be added in the future. If they are, please update
  939. # the above list.
  940. # Note: raw_stats is directly from the __parse_stats method.
  941. # Recall that this consists of a dictionary of timestamps,
  942. # each of which contain a dictionary of stat categories which
  943. # contain a dictionary of stats
  944. ##############################################################
  945. def __calculate_average_stats(self, raw_stats):
  946. raw_stat_collection = dict()
  947. for timestamp, time_dict in raw_stats.items():
  948. for main_header, sub_headers in time_dict.items():
  949. item_to_append = None
  950. if 'cpu' in main_header:
  951. # We want to take the idl stat and subtract it from 100
  952. # to get the time that the CPU is NOT idle.
  953. item_to_append = sub_headers['idl'] - 100.0
  954. elif main_header == 'memory usage':
  955. item_to_append = sub_headers['used']
  956. elif 'net' in main_header:
  957. # Network stats have two parts - recieve and send. We'll use a tuple of
  958. # style (recieve, send)
  959. item_to_append = (sub_headers['recv'], sub_headers['send'])
  960. elif 'dsk' or 'io' in main_header:
  961. # Similar for network, except our tuple looks like (read, write)
  962. item_to_append = (sub_headers['read'], sub_headers['writ'])
  963. if item_to_append is not None:
  964. if main_header not in raw_stat_collection:
  965. raw_stat_collection[main_header] = list()
  966. raw_stat_collection[main_header].append(item_to_append)
  967. # Simple function to determine human readable size
  968. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  969. def sizeof_fmt(num):
  970. # We'll assume that any number we get is convertable to a float, just in case
  971. num = float(num)
  972. for x in ['bytes','KB','MB','GB']:
  973. if num < 1024.0 and num > -1024.0:
  974. return "%3.1f%s" % (num, x)
  975. num /= 1024.0
  976. return "%3.1f%s" % (num, 'TB')
  977. # Now we have our raw stats in a readable format - we need to format it for display
  978. # We need a floating point sum, so the built in sum doesn't cut it
  979. display_stat_collection = dict()
  980. for header, values in raw_stat_collection.items():
  981. display_stat = None
  982. if 'cpu' in header:
  983. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  984. elif main_header == 'memory usage':
  985. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  986. elif 'net' in main_header:
  987. receive, send = zip(*values) # unzip
  988. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  989. else: # if 'dsk' or 'io' in header:
  990. read, write = zip(*values) # unzip
  991. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  992. display_stat_collection[header] = display_stat
  993. return display_stat
  994. ###########################################################################################
  995. # End __calculate_average_stats
  996. #########################################################################################
  997. ##########################################################################################
  998. # Constructor
  999. ##########################################################################################
  1000. def __init__(self, name, directory, benchmarker, runTests, args):
  1001. self.name = name
  1002. self.directory = directory
  1003. self.benchmarker = benchmarker
  1004. self.runTests = runTests
  1005. self.fwroot = benchmarker.fwroot
  1006. # setup logging
  1007. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  1008. self.install_root="%s/%s" % (self.fwroot, "installs")
  1009. if benchmarker.install_strategy is 'pertest':
  1010. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1011. # Used in setup.py scripts for consistency with
  1012. # the bash environment variables
  1013. self.troot = self.directory
  1014. self.iroot = self.install_root
  1015. self.__dict__.update(args)
  1016. # ensure directory has __init__.py file so that we can use it as a Python package
  1017. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1018. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  1019. open(os.path.join(directory, "__init__.py"), 'w').close()
  1020. # Import the module (TODO - consider using sys.meta_path)
  1021. # Note: You can see the log output if you really want to, but it's a *ton*
  1022. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  1023. if dir_rel_to_fwroot != ".":
  1024. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1025. logging.log(0, "Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  1026. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1027. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1028. else:
  1029. logging.log(0, "Importing %s.%s", directory, self.setup_file)
  1030. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1031. ############################################################
  1032. # End __init__
  1033. ############################################################
  1034. ############################################################
  1035. # End FrameworkTest
  1036. ############################################################
  1037. ##########################################################################################
  1038. # Static methods
  1039. ##########################################################################################
  1040. ##############################################################
  1041. # parse_config(config, directory, benchmarker)
  1042. # parses a config file and returns a list of FrameworkTest
  1043. # objects based on that config file.
  1044. ##############################################################
  1045. def parse_config(config, directory, benchmarker):
  1046. tests = []
  1047. # The config object can specify multiple tests
  1048. # Loop over them and parse each into a FrameworkTest
  1049. for test in config['tests']:
  1050. for test_name, test_keys in test.iteritems():
  1051. # Prefix all test names with framework except 'default' test
  1052. if test_name == 'default':
  1053. test_name = config['framework']
  1054. else:
  1055. test_name = "%s-%s" % (config['framework'], test_name)
  1056. # Ensure FrameworkTest.framework is available
  1057. if not test_keys['framework']:
  1058. test_keys['framework'] = config['framework']
  1059. #if test_keys['framework'].lower() != config['framework'].lower():
  1060. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  1061. # (test_name, test_keys['framework'], config['framework']))
  1062. # Confirm required keys are present
  1063. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  1064. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  1065. if not all (key in test_keys for key in required):
  1066. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  1067. # Map test type to a parsed FrameworkTestType object
  1068. runTests = dict()
  1069. for type_name, type_obj in benchmarker.types.iteritems():
  1070. try:
  1071. runTests[type_name] = type_obj.copy().parse(test_keys)
  1072. except AttributeError as ae:
  1073. # This is quite common - most tests don't support all types
  1074. # Quitely log it and move on
  1075. logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  1076. pass
  1077. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  1078. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, test_keys))
  1079. return tests
  1080. ##############################################################
  1081. # End parse_config
  1082. ##############################################################