framework_test.py 32 KB

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