framework_test.py 41 KB

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