framework_test.py 40 KB

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