framework_test.py 50 KB

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