framework_test.py 41 KB

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