framework_test.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. # We are allowing the single-object array for the DB
  130. # test for now, but will likely remove this later.
  131. if type(obj) == list:
  132. obj = obj[0]
  133. # This will error out of the value could not parsed to a
  134. # float (this will work with ints, but it will turn them
  135. # into their float equivalent; i.e. "123" => 123.0)
  136. if (type(float(obj["id"])) == float and
  137. type(float(obj["randomNumber"])) == float):
  138. return True
  139. except:
  140. err.write(textwrap.dedent("""
  141. -----------------------------------------------------
  142. Error: validateDb raised exception
  143. -----------------------------------------------------
  144. {trace}
  145. """.format( trace=sys.exc_info()[:2])))
  146. return False
  147. def validateDbStrict(self, jsonString, out, err):
  148. try:
  149. obj = json.loads(jsonString)
  150. # This will error out of the value could not parsed to a
  151. # float (this will work with ints, but it will turn them
  152. # into their float equivalent; i.e. "123" => 123.0)
  153. if (type(float(obj["id"])) == float and
  154. type(float(obj["randomNumber"])) == float):
  155. return True
  156. except:
  157. err.write(textwrap.dedent("""
  158. -----------------------------------------------------
  159. Error: validateDbStrict raised exception
  160. -----------------------------------------------------
  161. {trace}
  162. """.format( trace=sys.exc_info()[:2])))
  163. return False
  164. ############################################################
  165. # Validates the jsonString is an array with a length of
  166. # 2, that each entry in the array is a JSON object, that
  167. # each object has an "id" and a "randomNumber" key, and that
  168. # both keys map to integers.
  169. ############################################################
  170. def validateQuery(self, jsonString, out, err):
  171. try:
  172. arr = json.loads(jsonString)
  173. if (type(float(arr[0]["id"])) == float and
  174. type(float(arr[0]["randomNumber"])) == float and
  175. type(float(arr[1]["id"])) == float and
  176. type(float(arr[1]["randomNumber"])) == float):
  177. return True
  178. except:
  179. err.write(textwrap.dedent("""
  180. -----------------------------------------------------
  181. Error: validateQuery raised exception
  182. -----------------------------------------------------
  183. {trace}
  184. """.format( trace=sys.exc_info()[:2])))
  185. return False
  186. ############################################################
  187. # Validates the jsonString is an array with a length of
  188. # 1, that each entry in the array is a JSON object, that
  189. # each object has an "id" and a "randomNumber" key, and that
  190. # both keys map to integers.
  191. ############################################################
  192. def validateQueryOneOrLess(self, jsonString, out, err):
  193. try:
  194. arr = json.loads(jsonString)
  195. if len(arr) != 1:
  196. return False
  197. for obj in arr:
  198. if (type(float(obj["id"])) != float or
  199. type(float(obj["randomNumber"])) != float or
  200. type(float(obj["id"])) != float or
  201. type(float(obj["randomNumber"])) != float):
  202. return False
  203. # By here, it's passed validation
  204. return True
  205. except:
  206. err.write(textwrap.dedent("""
  207. -----------------------------------------------------
  208. Error: validateQuery raised exception
  209. -----------------------------------------------------
  210. {trace}
  211. """.format( trace=sys.exc_info()[:2])))
  212. return False
  213. ############################################################
  214. # Validates the jsonString is an array with a length of
  215. # 500, that each entry in the array is a JSON object, that
  216. # each object has an "id" and a "randomNumber" key, and that
  217. # both keys map to integers.
  218. ############################################################
  219. def validateQueryFiveHundredOrMore(self, jsonString, out, err):
  220. try:
  221. arr = json.loads(jsonString)
  222. if len(arr) != 500:
  223. return False
  224. for obj in arr:
  225. if (type(float(obj["id"])) != float or
  226. type(float(obj["randomNumber"])) != float or
  227. type(float(obj["id"])) != float or
  228. type(float(obj["randomNumber"])) != float):
  229. return False
  230. # By here, it's passed validation
  231. return True
  232. except:
  233. err.write(textwrap.dedent("""
  234. -----------------------------------------------------
  235. Error: validateQuery raised exception
  236. -----------------------------------------------------
  237. {trace}
  238. """.format( trace=sys.exc_info()[:2])))
  239. return False
  240. ############################################################
  241. # Parses the given HTML string and asks a FortuneHTMLParser
  242. # whether the parsed string is a valid fortune return.
  243. ############################################################
  244. def validateFortune(self, htmlString, out, err):
  245. try:
  246. parser = FortuneHTMLParser()
  247. parser.feed(htmlString)
  248. return parser.isValidFortune()
  249. except:
  250. err.write(textwrap.dedent("""
  251. -----------------------------------------------------
  252. Error: validateFortune raised exception
  253. -----------------------------------------------------
  254. {trace}
  255. """.format( trace=sys.exc_info()[:2])))
  256. return False
  257. ############################################################
  258. # Validates the jsonString is an array with a length of
  259. # 2, that each entry in the array is a JSON object, that
  260. # each object has an "id" and a "randomNumber" key, and that
  261. # both keys map to integers.
  262. ############################################################
  263. def validateUpdate(self, jsonString, out, err):
  264. try:
  265. arr = json.loads(jsonString)
  266. if (type(float(arr[0]["id"])) == float and
  267. type(float(arr[0]["randomNumber"])) == float and
  268. type(float(arr[1]["id"])) == float and
  269. type(float(arr[1]["randomNumber"])) == float):
  270. return True
  271. except:
  272. err.write(textwrap.dedent("""
  273. -----------------------------------------------------
  274. Error: validateUpdate raised exception
  275. -----------------------------------------------------
  276. {trace}
  277. """.format( trace=sys.exc_info()[:2])))
  278. return False
  279. ############################################################
  280. #
  281. ############################################################
  282. def validatePlaintext(self, jsonString, out, err):
  283. try:
  284. return jsonString.lower().strip() == "hello, world!"
  285. except:
  286. err.write(textwrap.dedent("""
  287. -----------------------------------------------------
  288. Error: validatePlaintext raised exception
  289. -----------------------------------------------------
  290. {trace}
  291. """.format( trace=sys.exc_info()[:2])))
  292. return False
  293. ############################################################
  294. # start(benchmarker)
  295. # Start the test using it's setup file
  296. ############################################################
  297. def start(self, out, err):
  298. return self.setup_module.start(self.benchmarker, out, err)
  299. ############################################################
  300. # End start
  301. ############################################################
  302. ############################################################
  303. # stop(benchmarker)
  304. # Stops the test using it's setup file
  305. ############################################################
  306. def stop(self, out, err):
  307. return self.setup_module.stop(out, err)
  308. ############################################################
  309. # End stop
  310. ############################################################
  311. ############################################################
  312. # verify_urls
  313. # Verifys each of the URLs for this test. THis will sinply
  314. # curl the URL and check for it's return status.
  315. # For each url, a flag will be set on this object for whether
  316. # or not it passed
  317. ############################################################
  318. def verify_urls(self, out, err):
  319. # JSON
  320. if self.runTests[self.JSON]:
  321. out.write( "VERIFYING JSON (" + self.json_url + ") ...\n" )
  322. out.flush()
  323. try:
  324. url = self.benchmarker.generate_url(self.json_url, self.port)
  325. output = self.__curl_url(url, self.JSON, out, err)
  326. if self.validateJson(output, out, err):
  327. self.json_url_passed = True
  328. else:
  329. self.json_url_passed = False
  330. except (AttributeError, subprocess.CalledProcessError):
  331. err.write(textwrap.dedent("""
  332. -----------------------------------------------------
  333. Error: verify_urls raised exception (JSON)
  334. -----------------------------------------------------
  335. {trace}
  336. """.format( trace=sys.exc_info()[:2])))
  337. err.flush()
  338. self.json_url_passed = False
  339. out.write("VALIDATING JSON ... ")
  340. if self.json_url_passed:
  341. out.write("PASS\n\n")
  342. else:
  343. out.write("FAIL\n\n")
  344. out.flush
  345. # DB
  346. if self.runTests[self.DB]:
  347. out.write( "VERIFYING DB (" + self.db_url + ") ...\n" )
  348. out.flush()
  349. try:
  350. url = self.benchmarker.generate_url(self.db_url, self.port)
  351. output = self.__curl_url(url, self.DB, out, err)
  352. if self.validateDb(output, out, err):
  353. self.db_url_passed = True
  354. else:
  355. self.db_url_passed = False
  356. if self.validateDbStrict(output, out, err):
  357. self.db_url_warn = False
  358. else:
  359. self.db_url_warn = True
  360. except (AttributeError, subprocess.CalledProcessError):
  361. err.write(textwrap.dedent("""
  362. -----------------------------------------------------
  363. Error: verify_urls raised exception (DB)
  364. -----------------------------------------------------
  365. {trace}
  366. """.format( trace=sys.exc_info()[:2])))
  367. err.flush()
  368. self.db_url_passed = False
  369. out.write("VALIDATING DB ... ")
  370. if self.db_url_passed:
  371. out.write("PASS\n\n")
  372. else:
  373. out.write("FAIL\n\n")
  374. out.flush
  375. # Query
  376. if self.runTests[self.QUERY]:
  377. out.write( "VERIFYING QUERY (" + self.query_url + "2, " +
  378. self.query_url + "0," + self.query_url + "foo, " +
  379. self.query_url + "501 ) ...\n")
  380. out.flush()
  381. try:
  382. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  383. output = self.__curl_url(url, self.QUERY, out, err)
  384. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  385. output2 = self.__curl_url(url2, self.QUERY, out, err)
  386. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  387. output3 = self.__curl_url(url3, self.QUERY, out, err)
  388. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  389. output4 = self.__curl_url(url4, self.QUERY, out, err)
  390. if self.validateQuery(output, out, err):
  391. self.query_url_passed = True
  392. else:
  393. self.query_url_passed = False
  394. if (not self.validateQueryOneOrLess(output2, out, err) or
  395. not self.validateQueryOneOrLess(output3, out, err) or
  396. not self.validateQueryFiveHundredOrMore(output4, out, err)):
  397. self.query_url_warn = True
  398. else:
  399. self.query_url_warn = False
  400. except (AttributeError, subprocess.CalledProcessError):
  401. err.write(textwrap.dedent("""
  402. -----------------------------------------------------
  403. Error: verify_urls raised exception (QUERY)
  404. -----------------------------------------------------
  405. {trace}
  406. """.format( trace=sys.exc_info()[:2])))
  407. err.flush()
  408. self.query_url_passed = False
  409. out.write("VALIDATING QUERY ... ")
  410. if self.query_url_passed:
  411. out.write("PASS\n\n")
  412. else:
  413. out.write("FAIL\n\n")
  414. out.flush
  415. # Fortune
  416. if self.runTests[self.FORTUNE]:
  417. out.write( "VERIFYING FORTUNE (" + self.fortune_url + ") ...\n" )
  418. out.flush()
  419. try:
  420. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  421. output = self.__curl_url(url, self.FORTUNE, out, err)
  422. if self.validateFortune(output, out, err):
  423. self.fortune_url_passed = True
  424. else:
  425. self.fortune_url_passed = False
  426. except (AttributeError, subprocess.CalledProcessError):
  427. err.write(textwrap.dedent("""
  428. -----------------------------------------------------
  429. Error: verify_urls raised exception (FORTUNE)
  430. -----------------------------------------------------
  431. {trace}
  432. """.format( trace=sys.exc_info()[:2])))
  433. err.flush()
  434. self.fortune_url_passed = False
  435. out.write("VALIDATING FORTUNE ... ")
  436. if self.fortune_url_passed:
  437. out.write("PASS\n\n")
  438. else:
  439. out.write("FAIL\n\n")
  440. out.flush
  441. # Update
  442. if self.runTests[self.UPDATE]:
  443. out.write( "VERIFYING UPDATE (" + self.update_url + "2) ...\n" )
  444. out.flush()
  445. try:
  446. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  447. output = self.__curl_url(url, self.UPDATE, out, err)
  448. if self.validateUpdate(output, out, err):
  449. self.update_url_passed = True
  450. else:
  451. self.update_url_passed = False
  452. except (AttributeError, subprocess.CalledProcessError):
  453. err.write(textwrap.dedent("""
  454. -----------------------------------------------------
  455. Error: verify_urls raised exception (UPDATE)
  456. -----------------------------------------------------
  457. {trace}
  458. """.format( trace=sys.exc_info()[:2])))
  459. err.flush()
  460. self.update_url_passed = False
  461. out.write("VALIDATING UPDATE ... ")
  462. if self.update_url_passed:
  463. out.write("PASS\n\n")
  464. else:
  465. out.write("FAIL\n\n")
  466. out.flush
  467. # plaintext
  468. if self.runTests[self.PLAINTEXT]:
  469. out.write( "VERIFYING PLAINTEXT (" + self.plaintext_url + ") ...\n" )
  470. out.flush()
  471. try:
  472. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  473. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  474. if self.validatePlaintext(output, out, err):
  475. self.plaintext_url_passed = True
  476. else:
  477. self.plaintext_url_passed = False
  478. except (AttributeError, subprocess.CalledProcessError):
  479. err.write(textwrap.dedent("""
  480. -----------------------------------------------------
  481. Error: verify_urls raised exception (PLAINTEXT)
  482. -----------------------------------------------------
  483. {trace}
  484. """.format( trace=sys.exc_info()[:2])))
  485. err.flush()
  486. self.plaintext_url_passed = False
  487. out.write("VALIDATING PLAINTEXT ... ")
  488. if self.plaintext_url_passed:
  489. out.write("PASS\n\n")
  490. else:
  491. out.write("FAIL\n\n")
  492. out.flush
  493. ############################################################
  494. # End verify_urls
  495. ############################################################
  496. ############################################################
  497. # contains_type(type)
  498. # true if this test contains an implementation of the given
  499. # test type (json, db, etc.)
  500. ############################################################
  501. def contains_type(self, type):
  502. try:
  503. if type == self.JSON and self.json_url != None:
  504. return True
  505. if type == self.DB and self.db_url != None:
  506. return True
  507. if type == self.QUERY and self.query_url != None:
  508. return True
  509. if type == self.FORTUNE and self.fortune_url != None:
  510. return True
  511. if type == self.UPDATE and self.update_url != None:
  512. return True
  513. if type == self.PLAINTEXT and self.plaintext_url != None:
  514. return True
  515. except AttributeError:
  516. pass
  517. return False
  518. ############################################################
  519. # End stop
  520. ############################################################
  521. ############################################################
  522. # benchmark
  523. # Runs the benchmark for each type of test that it implements
  524. # JSON/DB/Query.
  525. ############################################################
  526. def benchmark(self, out, err):
  527. # JSON
  528. if self.runTests[self.JSON]:
  529. try:
  530. out.write("BENCHMARKING JSON ... ")
  531. out.flush()
  532. results = None
  533. output_file = self.benchmarker.output_file(self.name, self.JSON)
  534. if not os.path.exists(output_file):
  535. with open(output_file, 'w'):
  536. # Simply opening the file in write mode should create the empty file.
  537. pass
  538. if self.json_url_passed:
  539. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  540. self.__run_benchmark(remote_script, output_file, err)
  541. results = self.__parse_test(self.JSON)
  542. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  543. out.write( "Complete\n" )
  544. out.flush()
  545. except AttributeError:
  546. pass
  547. # DB
  548. if self.runTests[self.DB]:
  549. try:
  550. out.write("BENCHMARKING DB ... ")
  551. out.flush()
  552. results = None
  553. output_file = self.benchmarker.output_file(self.name, self.DB)
  554. warning_file = self.benchmarker.warning_file(self.name, self.DB)
  555. if not os.path.exists(output_file):
  556. with open(output_file, 'w'):
  557. # Simply opening the file in write mode should create the empty file.
  558. pass
  559. if self.db_url_warn:
  560. with open(warning_file, 'w'):
  561. pass
  562. if self.db_url_passed:
  563. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  564. self.__run_benchmark(remote_script, output_file, err)
  565. results = self.__parse_test(self.DB)
  566. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  567. out.write( "Complete\n" )
  568. except AttributeError:
  569. pass
  570. # Query
  571. if self.runTests[self.QUERY]:
  572. try:
  573. out.write("BENCHMARKING Query ... ")
  574. out.flush()
  575. results = None
  576. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  577. warning_file = self.benchmarker.warning_file(self.name, self.QUERY)
  578. if not os.path.exists(output_file):
  579. with open(output_file, 'w'):
  580. # Simply opening the file in write mode should create the empty file.
  581. pass
  582. if self.query_url_warn:
  583. with open(warning_file, 'w'):
  584. pass
  585. if self.query_url_passed:
  586. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  587. self.__run_benchmark(remote_script, output_file, err)
  588. results = self.__parse_test(self.QUERY)
  589. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  590. out.write( "Complete\n" )
  591. out.flush()
  592. except AttributeError:
  593. pass
  594. # fortune
  595. if self.runTests[self.FORTUNE]:
  596. try:
  597. out.write("BENCHMARKING Fortune ... ")
  598. out.flush()
  599. results = None
  600. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  601. if not os.path.exists(output_file):
  602. with open(output_file, 'w'):
  603. # Simply opening the file in write mode should create the empty file.
  604. pass
  605. if self.fortune_url_passed:
  606. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  607. self.__run_benchmark(remote_script, output_file, err)
  608. results = self.__parse_test(self.FORTUNE)
  609. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  610. out.write( "Complete\n" )
  611. out.flush()
  612. except AttributeError:
  613. pass
  614. # update
  615. if self.runTests[self.UPDATE]:
  616. try:
  617. out.write("BENCHMARKING Update ... ")
  618. out.flush()
  619. results = None
  620. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  621. if not os.path.exists(output_file):
  622. with open(output_file, 'w'):
  623. # Simply opening the file in write mode should create the empty file.
  624. pass
  625. if self.update_url_passed:
  626. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  627. self.__run_benchmark(remote_script, output_file, err)
  628. results = self.__parse_test(self.UPDATE)
  629. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  630. out.write( "Complete\n" )
  631. out.flush()
  632. except AttributeError:
  633. pass
  634. # plaintext
  635. if self.runTests[self.PLAINTEXT]:
  636. try:
  637. out.write("BENCHMARKING Plaintext ... ")
  638. out.flush()
  639. results = None
  640. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  641. if not os.path.exists(output_file):
  642. with open(output_file, 'w'):
  643. # Simply opening the file in write mode should create the empty file.
  644. pass
  645. if self.plaintext_url_passed:
  646. 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")
  647. self.__run_benchmark(remote_script, output_file, err)
  648. results = self.__parse_test(self.PLAINTEXT)
  649. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  650. out.write( "Complete\n" )
  651. out.flush()
  652. except AttributeError:
  653. traceback.print_exc()
  654. pass
  655. ############################################################
  656. # End benchmark
  657. ############################################################
  658. ############################################################
  659. # parse_all
  660. # Method meant to be run for a given timestamp
  661. ############################################################
  662. def parse_all(self):
  663. # JSON
  664. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  665. results = self.__parse_test(self.JSON)
  666. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  667. # DB
  668. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  669. results = self.__parse_test(self.DB)
  670. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  671. # Query
  672. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  673. results = self.__parse_test(self.QUERY)
  674. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  675. # Fortune
  676. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  677. results = self.__parse_test(self.FORTUNE)
  678. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  679. # Update
  680. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  681. results = self.__parse_test(self.UPDATE)
  682. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  683. # Plaintext
  684. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  685. results = self.__parse_test(self.PLAINTEXT)
  686. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  687. ############################################################
  688. # End parse_all
  689. ############################################################
  690. ############################################################
  691. # __parse_test(test_type)
  692. ############################################################
  693. def __parse_test(self, test_type):
  694. try:
  695. results = dict()
  696. results['results'] = []
  697. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  698. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  699. is_warmup = True
  700. rawData = None
  701. for line in raw_data:
  702. if "Queries:" in line or "Concurrency:" in line:
  703. is_warmup = False
  704. rawData = None
  705. continue
  706. if "Warmup" in line or "Primer" in line:
  707. is_warmup = True
  708. continue
  709. if not is_warmup:
  710. if rawData == None:
  711. rawData = dict()
  712. results['results'].append(rawData)
  713. #if "Requests/sec:" in line:
  714. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  715. # rawData['reportedResults'] = m.group(1)
  716. # search for weighttp data such as succeeded and failed.
  717. if "Latency" in line:
  718. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  719. if len(m) == 4:
  720. rawData['latencyAvg'] = m[0]
  721. rawData['latencyStdev'] = m[1]
  722. rawData['latencyMax'] = m[2]
  723. # rawData['latencyStdevPercent'] = m[3]
  724. #if "Req/Sec" in line:
  725. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  726. # if len(m) == 4:
  727. # rawData['requestsAvg'] = m[0]
  728. # rawData['requestsStdev'] = m[1]
  729. # rawData['requestsMax'] = m[2]
  730. # rawData['requestsStdevPercent'] = m[3]
  731. #if "requests in" in line:
  732. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  733. # if m != None:
  734. # # parse out the raw time, which may be in minutes or seconds
  735. # raw_time = m.group(1)
  736. # if "ms" in raw_time:
  737. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  738. # elif "s" in raw_time:
  739. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  740. # elif "m" in raw_time:
  741. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  742. # elif "h" in raw_time:
  743. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  744. if "requests in" in line:
  745. m = re.search("([0-9]+) requests in", line)
  746. if m != None:
  747. rawData['totalRequests'] = int(m.group(1))
  748. if "Socket errors" in line:
  749. if "connect" in line:
  750. m = re.search("connect ([0-9]+)", line)
  751. rawData['connect'] = int(m.group(1))
  752. if "read" in line:
  753. m = re.search("read ([0-9]+)", line)
  754. rawData['read'] = int(m.group(1))
  755. if "write" in line:
  756. m = re.search("write ([0-9]+)", line)
  757. rawData['write'] = int(m.group(1))
  758. if "timeout" in line:
  759. m = re.search("timeout ([0-9]+)", line)
  760. rawData['timeout'] = int(m.group(1))
  761. if "Non-2xx" in line:
  762. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  763. if m != None:
  764. rawData['5xx'] = int(m.group(1))
  765. return results
  766. except IOError:
  767. return None
  768. ############################################################
  769. # End benchmark
  770. ############################################################
  771. ##########################################################################################
  772. # Private Methods
  773. ##########################################################################################
  774. ############################################################
  775. # __run_benchmark(script, output_file)
  776. # Runs a single benchmark using the script which is a bash
  777. # template that uses weighttp to run the test. All the results
  778. # outputed to the output_file.
  779. ############################################################
  780. def __run_benchmark(self, script, output_file, err):
  781. with open(output_file, 'w') as raw_file:
  782. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  783. p.communicate(script)
  784. err.flush()
  785. ############################################################
  786. # End __run_benchmark
  787. ############################################################
  788. ############################################################
  789. # __generate_concurrency_script(url, port)
  790. # Generates the string containing the bash script that will
  791. # be run on the client to benchmark a single test. This
  792. # specifically works for the variable concurrency tests (JSON
  793. # and DB)
  794. ############################################################
  795. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  796. if len(intervals) == 0:
  797. intervals = self.benchmarker.concurrency_levels
  798. headers = self.__get_request_headers(accept_header)
  799. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  800. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  801. interval=" ".join("{}".format(item) for item in intervals),
  802. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  803. pipeline=pipeline)
  804. ############################################################
  805. # End __generate_concurrency_script
  806. ############################################################
  807. ############################################################
  808. # __generate_query_script(url, port)
  809. # Generates the string containing the bash script that will
  810. # be run on the client to benchmark a single test. This
  811. # specifically works for the variable query tests (Query)
  812. ############################################################
  813. def __generate_query_script(self, url, port, accept_header):
  814. headers = self.__get_request_headers(accept_header)
  815. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  816. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  817. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  818. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  819. ############################################################
  820. # End __generate_query_script
  821. ############################################################
  822. ############################################################
  823. # __get_request_headers(accept_header)
  824. # Generates the complete HTTP header string
  825. ############################################################
  826. def __get_request_headers(self, accept_header):
  827. return self.headers_template.format(accept=accept_header)
  828. ############################################################
  829. # End __format_request_headers
  830. ############################################################
  831. ############################################################
  832. # __curl_url
  833. # Dump HTTP response and headers. Throw exception if there
  834. # is an HTTP error.
  835. ############################################################
  836. def __curl_url(self, url, testType, out, err):
  837. # Use -i to output response with headers.
  838. # Don't use -f so that the HTTP response code is ignored.
  839. # Use --stderr - to redirect stderr to stdout so we get
  840. # error output for sure in stdout.
  841. # Use -sS to hide progress bar, but show errors.
  842. subprocess.check_call(["curl", "-i", "-sS", url], stderr=err, stdout=out)
  843. # HTTP output may not end in a newline, so add that here.
  844. out.write( "\n\n" )
  845. out.flush()
  846. err.flush()
  847. # We need to get the respond body from the curl and return it.
  848. p = subprocess.Popen(["curl", "-s", url], stdout=subprocess.PIPE)
  849. output = p.communicate()
  850. # In the curl invocation above we could not use -f because
  851. # then the HTTP response would not be output, so use -f in
  852. # an additional invocation so that if there is an HTTP error,
  853. # subprocess.CalledProcessError will be thrown. Note that this
  854. # uses check_output() instead of check_call() so that we can
  855. # ignore the HTTP response because we already output that in
  856. # the first curl invocation.
  857. #subprocess.check_output(["curl", "-fsS", url], stderr=err)
  858. #err.flush()
  859. if output:
  860. # We have the response body - return it
  861. return output[0]
  862. ##############################################################
  863. # End __curl_url
  864. ##############################################################
  865. ##########################################################################################
  866. # Constructor
  867. ##########################################################################################
  868. def __init__(self, name, directory, benchmarker, runTests, args):
  869. self.name = name
  870. self.directory = directory
  871. self.benchmarker = benchmarker
  872. self.runTests = runTests
  873. self.__dict__.update(args)
  874. # ensure directory has __init__.py file so that we can use it as a Python package
  875. if not os.path.exists(os.path.join(directory, "__init__.py")):
  876. open(os.path.join(directory, "__init__.py"), 'w').close()
  877. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  878. ############################################################
  879. # End __init__
  880. ############################################################
  881. ############################################################
  882. # End FrameworkTest
  883. ############################################################
  884. ##########################################################################################
  885. # Static methods
  886. ##########################################################################################
  887. ##############################################################
  888. # parse_config(config, directory, benchmarker)
  889. # parses a config file and returns a list of FrameworkTest
  890. # objects based on that config file.
  891. ##############################################################
  892. def parse_config(config, directory, benchmarker):
  893. tests = []
  894. # The config object can specify multiple tests, we neep to loop
  895. # over them and parse them out
  896. for test in config['tests']:
  897. for key, value in test.iteritems():
  898. test_name = config['framework']
  899. runTests = dict()
  900. runTests["json"] = (benchmarker.type == "all" or benchmarker.type == "json") and value.get("json_url", False)
  901. runTests["db"] = (benchmarker.type == "all" or benchmarker.type == "db") and value.get("db_url", False)
  902. runTests["query"] = (benchmarker.type == "all" or benchmarker.type == "query") and value.get("query_url", False)
  903. runTests["fortune"] = (benchmarker.type == "all" or benchmarker.type == "fortune") and value.get("fortune_url", False)
  904. runTests["update"] = (benchmarker.type == "all" or benchmarker.type == "update") and value.get("update_url", False)
  905. runTests["plaintext"] = (benchmarker.type == "all" or benchmarker.type == "plaintext") and value.get("plaintext_url", False)
  906. # if the test uses the 'defualt' keywork, then we don't
  907. # append anything to it's name. All configs should only have 1 default
  908. if key != 'default':
  909. # we need to use the key in the test_name
  910. test_name = test_name + "-" + key
  911. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, value))
  912. return tests
  913. ##############################################################
  914. # End parse_config
  915. ##############################################################