framework_test.py 38 KB

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