framework_test.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. from benchmark.fortune_html_parser import FortuneHTMLParser
  2. import importlib
  3. import os
  4. import subprocess
  5. import time
  6. import re
  7. import pprint
  8. import sys
  9. import traceback
  10. import json
  11. import textwrap
  12. class FrameworkTest:
  13. ##########################################################################################
  14. # Class variables
  15. ##########################################################################################
  16. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  17. 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'"
  18. accept_json = "Accept: application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  19. accept_html = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  20. accept_plaintext = "Accept: text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  21. concurrency_template = """
  22. echo ""
  23. echo "---------------------------------------------------------"
  24. echo " Running Primer {name}"
  25. echo " {wrk} {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}\""
  26. echo "---------------------------------------------------------"
  27. echo ""
  28. {wrk} {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}"
  29. sleep 5
  30. echo ""
  31. echo "---------------------------------------------------------"
  32. echo " Running Warmup {name}"
  33. echo " {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  34. echo "---------------------------------------------------------"
  35. echo ""
  36. {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  37. sleep 5
  38. for c in {interval}
  39. do
  40. echo ""
  41. echo "---------------------------------------------------------"
  42. echo " Concurrency: $c for {name}"
  43. echo " {wrk} {headers} {pipeline} -d {duration} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  44. echo "---------------------------------------------------------"
  45. echo ""
  46. {wrk} {headers} {pipeline} -d {duration} -c "$c" -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  47. sleep 2
  48. done
  49. """
  50. query_template = """
  51. echo ""
  52. echo "---------------------------------------------------------"
  53. echo " Running Primer {name}"
  54. echo " wrk {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}2\""
  55. echo "---------------------------------------------------------"
  56. echo ""
  57. wrk {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}2"
  58. sleep 5
  59. echo ""
  60. echo "---------------------------------------------------------"
  61. echo " Running Warmup {name}"
  62. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  63. echo "---------------------------------------------------------"
  64. echo ""
  65. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  66. sleep 5
  67. for c in {interval}
  68. do
  69. echo ""
  70. echo "---------------------------------------------------------"
  71. echo " Queries: $c for {name}"
  72. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  73. echo "---------------------------------------------------------"
  74. echo ""
  75. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  76. sleep 2
  77. done
  78. """
  79. language = None
  80. platform = None
  81. webserver = None
  82. classification = None
  83. database = None
  84. approach = None
  85. orm = None
  86. framework = None
  87. os = None
  88. database_os = None
  89. display_name = None
  90. notes = None
  91. versus = None
  92. ############################################################
  93. # Test Variables
  94. ############################################################
  95. JSON = "json"
  96. DB = "db"
  97. QUERY = "query"
  98. FORTUNE = "fortune"
  99. UPDATE = "update"
  100. PLAINTEXT = "plaintext"
  101. ##########################################################################################
  102. # Public Methods
  103. ##########################################################################################
  104. ############################################################
  105. # Validates the jsonString is a JSON object with a 'message'
  106. # key with the value "hello, world!" (case-insensitive).
  107. ############################################################
  108. def validateJson(self, jsonString, out, err):
  109. try:
  110. obj = json.loads(jsonString)
  111. if obj["message"].lower() == "hello, world!":
  112. return True
  113. except:
  114. err.write(textwrap.dedent("""
  115. -----------------------------------------------------
  116. Error: validateJson raised exception
  117. -----------------------------------------------------
  118. {trace}
  119. """.format( trace=sys.exc_info()[:2])))
  120. return False
  121. ############################################################
  122. # Validates the jsonString is a JSON object that has an "id"
  123. # and a "randomNumber" key, and that both keys map to
  124. # integers.
  125. ############################################################
  126. def validateDb(self, jsonString, out, err):
  127. try:
  128. obj = json.loads(jsonString)
  129. # This will error out of the value could not parsed to a
  130. # float (this will work with ints, but it will turn them
  131. # into their float equivalent; i.e. "123" => 123.0)
  132. if type(float(obj["id"])) == float and type(float(obj["randomNumber"])) == float:
  133. return True
  134. except:
  135. err.write(textwrap.dedent("""
  136. -----------------------------------------------------
  137. Error: validateDb raised exception
  138. -----------------------------------------------------
  139. {trace}
  140. """.format( trace=sys.exc_info()[:2])))
  141. return False
  142. ############################################################
  143. # Validates the jsonString is an array with a length of
  144. # 2, that each entry in the array is a JSON object, that
  145. # each object has an "id" and a "randomNumber" key, and that
  146. # both keys map to integers.
  147. ############################################################
  148. def validateQuery(self, jsonString, out, err):
  149. try:
  150. arr = json.loads(jsonString)
  151. if type(float(arr[0]["id"])) == float and type(float(arr[0]["randomNumber"])) == float and type(float(arr[1]["id"])) == float and type(float(arr[1]["randomNumber"])) == float:
  152. return True
  153. except:
  154. err.write(textwrap.dedent("""
  155. -----------------------------------------------------
  156. Error: validateQuery raised exception
  157. -----------------------------------------------------
  158. {trace}
  159. """.format( trace=sys.exc_info()[:2])))
  160. return False
  161. ############################################################
  162. # Parses the given HTML string and asks a FortuneHTMLParser
  163. # whether the parsed string is a valid fortune return.
  164. ############################################################
  165. def validateFortune(self, htmlString, out, err):
  166. try:
  167. parser = FortuneHTMLParser()
  168. parser.feed(htmlString)
  169. return parser.isValidFortune()
  170. except:
  171. err.write(textwrap.dedent("""
  172. -----------------------------------------------------
  173. Error: validateFortune raised exception
  174. -----------------------------------------------------
  175. {trace}
  176. """.format( trace=sys.exc_info()[:2])))
  177. return False
  178. ############################################################
  179. # Validates the jsonString is an array with a length of
  180. # 2, that each entry in the array is a JSON object, that
  181. # each object has an "id" and a "randomNumber" key, and that
  182. # both keys map to integers.
  183. ############################################################
  184. def validateUpdate(self, jsonString, out, err):
  185. try:
  186. arr = json.loads(jsonString)
  187. if type(float(arr[0]["id"])) == float and type(float(arr[0]["randomNumber"])) == float and type(float(arr[1]["id"])) == float and type(float(arr[1]["randomNumber"])) == float:
  188. return True
  189. except:
  190. err.write(textwrap.dedent("""
  191. -----------------------------------------------------
  192. Error: validateUpdate raised exception
  193. -----------------------------------------------------
  194. {trace}
  195. """.format( trace=sys.exc_info()[:2])))
  196. return False
  197. ############################################################
  198. #
  199. ############################################################
  200. def validatePlaintext(self, jsonString, out, err):
  201. try:
  202. return jsonString.lower().strip() == "hello, world!"
  203. except:
  204. err.write(textwrap.dedent("""
  205. -----------------------------------------------------
  206. Error: validatePlaintext raised exception
  207. -----------------------------------------------------
  208. {trace}
  209. """.format( trace=sys.exc_info()[:2])))
  210. return False
  211. ############################################################
  212. # start(benchmarker)
  213. # Start the test using it's setup file
  214. ############################################################
  215. def start(self, out, err):
  216. return self.setup_module.start(self.benchmarker, out, err)
  217. ############################################################
  218. # End start
  219. ############################################################
  220. ############################################################
  221. # stop(benchmarker)
  222. # Stops the test using it's setup file
  223. ############################################################
  224. def stop(self, out, err):
  225. return self.setup_module.stop(out, err)
  226. ############################################################
  227. # End stop
  228. ############################################################
  229. ############################################################
  230. # verify_urls
  231. # Verifys each of the URLs for this test. THis will sinply
  232. # curl the URL and check for it's return status.
  233. # For each url, a flag will be set on this object for whether
  234. # or not it passed
  235. ############################################################
  236. def verify_urls(self, out, err):
  237. # JSON
  238. if self.runTests[self.JSON]:
  239. out.write( "VERIFYING JSON (" + self.json_url + ") ...\n" )
  240. out.flush()
  241. try:
  242. url = self.benchmarker.generate_url(self.json_url, self.port)
  243. output = self.__curl_url(url, self.JSON, out, err)
  244. if self.validateJson(output, out, err):
  245. self.json_url_passed = True
  246. else:
  247. self.json_url_passed = False
  248. except (AttributeError, subprocess.CalledProcessError) as e:
  249. self.json_url_passed = False
  250. out.write("VALIDATING JSON ... ")
  251. if self.json_url_passed:
  252. out.write("PASS\n\n")
  253. else:
  254. out.write("FAIL\n\n")
  255. out.flush
  256. # DB
  257. if self.runTests[self.DB]:
  258. out.write( "VERIFYING DB (" + self.db_url + ") ...\n" )
  259. out.flush()
  260. try:
  261. url = self.benchmarker.generate_url(self.db_url, self.port)
  262. output = self.__curl_url(url, self.DB, out, err)
  263. if self.validateDb(output, out, err):
  264. self.db_url_passed = True
  265. else:
  266. self.db_url_passed = False
  267. except (AttributeError, subprocess.CalledProcessError) as e:
  268. self.db_url_passed = False
  269. out.write("VALIDATING DB ... ")
  270. if self.db_url_passed:
  271. out.write("PASS\n\n")
  272. else:
  273. out.write("FAIL\n\n")
  274. out.flush
  275. # Query
  276. if self.runTests[self.QUERY]:
  277. out.write( "VERIFYING QUERY (" + self.query_url + "2) ...\n" )
  278. out.flush()
  279. try:
  280. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  281. output = self.__curl_url(url, self.QUERY, out, err)
  282. if self.validateQuery(output, out, err):
  283. self.query_url_passed = True
  284. else:
  285. self.query_url_passed = False
  286. except (AttributeError, subprocess.CalledProcessError) as e:
  287. self.query_url_passed = False
  288. out.write("VALIDATING QUERY ... ")
  289. if self.query_url_passed:
  290. out.write("PASS\n\n")
  291. else:
  292. out.write("FAIL\n\n")
  293. out.flush
  294. # Fortune
  295. if self.runTests[self.FORTUNE]:
  296. out.write( "VERIFYING FORTUNE (" + self.fortune_url + ") ...\n" )
  297. out.flush()
  298. try:
  299. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  300. output = self.__curl_url(url, self.FORTUNE, out, err)
  301. if self.validateFortune(output, out, err):
  302. self.fortune_url_passed = True
  303. else:
  304. self.fortune_url_passed = False
  305. except (AttributeError, subprocess.CalledProcessError) as e:
  306. self.fortune_url_passed = False
  307. out.write("VALIDATING FORTUNE ... ")
  308. if self.fortune_url_passed:
  309. out.write("PASS\n\n")
  310. else:
  311. out.write("FAIL\n\n")
  312. out.flush
  313. # Update
  314. if self.runTests[self.UPDATE]:
  315. out.write( "VERIFYING UPDATE (" + self.update_url + "2) ...\n" )
  316. out.flush()
  317. try:
  318. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  319. output = self.__curl_url(url, self.UPDATE, out, err)
  320. if self.validateUpdate(output, out, err):
  321. self.update_url_passed = True
  322. else:
  323. self.update_url_passed = False
  324. except (AttributeError, subprocess.CalledProcessError) as e:
  325. self.update_url_passed = False
  326. out.write("VALIDATING UPDATE ... ")
  327. if self.update_url_passed:
  328. out.write("PASS\n\n")
  329. else:
  330. out.write("FAIL\n\n")
  331. out.flush
  332. # plaintext
  333. if self.runTests[self.PLAINTEXT]:
  334. out.write( "VERIFYING PLAINTEXT (" + self.plaintext_url + ") ...\n" )
  335. out.flush()
  336. try:
  337. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  338. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  339. if self.validatePlaintext(output, out, err):
  340. self.plaintext_url_passed = True
  341. else:
  342. self.plaintext_url_passed = False
  343. except (AttributeError, subprocess.CalledProcessError) as e:
  344. self.plaintext_url_passed = False
  345. out.write("VALIDATING PLAINTEXT ... ")
  346. if self.plaintext_url_passed:
  347. out.write("PASS\n\n")
  348. else:
  349. out.write("FAIL\n\n")
  350. out.flush
  351. ############################################################
  352. # End verify_urls
  353. ############################################################
  354. ############################################################
  355. # contains_type(type)
  356. # true if this test contains an implementation of the given
  357. # test type (json, db, etc.)
  358. ############################################################
  359. def contains_type(self, type):
  360. try:
  361. if type == self.JSON and self.json_url != None:
  362. return True
  363. if type == self.DB and self.db_url != None:
  364. return True
  365. if type == self.QUERY and self.query_url != None:
  366. return True
  367. if type == self.FORTUNE and self.fortune_url != None:
  368. return True
  369. if type == self.UPDATE and self.update_url != None:
  370. return True
  371. if type == self.PLAINTEXT and self.plaintext_url != None:
  372. return True
  373. except AttributeError:
  374. pass
  375. return False
  376. ############################################################
  377. # End stop
  378. ############################################################
  379. ############################################################
  380. # benchmark
  381. # Runs the benchmark for each type of test that it implements
  382. # JSON/DB/Query.
  383. ############################################################
  384. def benchmark(self, out, err):
  385. # JSON
  386. if self.runTests[self.JSON]:
  387. try:
  388. if self.benchmarker.type == "all" or self.benchmarker.type == self.JSON:
  389. out.write("BENCHMARKING JSON ... ")
  390. out.flush()
  391. results = None
  392. output_file = self.benchmarker.output_file(self.name, self.JSON)
  393. if not os.path.exists(output_file):
  394. with open(output_file, 'w'):
  395. # Simply opening the file in write mode should create the empty file.
  396. pass
  397. if self.json_url_passed:
  398. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  399. self.__run_benchmark(remote_script, output_file, err)
  400. results = self.__parse_test(self.JSON)
  401. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  402. out.write( "Complete\n" )
  403. out.flush()
  404. except AttributeError:
  405. pass
  406. # DB
  407. if self.runTests[self.DB]:
  408. try:
  409. if self.benchmarker.type == "all" or self.benchmarker.type == self.DB:
  410. out.write("BENCHMARKING DB ... ")
  411. out.flush()
  412. results = None
  413. output_file = self.benchmarker.output_file(self.name, self.DB)
  414. if not os.path.exists(output_file):
  415. with open(output_file, 'w'):
  416. # Simply opening the file in write mode should create the empty file.
  417. pass
  418. if self.db_url_passed:
  419. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  420. self.__run_benchmark(remote_script, output_file, err)
  421. results = self.__parse_test(self.DB)
  422. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  423. out.write( "Complete\n" )
  424. except AttributeError:
  425. pass
  426. # Query
  427. if self.runTests[self.QUERY]:
  428. try:
  429. if self.benchmarker.type == "all" or self.benchmarker.type == self.QUERY:
  430. out.write("BENCHMARKING Query ... ")
  431. out.flush()
  432. results = None
  433. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  434. if not os.path.exists(output_file):
  435. with open(output_file, 'w'):
  436. # Simply opening the file in write mode should create the empty file.
  437. pass
  438. if self.query_url_passed:
  439. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  440. self.__run_benchmark(remote_script, output_file, err)
  441. results = self.__parse_test(self.QUERY)
  442. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  443. out.write( "Complete\n" )
  444. out.flush()
  445. except AttributeError:
  446. pass
  447. # fortune
  448. if self.runTests[self.FORTUNE]:
  449. try:
  450. if self.benchmarker.type == "all" or self.benchmarker.type == self.FORTUNE:
  451. out.write("BENCHMARKING Fortune ... ")
  452. out.flush()
  453. results = None
  454. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  455. if not os.path.exists(output_file):
  456. with open(output_file, 'w'):
  457. # Simply opening the file in write mode should create the empty file.
  458. pass
  459. if self.fortune_url_passed:
  460. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  461. self.__run_benchmark(remote_script, output_file, err)
  462. results = self.__parse_test(self.FORTUNE)
  463. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  464. out.write( "Complete\n" )
  465. out.flush()
  466. except AttributeError:
  467. pass
  468. # update
  469. if self.runTests[self.UPDATE]:
  470. try:
  471. if self.benchmarker.type == "all" or self.benchmarker.type == self.UPDATE:
  472. out.write("BENCHMARKING Update ... ")
  473. out.flush()
  474. results = None
  475. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  476. if not os.path.exists(output_file):
  477. with open(output_file, 'w'):
  478. # Simply opening the file in write mode should create the empty file.
  479. pass
  480. if self.update_url_passed:
  481. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  482. self.__run_benchmark(remote_script, output_file, err)
  483. results = self.__parse_test(self.UPDATE)
  484. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  485. out.write( "Complete\n" )
  486. out.flush()
  487. except AttributeError:
  488. pass
  489. # plaintext
  490. if self.runTests[self.PLAINTEXT]:
  491. try:
  492. if self.benchmarker.type == "all" or self.benchmarker.type == self.PLAINTEXT:
  493. out.write("BENCHMARKING Plaintext ... ")
  494. out.flush()
  495. results = None
  496. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  497. if not os.path.exists(output_file):
  498. with open(output_file, 'w'):
  499. # Simply opening the file in write mode should create the empty file.
  500. pass
  501. if self.plaintext_url_passed:
  502. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk-pipeline", intervals=[256,1024,4096,16384], pipeline="--pipeline 16")
  503. self.__run_benchmark(remote_script, output_file, err)
  504. results = self.__parse_test(self.PLAINTEXT)
  505. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  506. out.write( "Complete\n" )
  507. out.flush()
  508. except AttributeError:
  509. traceback.print_exc()
  510. pass
  511. ############################################################
  512. # End benchmark
  513. ############################################################
  514. ############################################################
  515. # parse_all
  516. # Method meant to be run for a given timestamp
  517. ############################################################
  518. def parse_all(self):
  519. # JSON
  520. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  521. results = self.__parse_test(self.JSON)
  522. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  523. # DB
  524. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  525. results = self.__parse_test(self.DB)
  526. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  527. # Query
  528. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  529. results = self.__parse_test(self.QUERY)
  530. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  531. # Fortune
  532. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  533. results = self.__parse_test(self.FORTUNE)
  534. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  535. # Update
  536. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  537. results = self.__parse_test(self.UPDATE)
  538. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  539. # Plaintext
  540. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  541. results = self.__parse_test(self.PLAINTEXT)
  542. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  543. ############################################################
  544. # End parse_all
  545. ############################################################
  546. ############################################################
  547. # __parse_test(test_type)
  548. ############################################################
  549. def __parse_test(self, test_type):
  550. try:
  551. results = dict()
  552. results['results'] = []
  553. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  554. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  555. is_warmup = True
  556. rawData = None
  557. for line in raw_data:
  558. if "Queries:" in line or "Concurrency:" in line:
  559. is_warmup = False
  560. rawData = None
  561. continue
  562. if "Warmup" in line or "Primer" in line:
  563. is_warmup = True
  564. continue
  565. if not is_warmup:
  566. if rawData == None:
  567. rawData = dict()
  568. results['results'].append(rawData)
  569. #if "Requests/sec:" in line:
  570. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  571. # rawData['reportedResults'] = m.group(1)
  572. # search for weighttp data such as succeeded and failed.
  573. if "Latency" in line:
  574. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  575. if len(m) == 4:
  576. rawData['latencyAvg'] = m[0]
  577. rawData['latencyStdev'] = m[1]
  578. rawData['latencyMax'] = m[2]
  579. # rawData['latencyStdevPercent'] = m[3]
  580. #if "Req/Sec" in line:
  581. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  582. # if len(m) == 4:
  583. # rawData['requestsAvg'] = m[0]
  584. # rawData['requestsStdev'] = m[1]
  585. # rawData['requestsMax'] = m[2]
  586. # rawData['requestsStdevPercent'] = m[3]
  587. #if "requests in" in line:
  588. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  589. # if m != None:
  590. # # parse out the raw time, which may be in minutes or seconds
  591. # raw_time = m.group(1)
  592. # if "ms" in raw_time:
  593. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  594. # elif "s" in raw_time:
  595. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  596. # elif "m" in raw_time:
  597. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  598. # elif "h" in raw_time:
  599. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  600. if "requests in" in line:
  601. m = re.search("([0-9]+) requests in", line)
  602. if m != None:
  603. rawData['totalRequests'] = int(m.group(1))
  604. if "Socket errors" in line:
  605. if "connect" in line:
  606. m = re.search("connect ([0-9]+)", line)
  607. rawData['connect'] = int(m.group(1))
  608. if "read" in line:
  609. m = re.search("read ([0-9]+)", line)
  610. rawData['read'] = int(m.group(1))
  611. if "write" in line:
  612. m = re.search("write ([0-9]+)", line)
  613. rawData['write'] = int(m.group(1))
  614. if "timeout" in line:
  615. m = re.search("timeout ([0-9]+)", line)
  616. rawData['timeout'] = int(m.group(1))
  617. if "Non-2xx" in line:
  618. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  619. if m != None:
  620. rawData['5xx'] = int(m.group(1))
  621. return results
  622. except IOError:
  623. return None
  624. ############################################################
  625. # End benchmark
  626. ############################################################
  627. ##########################################################################################
  628. # Private Methods
  629. ##########################################################################################
  630. ############################################################
  631. # __run_benchmark(script, output_file)
  632. # Runs a single benchmark using the script which is a bash
  633. # template that uses weighttp to run the test. All the results
  634. # outputed to the output_file.
  635. ############################################################
  636. def __run_benchmark(self, script, output_file, err):
  637. with open(output_file, 'w') as raw_file:
  638. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  639. p.communicate(script)
  640. err.flush()
  641. ############################################################
  642. # End __run_benchmark
  643. ############################################################
  644. ############################################################
  645. # __generate_concurrency_script(url, port)
  646. # Generates the string containing the bash script that will
  647. # be run on the client to benchmark a single test. This
  648. # specifically works for the variable concurrency tests (JSON
  649. # and DB)
  650. ############################################################
  651. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  652. if len(intervals) == 0:
  653. intervals = self.benchmarker.concurrency_levels
  654. headers = self.__get_request_headers(accept_header)
  655. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  656. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  657. interval=" ".join("{}".format(item) for item in intervals),
  658. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  659. pipeline=pipeline)
  660. ############################################################
  661. # End __generate_concurrency_script
  662. ############################################################
  663. ############################################################
  664. # __generate_query_script(url, port)
  665. # Generates the string containing the bash script that will
  666. # be run on the client to benchmark a single test. This
  667. # specifically works for the variable query tests (Query)
  668. ############################################################
  669. def __generate_query_script(self, url, port, accept_header):
  670. headers = self.__get_request_headers(accept_header)
  671. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  672. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  673. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  674. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  675. ############################################################
  676. # End __generate_query_script
  677. ############################################################
  678. ############################################################
  679. # __get_request_headers(accept_header)
  680. # Generates the complete HTTP header string
  681. ############################################################
  682. def __get_request_headers(self, accept_header):
  683. return self.headers_template.format(accept=accept_header)
  684. ############################################################
  685. # End __format_request_headers
  686. ############################################################
  687. ############################################################
  688. # __curl_url
  689. # Dump HTTP response and headers. Throw exception if there
  690. # is an HTTP error.
  691. ############################################################
  692. def __curl_url(self, url, testType, out, err):
  693. # Use -i to output response with headers.
  694. # Don't use -f so that the HTTP response code is ignored.
  695. # Use --stderr - to redirect stderr to stdout so we get
  696. # error output for sure in stdout.
  697. # Use -sS to hide progress bar, but show errors.
  698. subprocess.check_call(["curl", "-i", "-sS", url], stderr=err, stdout=out)
  699. out.flush()
  700. err.flush()
  701. # HTTP output may not end in a newline, so add that here.
  702. out.write( "\n" )
  703. out.flush()
  704. # We need to get the respond body from the curl and return it.
  705. p = subprocess.Popen(["curl", "-s", url], stdout=subprocess.PIPE)
  706. output = p.communicate()
  707. # In the curl invocation above we could not use -f because
  708. # then the HTTP response would not be output, so use -f in
  709. # an additional invocation so that if there is an HTTP error,
  710. # subprocess.CalledProcessError will be thrown. Note that this
  711. # uses check_output() instead of check_call() so that we can
  712. # ignore the HTTP response because we already output that in
  713. # the first curl invocation.
  714. subprocess.check_output(["curl", "-fsS", url], stderr=err)
  715. err.flush()
  716. # HTTP output may not end in a newline, so add that here.
  717. out.write( "\n" )
  718. out.flush()
  719. if output:
  720. # We have the response body - return it
  721. return output[0]
  722. ##############################################################
  723. # End __curl_url
  724. ##############################################################
  725. ##########################################################################################
  726. # Constructor
  727. ##########################################################################################
  728. def __init__(self, name, directory, benchmarker, runTests, args):
  729. self.name = name
  730. self.directory = directory
  731. self.benchmarker = benchmarker
  732. self.runTests = runTests
  733. self.__dict__.update(args)
  734. # ensure directory has __init__.py file so that we can use it as a Python package
  735. if not os.path.exists(os.path.join(directory, "__init__.py")):
  736. open(os.path.join(directory, "__init__.py"), 'w').close()
  737. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  738. ############################################################
  739. # End __init__
  740. ############################################################
  741. ############################################################
  742. # End FrameworkTest
  743. ############################################################
  744. ##########################################################################################
  745. # Static methods
  746. ##########################################################################################
  747. ##############################################################
  748. # parse_config(config, directory, benchmarker)
  749. # parses a config file and returns a list of FrameworkTest
  750. # objects based on that config file.
  751. ##############################################################
  752. def parse_config(config, directory, benchmarker):
  753. tests = []
  754. # The config object can specify multiple tests, we neep to loop
  755. # over them and parse them out
  756. for test in config['tests']:
  757. for key, value in test.iteritems():
  758. test_name = config['framework']
  759. runTests = dict()
  760. runTests["json"] = True if value.get("json_url", False) else False
  761. runTests["db"] = True if value.get("db_url", False) else False
  762. runTests["query"] = True if value.get("query_url", False) else False
  763. runTests["fortune"] = True if value.get("fortune_url", False) else False
  764. runTests["update"] = True if value.get("update_url", False) else False
  765. runTests["plaintext"] = True if value.get("plaintext_url", False) else False
  766. # if the test uses the 'defualt' keywork, then we don't
  767. # append anything to it's name. All configs should only have 1 default
  768. if key != 'default':
  769. # we need to use the key in the test_name
  770. test_name = test_name + "-" + key
  771. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, value))
  772. return tests
  773. ##############################################################
  774. # End parse_config
  775. ##############################################################