framework_test.py 38 KB

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