framework_test.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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(textwrap.dedent("""
  322. -----------------------------------------------------
  323. VERIFYING JSON ({url})
  324. -----------------------------------------------------
  325. """.format(url = self.json_url)))
  326. out.flush()
  327. try:
  328. url = self.benchmarker.generate_url(self.json_url, self.port)
  329. output = self.__curl_url(url, self.JSON, out, err)
  330. if self.validateJson(output, out, err):
  331. self.json_url_passed = True
  332. else:
  333. self.json_url_passed = False
  334. except (AttributeError, subprocess.CalledProcessError):
  335. err.write(textwrap.dedent("""
  336. -----------------------------------------------------
  337. Error: verify_urls raised exception (JSON)
  338. -----------------------------------------------------
  339. {trace}
  340. """.format( trace=sys.exc_info()[:2])))
  341. err.flush()
  342. self.json_url_passed = False
  343. out.write("VALIDATING JSON ... ")
  344. if self.json_url_passed:
  345. out.write("PASS\n\n")
  346. else:
  347. out.write("FAIL\n\n")
  348. out.flush
  349. # DB
  350. if self.runTests[self.DB]:
  351. out.write(textwrap.dedent("""
  352. -----------------------------------------------------
  353. VERIFYING DB ({url})
  354. -----------------------------------------------------
  355. """.format(url = self.db_url)))
  356. out.flush()
  357. try:
  358. url = self.benchmarker.generate_url(self.db_url, self.port)
  359. output = self.__curl_url(url, self.DB, out, err)
  360. if self.validateDb(output, out, err):
  361. self.db_url_passed = True
  362. else:
  363. self.db_url_passed = False
  364. if self.validateDbStrict(output, out, err):
  365. self.db_url_warn = False
  366. else:
  367. self.db_url_warn = True
  368. except (AttributeError, subprocess.CalledProcessError):
  369. err.write(textwrap.dedent("""
  370. -----------------------------------------------------
  371. Error: verify_urls raised exception (DB)
  372. -----------------------------------------------------
  373. {trace}
  374. """.format( trace=sys.exc_info()[:2])))
  375. err.flush()
  376. self.db_url_passed = False
  377. out.write("VALIDATING DB ... ")
  378. if self.db_url_passed:
  379. out.write("PASS\n\n")
  380. else:
  381. out.write("FAIL\n\n")
  382. out.flush
  383. # Query
  384. if self.runTests[self.QUERY]:
  385. out.write(textwrap.dedent("""
  386. -----------------------------------------------------
  387. VERIFYING QUERY ({url})
  388. -----------------------------------------------------
  389. """.format(url=self.query_url+"2")))
  390. out.flush()
  391. try:
  392. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  393. output = self.__curl_url(url, self.QUERY, out, err)
  394. if self.validateQuery(output, out, err):
  395. self.query_url_passed = True
  396. out.write(self.query_url + "2 - PASS\n\n")
  397. else:
  398. self.query_url_passed = False
  399. out.write(self.query_url + "2 - ERROR\n\n")
  400. out.write("-----------------------------------------------------\n\n")
  401. out.flush()
  402. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  403. output2 = self.__curl_url(url2, self.QUERY, out, err)
  404. if not self.validateQueryOneOrLess(output2, out, err):
  405. self.query_url_warn = True
  406. out.write(self.query_url + "0 - WARNING\n\n")
  407. else:
  408. out.write(self.query_url + "0 - PASS\n\n")
  409. out.write("-----------------------------------------------------\n\n")
  410. out.flush()
  411. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  412. output3 = self.__curl_url(url3, self.QUERY, out, err)
  413. if not self.validateQueryOneOrLess(output3, out, err):
  414. self.query_url_warn = True
  415. out.write(self.query_url + "foo - WARNING\n\n")
  416. else:
  417. out.write(self.query_url + "foo - PASS\n\n")
  418. out.write("-----------------------------------------------------\n\n")
  419. out.flush()
  420. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  421. output4 = self.__curl_url(url4, self.QUERY, out, err)
  422. if not self.validateQueryFiveHundredOrMore(output4, out, err):
  423. self.query_url_warn = True
  424. out.write(self.query_url + "501 - WARNING\n\n")
  425. else:
  426. self.query_url_warn = False
  427. out.write(self.query_url + "501 - PASS\n\n")
  428. out.write("-----------------------------------------------------\n\n")
  429. out.flush()
  430. except (AttributeError, subprocess.CalledProcessError):
  431. err.write(textwrap.dedent("""
  432. -----------------------------------------------------
  433. Error: verify_urls raised exception (QUERY)
  434. -----------------------------------------------------
  435. {trace}
  436. """.format( trace=sys.exc_info()[:2])))
  437. err.flush()
  438. self.query_url_passed = False
  439. out.write("VALIDATING QUERY ... ")
  440. if self.query_url_passed:
  441. out.write("PASS")
  442. if self.query_url_warn:
  443. out.write(" (with warnings)")
  444. out.write("\n\n")
  445. else:
  446. out.write("FAIL\n\n")
  447. out.flush
  448. # Fortune
  449. if self.runTests[self.FORTUNE]:
  450. out.write(textwrap.dedent("""
  451. -----------------------------------------------------
  452. VERIFYING FORTUNE ({url})
  453. -----------------------------------------------------
  454. """.format(url = self.fortune_url)))
  455. out.flush()
  456. try:
  457. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  458. output = self.__curl_url(url, self.FORTUNE, out, err)
  459. if self.validateFortune(output, out, err):
  460. self.fortune_url_passed = True
  461. else:
  462. self.fortune_url_passed = False
  463. except (AttributeError, subprocess.CalledProcessError):
  464. err.write(textwrap.dedent("""
  465. -----------------------------------------------------
  466. Error: verify_urls raised exception (FORTUNE)
  467. -----------------------------------------------------
  468. {trace}
  469. """.format( trace=sys.exc_info()[:2])))
  470. err.flush()
  471. self.fortune_url_passed = False
  472. out.write("VALIDATING FORTUNE ... ")
  473. if self.fortune_url_passed:
  474. out.write("PASS\n\n")
  475. else:
  476. out.write("FAIL\n\n")
  477. out.flush
  478. # Update
  479. if self.runTests[self.UPDATE]:
  480. out.write(textwrap.dedent("""
  481. -----------------------------------------------------
  482. VERIFYING UPDATE ({url})
  483. -----------------------------------------------------
  484. """.format(url = self.update_url)))
  485. out.flush()
  486. try:
  487. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  488. output = self.__curl_url(url, self.UPDATE, out, err)
  489. if self.validateUpdate(output, out, err):
  490. self.update_url_passed = True
  491. else:
  492. self.update_url_passed = False
  493. except (AttributeError, subprocess.CalledProcessError):
  494. err.write(textwrap.dedent("""
  495. -----------------------------------------------------
  496. Error: verify_urls raised exception (UPDATE)
  497. -----------------------------------------------------
  498. {trace}
  499. """.format( trace=sys.exc_info()[:2])))
  500. err.flush()
  501. self.update_url_passed = False
  502. out.write("VALIDATING UPDATE ... ")
  503. if self.update_url_passed:
  504. out.write("PASS\n\n")
  505. else:
  506. out.write("FAIL\n\n")
  507. out.flush
  508. # plaintext
  509. if self.runTests[self.PLAINTEXT]:
  510. out.write(textwrap.dedent("""
  511. -----------------------------------------------------
  512. VERIFYING PLAINTEXT ({url})
  513. -----------------------------------------------------
  514. """.format(url = self.plaintext_url)))
  515. out.flush()
  516. try:
  517. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  518. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  519. if self.validatePlaintext(output, out, err):
  520. self.plaintext_url_passed = True
  521. else:
  522. self.plaintext_url_passed = False
  523. except (AttributeError, subprocess.CalledProcessError):
  524. err.write(textwrap.dedent("""
  525. -----------------------------------------------------
  526. Error: verify_urls raised exception (PLAINTEXT)
  527. -----------------------------------------------------
  528. {trace}
  529. """.format( trace=sys.exc_info()[:2])))
  530. err.flush()
  531. self.plaintext_url_passed = False
  532. out.write("VALIDATING PLAINTEXT ... ")
  533. if self.plaintext_url_passed:
  534. out.write("PASS")
  535. else:
  536. out.write("FAIL\n\n")
  537. out.flush
  538. ############################################################
  539. # End verify_urls
  540. ############################################################
  541. ############################################################
  542. # contains_type(type)
  543. # true if this test contains an implementation of the given
  544. # test type (json, db, etc.)
  545. ############################################################
  546. def contains_type(self, type):
  547. try:
  548. if type == self.JSON and self.json_url != None:
  549. return True
  550. if type == self.DB and self.db_url != None:
  551. return True
  552. if type == self.QUERY and self.query_url != None:
  553. return True
  554. if type == self.FORTUNE and self.fortune_url != None:
  555. return True
  556. if type == self.UPDATE and self.update_url != None:
  557. return True
  558. if type == self.PLAINTEXT and self.plaintext_url != None:
  559. return True
  560. except AttributeError:
  561. pass
  562. return False
  563. ############################################################
  564. # End stop
  565. ############################################################
  566. ############################################################
  567. # benchmark
  568. # Runs the benchmark for each type of test that it implements
  569. # JSON/DB/Query.
  570. ############################################################
  571. def benchmark(self, out, err):
  572. # JSON
  573. if self.runTests[self.JSON]:
  574. try:
  575. out.write("BENCHMARKING JSON ... ")
  576. out.flush()
  577. results = None
  578. output_file = self.benchmarker.output_file(self.name, self.JSON)
  579. if not os.path.exists(output_file):
  580. with open(output_file, 'w'):
  581. # Simply opening the file in write mode should create the empty file.
  582. pass
  583. if self.json_url_passed:
  584. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  585. self.__run_benchmark(remote_script, output_file, err)
  586. results = self.__parse_test(self.JSON)
  587. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  588. out.write( "Complete\n" )
  589. out.flush()
  590. except AttributeError:
  591. pass
  592. # DB
  593. if self.runTests[self.DB]:
  594. try:
  595. out.write("BENCHMARKING DB ... ")
  596. out.flush()
  597. results = None
  598. output_file = self.benchmarker.output_file(self.name, self.DB)
  599. warning_file = self.benchmarker.warning_file(self.name, self.DB)
  600. if not os.path.exists(output_file):
  601. with open(output_file, 'w'):
  602. # Simply opening the file in write mode should create the empty file.
  603. pass
  604. if self.db_url_warn:
  605. with open(warning_file, 'w'):
  606. pass
  607. if self.db_url_passed:
  608. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  609. self.__run_benchmark(remote_script, output_file, err)
  610. results = self.__parse_test(self.DB)
  611. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  612. out.write( "Complete\n" )
  613. except AttributeError:
  614. pass
  615. # Query
  616. if self.runTests[self.QUERY]:
  617. try:
  618. out.write("BENCHMARKING Query ... ")
  619. out.flush()
  620. results = None
  621. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  622. warning_file = self.benchmarker.warning_file(self.name, self.QUERY)
  623. if not os.path.exists(output_file):
  624. with open(output_file, 'w'):
  625. # Simply opening the file in write mode should create the empty file.
  626. pass
  627. if self.query_url_warn:
  628. with open(warning_file, 'w'):
  629. pass
  630. if self.query_url_passed:
  631. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  632. self.__run_benchmark(remote_script, output_file, err)
  633. results = self.__parse_test(self.QUERY)
  634. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  635. out.write( "Complete\n" )
  636. out.flush()
  637. except AttributeError:
  638. pass
  639. # fortune
  640. if self.runTests[self.FORTUNE]:
  641. try:
  642. out.write("BENCHMARKING Fortune ... ")
  643. out.flush()
  644. results = None
  645. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  646. if not os.path.exists(output_file):
  647. with open(output_file, 'w'):
  648. # Simply opening the file in write mode should create the empty file.
  649. pass
  650. if self.fortune_url_passed:
  651. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  652. self.__run_benchmark(remote_script, output_file, err)
  653. results = self.__parse_test(self.FORTUNE)
  654. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  655. out.write( "Complete\n" )
  656. out.flush()
  657. except AttributeError:
  658. pass
  659. # update
  660. if self.runTests[self.UPDATE]:
  661. try:
  662. out.write("BENCHMARKING Update ... ")
  663. out.flush()
  664. results = None
  665. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  666. if not os.path.exists(output_file):
  667. with open(output_file, 'w'):
  668. # Simply opening the file in write mode should create the empty file.
  669. pass
  670. if self.update_url_passed:
  671. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  672. self.__run_benchmark(remote_script, output_file, err)
  673. results = self.__parse_test(self.UPDATE)
  674. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  675. out.write( "Complete\n" )
  676. out.flush()
  677. except AttributeError:
  678. pass
  679. # plaintext
  680. if self.runTests[self.PLAINTEXT]:
  681. try:
  682. out.write("BENCHMARKING Plaintext ... ")
  683. out.flush()
  684. results = None
  685. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  686. if not os.path.exists(output_file):
  687. with open(output_file, 'w'):
  688. # Simply opening the file in write mode should create the empty file.
  689. pass
  690. if self.plaintext_url_passed:
  691. 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")
  692. self.__run_benchmark(remote_script, output_file, err)
  693. results = self.__parse_test(self.PLAINTEXT)
  694. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  695. out.write( "Complete\n" )
  696. out.flush()
  697. except AttributeError:
  698. traceback.print_exc()
  699. pass
  700. ############################################################
  701. # End benchmark
  702. ############################################################
  703. ############################################################
  704. # parse_all
  705. # Method meant to be run for a given timestamp
  706. ############################################################
  707. def parse_all(self):
  708. # JSON
  709. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  710. results = self.__parse_test(self.JSON)
  711. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  712. # DB
  713. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  714. results = self.__parse_test(self.DB)
  715. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  716. # Query
  717. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  718. results = self.__parse_test(self.QUERY)
  719. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  720. # Fortune
  721. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  722. results = self.__parse_test(self.FORTUNE)
  723. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  724. # Update
  725. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  726. results = self.__parse_test(self.UPDATE)
  727. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  728. # Plaintext
  729. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  730. results = self.__parse_test(self.PLAINTEXT)
  731. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  732. ############################################################
  733. # End parse_all
  734. ############################################################
  735. ############################################################
  736. # __parse_test(test_type)
  737. ############################################################
  738. def __parse_test(self, test_type):
  739. try:
  740. results = dict()
  741. results['results'] = []
  742. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  743. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  744. is_warmup = True
  745. rawData = None
  746. for line in raw_data:
  747. if "Queries:" in line or "Concurrency:" in line:
  748. is_warmup = False
  749. rawData = None
  750. continue
  751. if "Warmup" in line or "Primer" in line:
  752. is_warmup = True
  753. continue
  754. if not is_warmup:
  755. if rawData == None:
  756. rawData = dict()
  757. results['results'].append(rawData)
  758. #if "Requests/sec:" in line:
  759. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  760. # rawData['reportedResults'] = m.group(1)
  761. # search for weighttp data such as succeeded and failed.
  762. if "Latency" in line:
  763. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  764. if len(m) == 4:
  765. rawData['latencyAvg'] = m[0]
  766. rawData['latencyStdev'] = m[1]
  767. rawData['latencyMax'] = m[2]
  768. # rawData['latencyStdevPercent'] = m[3]
  769. #if "Req/Sec" in line:
  770. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  771. # if len(m) == 4:
  772. # rawData['requestsAvg'] = m[0]
  773. # rawData['requestsStdev'] = m[1]
  774. # rawData['requestsMax'] = m[2]
  775. # rawData['requestsStdevPercent'] = m[3]
  776. #if "requests in" in line:
  777. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  778. # if m != None:
  779. # # parse out the raw time, which may be in minutes or seconds
  780. # raw_time = m.group(1)
  781. # if "ms" in raw_time:
  782. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  783. # elif "s" in raw_time:
  784. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  785. # elif "m" in raw_time:
  786. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  787. # elif "h" in raw_time:
  788. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  789. if "requests in" in line:
  790. m = re.search("([0-9]+) requests in", line)
  791. if m != None:
  792. rawData['totalRequests'] = int(m.group(1))
  793. if "Socket errors" in line:
  794. if "connect" in line:
  795. m = re.search("connect ([0-9]+)", line)
  796. rawData['connect'] = int(m.group(1))
  797. if "read" in line:
  798. m = re.search("read ([0-9]+)", line)
  799. rawData['read'] = int(m.group(1))
  800. if "write" in line:
  801. m = re.search("write ([0-9]+)", line)
  802. rawData['write'] = int(m.group(1))
  803. if "timeout" in line:
  804. m = re.search("timeout ([0-9]+)", line)
  805. rawData['timeout'] = int(m.group(1))
  806. if "Non-2xx" in line:
  807. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  808. if m != None:
  809. rawData['5xx'] = int(m.group(1))
  810. return results
  811. except IOError:
  812. return None
  813. ############################################################
  814. # End benchmark
  815. ############################################################
  816. ##########################################################################################
  817. # Private Methods
  818. ##########################################################################################
  819. ############################################################
  820. # __run_benchmark(script, output_file)
  821. # Runs a single benchmark using the script which is a bash
  822. # template that uses weighttp to run the test. All the results
  823. # outputed to the output_file.
  824. ############################################################
  825. def __run_benchmark(self, script, output_file, err):
  826. with open(output_file, 'w') as raw_file:
  827. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  828. p.communicate(script)
  829. err.flush()
  830. ############################################################
  831. # End __run_benchmark
  832. ############################################################
  833. ############################################################
  834. # __generate_concurrency_script(url, port)
  835. # Generates the string containing the bash script that will
  836. # be run on the client to benchmark a single test. This
  837. # specifically works for the variable concurrency tests (JSON
  838. # and DB)
  839. ############################################################
  840. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  841. if len(intervals) == 0:
  842. intervals = self.benchmarker.concurrency_levels
  843. headers = self.__get_request_headers(accept_header)
  844. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  845. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  846. interval=" ".join("{}".format(item) for item in intervals),
  847. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  848. pipeline=pipeline)
  849. ############################################################
  850. # End __generate_concurrency_script
  851. ############################################################
  852. ############################################################
  853. # __generate_query_script(url, port)
  854. # Generates the string containing the bash script that will
  855. # be run on the client to benchmark a single test. This
  856. # specifically works for the variable query tests (Query)
  857. ############################################################
  858. def __generate_query_script(self, url, port, accept_header):
  859. headers = self.__get_request_headers(accept_header)
  860. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  861. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  862. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  863. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  864. ############################################################
  865. # End __generate_query_script
  866. ############################################################
  867. ############################################################
  868. # __get_request_headers(accept_header)
  869. # Generates the complete HTTP header string
  870. ############################################################
  871. def __get_request_headers(self, accept_header):
  872. return self.headers_template.format(accept=accept_header)
  873. ############################################################
  874. # End __format_request_headers
  875. ############################################################
  876. ############################################################
  877. # __curl_url
  878. # Dump HTTP response and headers. Throw exception if there
  879. # is an HTTP error.
  880. ############################################################
  881. def __curl_url(self, url, testType, out, err):
  882. # Use -i to output response with headers.
  883. # Don't use -f so that the HTTP response code is ignored.
  884. # Use --stderr - to redirect stderr to stdout so we get
  885. # error output for sure in stdout.
  886. # Use -sS to hide progress bar, but show errors.
  887. subprocess.check_call(["curl", "-i", "-sS", url], stderr=err, stdout=out)
  888. # HTTP output may not end in a newline, so add that here.
  889. out.write( "\n\n" )
  890. out.flush()
  891. err.flush()
  892. # We need to get the respond body from the curl and return it.
  893. p = subprocess.Popen(["curl", "-s", url], stdout=subprocess.PIPE)
  894. output = p.communicate()
  895. if output:
  896. # We have the response body - return it
  897. return output[0]
  898. ##############################################################
  899. # End __curl_url
  900. ##############################################################
  901. ##########################################################################################
  902. # Constructor
  903. ##########################################################################################
  904. def __init__(self, name, directory, benchmarker, runTests, args):
  905. self.name = name
  906. self.directory = directory
  907. self.benchmarker = benchmarker
  908. self.runTests = runTests
  909. self.__dict__.update(args)
  910. # ensure directory has __init__.py file so that we can use it as a Python package
  911. if not os.path.exists(os.path.join(directory, "__init__.py")):
  912. open(os.path.join(directory, "__init__.py"), 'w').close()
  913. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  914. ############################################################
  915. # End __init__
  916. ############################################################
  917. ############################################################
  918. # End FrameworkTest
  919. ############################################################
  920. ##########################################################################################
  921. # Static methods
  922. ##########################################################################################
  923. ##############################################################
  924. # parse_config(config, directory, benchmarker)
  925. # parses a config file and returns a list of FrameworkTest
  926. # objects based on that config file.
  927. ##############################################################
  928. def parse_config(config, directory, benchmarker):
  929. tests = []
  930. # The config object can specify multiple tests, we neep to loop
  931. # over them and parse them out
  932. for test in config['tests']:
  933. for key, value in test.iteritems():
  934. test_name = config['framework']
  935. runTests = dict()
  936. runTests["json"] = (benchmarker.type == "all" or benchmarker.type == "json") and value.get("json_url", False)
  937. runTests["db"] = (benchmarker.type == "all" or benchmarker.type == "db") and value.get("db_url", False)
  938. runTests["query"] = (benchmarker.type == "all" or benchmarker.type == "query") and value.get("query_url", False)
  939. runTests["fortune"] = (benchmarker.type == "all" or benchmarker.type == "fortune") and value.get("fortune_url", False)
  940. runTests["update"] = (benchmarker.type == "all" or benchmarker.type == "update") and value.get("update_url", False)
  941. runTests["plaintext"] = (benchmarker.type == "all" or benchmarker.type == "plaintext") and value.get("plaintext_url", False)
  942. # if the test uses the 'defualt' keywork, then we don't
  943. # append anything to it's name. All configs should only have 1 default
  944. if key != 'default':
  945. # we need to use the key in the test_name
  946. test_name = test_name + "-" + key
  947. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, value))
  948. return tests
  949. ##############################################################
  950. # End parse_config
  951. ##############################################################