framework_test.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. # Returns True if all verifications succeeded
  409. ############################################################
  410. def verify_urls(self, out, err):
  411. result = True
  412. # JSON
  413. if self.runTests[self.JSON]:
  414. out.write(textwrap.dedent("""
  415. -----------------------------------------------------
  416. VERIFYING JSON ({url})
  417. -----------------------------------------------------
  418. """.format(url = self.json_url)))
  419. out.flush()
  420. url = self.benchmarker.generate_url(self.json_url, self.port)
  421. output = self.__curl_url(url, self.JSON, out, err)
  422. out.write("VALIDATING JSON ... ")
  423. if self.validateJson(output, out, err):
  424. self.json_url_passed = True
  425. out.write("PASS\n\n")
  426. else:
  427. self.json_url_passed = False
  428. out.write("\nFAIL\n\n" + ret_tuple[1])
  429. result = False
  430. out.flush
  431. # DB
  432. if self.runTests[self.DB]:
  433. out.write(textwrap.dedent("""
  434. -----------------------------------------------------
  435. VERIFYING DB ({url})
  436. -----------------------------------------------------
  437. """.format(url = self.db_url)))
  438. out.flush()
  439. url = self.benchmarker.generate_url(self.db_url, self.port)
  440. output = self.__curl_url(url, self.DB, out, err)
  441. if self.validateDb(output, out, err):
  442. self.db_url_passed = True
  443. else:
  444. self.db_url_passed = False
  445. if self.validateDbStrict(output, out, err):
  446. self.db_url_warn = False
  447. else:
  448. self.db_url_warn = True
  449. out.write("VALIDATING DB ... ")
  450. if self.db_url_passed:
  451. out.write("PASS")
  452. if self.db_url_warn:
  453. out.write(" (with warnings)")
  454. out.write("\n\n")
  455. else:
  456. out.write("\nFAIL\n\n" + ret_tuple[1])
  457. result = False
  458. out.flush
  459. # Query
  460. if self.runTests[self.QUERY]:
  461. out.write(textwrap.dedent("""
  462. -----------------------------------------------------
  463. VERIFYING QUERY ({url})
  464. -----------------------------------------------------
  465. """.format(url=self.query_url+"2")))
  466. out.flush()
  467. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  468. output = self.__curl_url(url, self.QUERY, out, err)
  469. ret_tuple = self.validateQuery(output, out, err)
  470. if ret_tuple[0]:
  471. self.query_url_passed = True
  472. out.write(self.query_url + "2 - PASS\n\n")
  473. else:
  474. self.query_url_passed = False
  475. out.write(self.query_url + "2 - FAIL\n\n" + ret_tuple[1])
  476. out.write("-----------------------------------------------------\n\n")
  477. out.flush()
  478. self.query_url_warn = False
  479. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  480. output2 = self.__curl_url(url2, self.QUERY, out, err)
  481. ret_tuple = self.validateQueryOneOrLess(output2, out, err)
  482. if not ret_tuple[0]:
  483. self.query_url_warn = True
  484. out.write(self.query_url + "0 - WARNING\n\n" + ret_tuple[1])
  485. else:
  486. out.write(self.query_url + "0 - PASS\n\n")
  487. out.write("-----------------------------------------------------\n\n")
  488. out.flush()
  489. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  490. output3 = self.__curl_url(url3, self.QUERY, out, err)
  491. ret_tuple = self.validateQueryOneOrLess(output3, out, err)
  492. if not ret_tuple[0]:
  493. self.query_url_warn = True
  494. out.write(self.query_url + "foo - WARNING\n\n" + ret_tuple[1])
  495. else:
  496. out.write(self.query_url + "foo - PASS\n\n")
  497. out.write("-----------------------------------------------------\n\n")
  498. out.flush()
  499. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  500. output4 = self.__curl_url(url4, self.QUERY, out, err)
  501. ret_tuple = self.validateQueryFiveHundredOrMore(output4, out, err)
  502. if not ret_tuple[0]:
  503. self.query_url_warn = True
  504. out.write(self.query_url + "501 - WARNING\n\n" + ret_tuple[1])
  505. else:
  506. out.write(self.query_url + "501 - PASS\n\n")
  507. out.write("-----------------------------------------------------\n\n\n")
  508. out.flush()
  509. out.write("VALIDATING QUERY ... ")
  510. if self.query_url_passed:
  511. out.write("PASS")
  512. if self.query_url_warn:
  513. out.write(" (with warnings)")
  514. out.write("\n\n")
  515. else:
  516. out.write("\nFAIL\n\n" + ret_tuple[1])
  517. result = False
  518. out.flush
  519. # Fortune
  520. if self.runTests[self.FORTUNE]:
  521. out.write(textwrap.dedent("""
  522. -----------------------------------------------------
  523. VERIFYING FORTUNE ({url})
  524. -----------------------------------------------------
  525. """.format(url = self.fortune_url)))
  526. out.flush()
  527. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  528. output = self.__curl_url(url, self.FORTUNE, out, err)
  529. out.write("VALIDATING FORTUNE ... ")
  530. if self.validateFortune(output, out, err):
  531. self.fortune_url_passed = True
  532. out.write("PASS\n\n")
  533. else:
  534. self.fortune_url_passed = False
  535. out.write("\nFAIL\n\n")
  536. result = False
  537. out.flush
  538. # Update
  539. if self.runTests[self.UPDATE]:
  540. out.write(textwrap.dedent("""
  541. -----------------------------------------------------
  542. VERIFYING UPDATE ({url})
  543. -----------------------------------------------------
  544. """.format(url = self.update_url)))
  545. out.flush()
  546. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  547. output = self.__curl_url(url, self.UPDATE, out, err)
  548. out.write("VALIDATING UPDATE ... ")
  549. if self.validateUpdate(output, out, err):
  550. self.update_url_passed = True
  551. out.write("PASS\n\n")
  552. else:
  553. self.update_url_passed = False
  554. out.write("\nFAIL\n\n" + ret_tuple[1])
  555. result = False
  556. out.flush
  557. # plaintext
  558. if self.runTests[self.PLAINTEXT]:
  559. out.write(textwrap.dedent("""
  560. -----------------------------------------------------
  561. VERIFYING PLAINTEXT ({url})
  562. -----------------------------------------------------
  563. """.format(url = self.plaintext_url)))
  564. out.flush()
  565. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  566. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  567. out.write("VALIDATING PLAINTEXT ... ")
  568. ret_tuple = self.validatePlaintext(output, out, err)
  569. print ret_tuple
  570. if ret_tuple[0]:
  571. self.plaintext_url_passed = True
  572. out.write("PASS\n\n")
  573. else:
  574. self.plaintext_url_passed = False
  575. out.write(ret_tuple[1] + "\nFAIL\n\n")
  576. result = False
  577. out.flush
  578. return result
  579. ############################################################
  580. # End verify_urls
  581. ############################################################
  582. ############################################################
  583. # contains_type(type)
  584. # true if this test contains an implementation of the given
  585. # test type (json, db, etc.)
  586. ############################################################
  587. def contains_type(self, type):
  588. try:
  589. if type == self.JSON and self.json_url is not None:
  590. return True
  591. if type == self.DB and self.db_url is not None:
  592. return True
  593. if type == self.QUERY and self.query_url is not None:
  594. return True
  595. if type == self.FORTUNE and self.fortune_url is not None:
  596. return True
  597. if type == self.UPDATE and self.update_url is not None:
  598. return True
  599. if type == self.PLAINTEXT and self.plaintext_url is not None:
  600. return True
  601. except AttributeError:
  602. pass
  603. return False
  604. ############################################################
  605. # End stop
  606. ############################################################
  607. ############################################################
  608. # benchmark
  609. # Runs the benchmark for each type of test that it implements
  610. # JSON/DB/Query.
  611. ############################################################
  612. def benchmark(self, out, err):
  613. # JSON
  614. if self.runTests[self.JSON]:
  615. try:
  616. out.write("BENCHMARKING JSON ... ")
  617. out.flush()
  618. results = None
  619. output_file = self.benchmarker.output_file(self.name, self.JSON)
  620. if not os.path.exists(output_file):
  621. with open(output_file, 'w'):
  622. # Simply opening the file in write mode should create the empty file.
  623. pass
  624. if self.json_url_passed:
  625. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  626. self.__begin_logging(self.JSON)
  627. self.__run_benchmark(remote_script, output_file, err)
  628. self.__end_logging()
  629. results = self.__parse_test(self.JSON)
  630. print results
  631. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  632. out.write( "Complete\n" )
  633. out.flush()
  634. except AttributeError:
  635. pass
  636. # DB
  637. if self.runTests[self.DB]:
  638. try:
  639. out.write("BENCHMARKING DB ... ")
  640. out.flush()
  641. results = None
  642. output_file = self.benchmarker.output_file(self.name, self.DB)
  643. warning_file = self.benchmarker.warning_file(self.name, self.DB)
  644. if not os.path.exists(output_file):
  645. with open(output_file, 'w'):
  646. # Simply opening the file in write mode should create the empty file.
  647. pass
  648. if self.db_url_warn:
  649. with open(warning_file, 'w'):
  650. pass
  651. if self.db_url_passed:
  652. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  653. self.__begin_logging(self.DB)
  654. self.__run_benchmark(remote_script, output_file, err)
  655. self.__end_logging()
  656. results = self.__parse_test(self.DB)
  657. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  658. out.write( "Complete\n" )
  659. except AttributeError:
  660. pass
  661. # Query
  662. if self.runTests[self.QUERY]:
  663. try:
  664. out.write("BENCHMARKING Query ... ")
  665. out.flush()
  666. results = None
  667. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  668. warning_file = self.benchmarker.warning_file(self.name, self.QUERY)
  669. if not os.path.exists(output_file):
  670. with open(output_file, 'w'):
  671. # Simply opening the file in write mode should create the empty file.
  672. pass
  673. if self.query_url_warn:
  674. with open(warning_file, 'w'):
  675. pass
  676. if self.query_url_passed:
  677. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  678. self.__begin_logging(self.QUERY)
  679. self.__run_benchmark(remote_script, output_file, err)
  680. self.__end_logging()
  681. results = self.__parse_test(self.QUERY)
  682. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  683. out.write( "Complete\n" )
  684. out.flush()
  685. except AttributeError:
  686. pass
  687. # fortune
  688. if self.runTests[self.FORTUNE]:
  689. try:
  690. out.write("BENCHMARKING Fortune ... ")
  691. out.flush()
  692. results = None
  693. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  694. if not os.path.exists(output_file):
  695. with open(output_file, 'w'):
  696. # Simply opening the file in write mode should create the empty file.
  697. pass
  698. if self.fortune_url_passed:
  699. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  700. self.__begin_logging(self.FORTUNE)
  701. self.__run_benchmark(remote_script, output_file, err)
  702. self.__end_logging()
  703. results = self.__parse_test(self.FORTUNE)
  704. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  705. out.write( "Complete\n" )
  706. out.flush()
  707. except AttributeError:
  708. pass
  709. # update
  710. if self.runTests[self.UPDATE]:
  711. try:
  712. out.write("BENCHMARKING Update ... ")
  713. out.flush()
  714. results = None
  715. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  716. if not os.path.exists(output_file):
  717. with open(output_file, 'w'):
  718. # Simply opening the file in write mode should create the empty file.
  719. pass
  720. if self.update_url_passed:
  721. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  722. self.__begin_logging(self.UPDATE)
  723. self.__run_benchmark(remote_script, output_file, err)
  724. self.__end_logging()
  725. results = self.__parse_test(self.UPDATE)
  726. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  727. out.write( "Complete\n" )
  728. out.flush()
  729. except AttributeError:
  730. pass
  731. # plaintext
  732. if self.runTests[self.PLAINTEXT]:
  733. try:
  734. out.write("BENCHMARKING Plaintext ... ")
  735. out.flush()
  736. results = None
  737. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  738. if not os.path.exists(output_file):
  739. with open(output_file, 'w'):
  740. # Simply opening the file in write mode should create the empty file.
  741. pass
  742. if self.plaintext_url_passed:
  743. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  744. self.__begin_logging(self.PLAINTEXT)
  745. self.__run_benchmark(remote_script, output_file, err)
  746. self.__end_logging()
  747. results = self.__parse_test(self.PLAINTEXT)
  748. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  749. out.write( "Complete\n" )
  750. out.flush()
  751. except AttributeError:
  752. traceback.print_exc()
  753. pass
  754. ############################################################
  755. # End benchmark
  756. ############################################################
  757. ############################################################
  758. # parse_all
  759. # Method meant to be run for a given timestamp
  760. ############################################################
  761. def parse_all(self):
  762. # JSON
  763. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  764. results = self.__parse_test(self.JSON)
  765. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  766. # DB
  767. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  768. results = self.__parse_test(self.DB)
  769. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  770. # Query
  771. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  772. results = self.__parse_test(self.QUERY)
  773. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  774. # Fortune
  775. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  776. results = self.__parse_test(self.FORTUNE)
  777. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  778. # Update
  779. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  780. results = self.__parse_test(self.UPDATE)
  781. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  782. # Plaintext
  783. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  784. results = self.__parse_test(self.PLAINTEXT)
  785. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  786. ############################################################
  787. # End parse_all
  788. ############################################################
  789. ############################################################
  790. # __parse_test(test_type)
  791. ############################################################
  792. def __parse_test(self, test_type):
  793. try:
  794. results = dict()
  795. results['results'] = []
  796. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  797. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  798. is_warmup = True
  799. rawData = None
  800. for line in raw_data:
  801. if "Queries:" in line or "Concurrency:" in line:
  802. is_warmup = False
  803. rawData = None
  804. continue
  805. if "Warmup" in line or "Primer" in line:
  806. is_warmup = True
  807. continue
  808. if not is_warmup:
  809. if rawData == None:
  810. rawData = dict()
  811. results['results'].append(rawData)
  812. #if "Requests/sec:" in line:
  813. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  814. # rawData['reportedResults'] = m.group(1)
  815. # search for weighttp data such as succeeded and failed.
  816. if "Latency" in line:
  817. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  818. if len(m) == 4:
  819. rawData['latencyAvg'] = m[0]
  820. rawData['latencyStdev'] = m[1]
  821. rawData['latencyMax'] = m[2]
  822. # rawData['latencyStdevPercent'] = m[3]
  823. #if "Req/Sec" in line:
  824. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  825. # if len(m) == 4:
  826. # rawData['requestsAvg'] = m[0]
  827. # rawData['requestsStdev'] = m[1]
  828. # rawData['requestsMax'] = m[2]
  829. # rawData['requestsStdevPercent'] = m[3]
  830. #if "requests in" in line:
  831. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  832. # if m != None:
  833. # # parse out the raw time, which may be in minutes or seconds
  834. # raw_time = m.group(1)
  835. # if "ms" in raw_time:
  836. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  837. # elif "s" in raw_time:
  838. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  839. # elif "m" in raw_time:
  840. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  841. # elif "h" in raw_time:
  842. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  843. if "requests in" in line:
  844. m = re.search("([0-9]+) requests in", line)
  845. if m != None:
  846. rawData['totalRequests'] = int(m.group(1))
  847. if "Socket errors" in line:
  848. if "connect" in line:
  849. m = re.search("connect ([0-9]+)", line)
  850. rawData['connect'] = int(m.group(1))
  851. if "read" in line:
  852. m = re.search("read ([0-9]+)", line)
  853. rawData['read'] = int(m.group(1))
  854. if "write" in line:
  855. m = re.search("write ([0-9]+)", line)
  856. rawData['write'] = int(m.group(1))
  857. if "timeout" in line:
  858. m = re.search("timeout ([0-9]+)", line)
  859. rawData['timeout'] = int(m.group(1))
  860. if "Non-2xx" in line:
  861. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  862. if m != None:
  863. rawData['5xx'] = int(m.group(1))
  864. if "STARTTIME" in line:
  865. m = re.search("[0-9]+", line)
  866. rawData["startTime"] = int(m.group(0))
  867. if "ENDTIME" in line:
  868. m = re.search("[0-9]+", line)
  869. rawData["endTime"] = int(m.group(0))
  870. stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  871. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  872. json.dump(stats, stats_file)
  873. return results
  874. except IOError:
  875. return None
  876. ############################################################
  877. # End benchmark
  878. ############################################################
  879. ##########################################################################################
  880. # Private Methods
  881. ##########################################################################################
  882. ############################################################
  883. # __run_benchmark(script, output_file)
  884. # Runs a single benchmark using the script which is a bash
  885. # template that uses weighttp to run the test. All the results
  886. # outputed to the output_file.
  887. ############################################################
  888. def __run_benchmark(self, script, output_file, err):
  889. with open(output_file, 'w') as raw_file:
  890. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  891. p.communicate(script)
  892. err.flush()
  893. ############################################################
  894. # End __run_benchmark
  895. ############################################################
  896. ############################################################
  897. # __generate_concurrency_script(url, port)
  898. # Generates the string containing the bash script that will
  899. # be run on the client to benchmark a single test. This
  900. # specifically works for the variable concurrency tests (JSON
  901. # and DB)
  902. ############################################################
  903. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  904. if len(intervals) == 0:
  905. intervals = self.benchmarker.concurrency_levels
  906. headers = self.__get_request_headers(accept_header)
  907. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  908. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  909. interval=" ".join("{}".format(item) for item in intervals),
  910. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  911. pipeline=pipeline)
  912. ############################################################
  913. # End __generate_concurrency_script
  914. ############################################################
  915. ############################################################
  916. # __generate_query_script(url, port)
  917. # Generates the string containing the bash script that will
  918. # be run on the client to benchmark a single test. This
  919. # specifically works for the variable query tests (Query)
  920. ############################################################
  921. def __generate_query_script(self, url, port, accept_header):
  922. headers = self.__get_request_headers(accept_header)
  923. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  924. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  925. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  926. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  927. ############################################################
  928. # End __generate_query_script
  929. ############################################################
  930. ############################################################
  931. # __get_request_headers(accept_header)
  932. # Generates the complete HTTP header string
  933. ############################################################
  934. def __get_request_headers(self, accept_header):
  935. return self.headers_template.format(accept=accept_header)
  936. ############################################################
  937. # End __format_request_headers
  938. ############################################################
  939. ############################################################
  940. # __curl_url
  941. # Dump HTTP response and headers. Throw exception if there
  942. # is an HTTP error.
  943. ############################################################
  944. def __curl_url(self, url, testType, out, err):
  945. output = None
  946. try:
  947. # Use -m 15 to make curl stop trying after 15sec.
  948. # Use -i to output response with headers.
  949. # Don't use -f so that the HTTP response code is ignored.
  950. # Use --stderr - to redirect stderr to stdout so we get
  951. # error output for sure in stdout.
  952. # Use -sS to hide progress bar, but show errors.
  953. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  954. # HTTP output may not end in a newline, so add that here.
  955. out.write( "\n\n" )
  956. out.flush()
  957. err.flush()
  958. # We need to get the respond body from the curl and return it.
  959. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  960. output = p.communicate()
  961. except:
  962. pass
  963. if output:
  964. # We have the response body - return it
  965. return output[0]
  966. ##############################################################
  967. # End __curl_url
  968. ##############################################################
  969. def requires_database(self):
  970. """Returns True/False if this test requires a database"""
  971. return (self.contains_type(self.FORTUNE) or
  972. self.contains_type(self.DB) or
  973. self.contains_type(self.QUERY) or
  974. self.contains_type(self.UPDATE))
  975. ############################################################
  976. # __begin_logging
  977. # Starts a thread to monitor the resource usage, to be synced with the client's time
  978. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  979. ############################################################
  980. def __begin_logging(self, test_name):
  981. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_name))
  982. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  983. --raw --socket --tcp --udp --unix --vm --disk-util \
  984. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  985. cmd = shlex.split(dstat_string)
  986. dev_null = open(os.devnull, "w")
  987. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  988. ##############################################################
  989. # End __begin_logging
  990. ##############################################################
  991. ##############################################################
  992. # Begin __end_logging
  993. # Stops the logger thread and blocks until shutdown is complete.
  994. ##############################################################
  995. def __end_logging(self):
  996. self.subprocess_handle.terminate()
  997. self.subprocess_handle.communicate()
  998. ##############################################################
  999. # End __end_logging
  1000. ##############################################################
  1001. ##############################################################
  1002. # Begin __parse_stats
  1003. # For each test type, process all the statistics, and return a multi-layered dictionary
  1004. # that has a structure as follows:
  1005. # (timestamp)
  1006. # | (main header) - group that the stat is in
  1007. # | | (sub header) - title of the stat
  1008. # | | | (stat) - the stat itself, usually a floating point number
  1009. ##############################################################
  1010. def __parse_stats(self, test_type, start_time, end_time, interval):
  1011. stats_dict = dict()
  1012. stats_file = self.benchmarker.stats_file(self.name, test_type)
  1013. with open(stats_file) as stats:
  1014. while(stats.next() != "\n"):
  1015. pass
  1016. stats_reader = csv.reader(stats)
  1017. h1= stats_reader.next()
  1018. h2 = stats_reader.next()
  1019. time_row = h2.index("epoch")
  1020. int_counter = 0
  1021. for row in stats_reader:
  1022. time = float(row[time_row])
  1023. int_counter+=1
  1024. if time < start_time:
  1025. continue
  1026. elif time > end_time:
  1027. return stats_dict
  1028. if int_counter % interval != 0:
  1029. continue
  1030. row_dict = dict()
  1031. for nextheader in h1:
  1032. if nextheader != "":
  1033. row_dict[nextheader] = dict()
  1034. header = ""
  1035. for item_num in range(len(row)):
  1036. if(len(h1[item_num]) != 0):
  1037. header = h1[item_num]
  1038. row_dict[header][h2[item_num]] = row[item_num]
  1039. stats_dict[time] = row_dict
  1040. return stats_dict
  1041. ##############################################################
  1042. # End __parse_stats
  1043. ##############################################################
  1044. ##########################################################################################
  1045. # Constructor
  1046. ##########################################################################################
  1047. def __init__(self, name, directory, benchmarker, runTests, args):
  1048. self.name = name
  1049. self.directory = directory
  1050. self.benchmarker = benchmarker
  1051. self.runTests = runTests
  1052. self.fwroot = benchmarker.fwroot
  1053. # setup logging
  1054. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  1055. self.install_root="%s/%s" % (self.fwroot, "installs")
  1056. if benchmarker.install_strategy is 'pertest':
  1057. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1058. self.__dict__.update(args)
  1059. # ensure directory has __init__.py file so that we can use it as a Python package
  1060. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1061. open(os.path.join(directory, "__init__.py"), 'w').close()
  1062. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  1063. ############################################################
  1064. # End __init__
  1065. ############################################################
  1066. ############################################################
  1067. # End FrameworkTest
  1068. ############################################################
  1069. ##########################################################################################
  1070. # Static methods
  1071. ##########################################################################################
  1072. ##############################################################
  1073. # parse_config(config, directory, benchmarker)
  1074. # parses a config file and returns a list of FrameworkTest
  1075. # objects based on that config file.
  1076. ##############################################################
  1077. def parse_config(config, directory, benchmarker):
  1078. tests = []
  1079. # The config object can specify multiple tests, we neep to loop
  1080. # over them and parse them out
  1081. for test in config['tests']:
  1082. for key, value in test.iteritems():
  1083. test_name = config['framework']
  1084. runTests = dict()
  1085. runTests["json"] = (benchmarker.type == "all" or benchmarker.type == "json") and value.get("json_url", False)
  1086. runTests["db"] = (benchmarker.type == "all" or benchmarker.type == "db") and value.get("db_url", False)
  1087. runTests["query"] = (benchmarker.type == "all" or benchmarker.type == "query") and value.get("query_url", False)
  1088. runTests["fortune"] = (benchmarker.type == "all" or benchmarker.type == "fortune") and value.get("fortune_url", False)
  1089. runTests["update"] = (benchmarker.type == "all" or benchmarker.type == "update") and value.get("update_url", False)
  1090. runTests["plaintext"] = (benchmarker.type == "all" or benchmarker.type == "plaintext") and value.get("plaintext_url", False)
  1091. # if the test uses the 'defualt' keywork, then we don't
  1092. # append anything to it's name. All configs should only have 1 default
  1093. if key != 'default':
  1094. # we need to use the key in the test_name
  1095. test_name = test_name + "-" + key
  1096. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, value))
  1097. return tests
  1098. ##############################################################
  1099. # End parse_config
  1100. ##############################################################