framework_test.py 50 KB

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