framework_test.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import importlib
  2. import os
  3. import subprocess
  4. import time
  5. import re
  6. import pprint
  7. import sys
  8. class FrameworkTest:
  9. ##########################################################################################
  10. # Class variables
  11. ##########################################################################################
  12. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  13. 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'"
  14. accept_json = "Accept: application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  15. accept_html = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  16. accept_plaintext = "Accept: text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  17. concurrency_template = """
  18. echo ""
  19. echo "---------------------------------------------------------"
  20. echo " Running Primer {name}"
  21. echo " {wrk} {headers} -d 60 -c 8 -t 8 \"http://{server_host}:{port}{url}\""
  22. echo "---------------------------------------------------------"
  23. echo ""
  24. {wrk} {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}"
  25. sleep 5
  26. echo ""
  27. echo "---------------------------------------------------------"
  28. echo " Running Warmup {name}"
  29. echo " {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  30. echo "---------------------------------------------------------"
  31. echo ""
  32. {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  33. sleep 5
  34. for c in {interval}
  35. do
  36. echo ""
  37. echo "---------------------------------------------------------"
  38. echo " Concurrency: $c for {name}"
  39. echo " {wrk} {headers} {pipeline} -d {duration} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  40. echo "---------------------------------------------------------"
  41. echo ""
  42. {wrk} {headers} {pipeline} -d {duration} -c "$c" -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  43. sleep 2
  44. done
  45. """
  46. query_template = """
  47. echo ""
  48. echo "---------------------------------------------------------"
  49. echo " Running Primer {name}"
  50. echo " wrk {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}2\""
  51. echo "---------------------------------------------------------"
  52. echo ""
  53. wrk {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}2"
  54. sleep 5
  55. echo ""
  56. echo "---------------------------------------------------------"
  57. echo " Running Warmup {name}"
  58. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  59. echo "---------------------------------------------------------"
  60. echo ""
  61. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  62. sleep 5
  63. for c in {interval}
  64. do
  65. echo ""
  66. echo "---------------------------------------------------------"
  67. echo " Queries: $c for {name}"
  68. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  69. echo "---------------------------------------------------------"
  70. echo ""
  71. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  72. sleep 2
  73. done
  74. """
  75. language = None
  76. platform = None
  77. webserver = None
  78. classification = None
  79. database = None
  80. approach = None
  81. orm = None
  82. framework = None
  83. os = None
  84. database_os = None
  85. display_name = None
  86. notes = None
  87. versus = None
  88. ##########################################################################################
  89. # Public Methods
  90. ##########################################################################################
  91. ############################################################
  92. # start(benchmarker)
  93. # Start the test using it's setup file
  94. ############################################################
  95. def start(self):
  96. return self.setup_module.start(self.benchmarker)
  97. ############################################################
  98. # End start
  99. ############################################################
  100. ############################################################
  101. # stop(benchmarker)
  102. # Stops the test using it's setup file
  103. ############################################################
  104. def stop(self):
  105. return self.setup_module.stop()
  106. ############################################################
  107. # End stop
  108. ############################################################
  109. ############################################################
  110. # verify_urls
  111. # Verifys each of the URLs for this test. THis will sinply
  112. # curl the URL and check for it's return status.
  113. # For each url, a flag will be set on this object for whether
  114. # or not it passed
  115. ############################################################
  116. def verify_urls(self):
  117. # JSON
  118. try:
  119. print "VERIFYING JSON (" + self.json_url + ") ..."
  120. url = self.benchmarker.generate_url(self.json_url, self.port)
  121. subprocess.check_call(["curl", "-f", url])
  122. print ""
  123. self.json_url_passed = True
  124. except (AttributeError, subprocess.CalledProcessError) as e:
  125. self.json_url_passed = False
  126. # DB
  127. try:
  128. print "VERIFYING DB (" + self.db_url + ") ..."
  129. url = self.benchmarker.generate_url(self.db_url, self.port)
  130. subprocess.check_call(["curl", "-f", url])
  131. print ""
  132. self.db_url_passed = True
  133. except (AttributeError, subprocess.CalledProcessError) as e:
  134. self.db_url_passed = False
  135. # Query
  136. try:
  137. print "VERIFYING Query (" + self.query_url + "2) ..."
  138. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  139. subprocess.check_call(["curl", "-f", url])
  140. print ""
  141. self.query_url_passed = True
  142. except (AttributeError, subprocess.CalledProcessError) as e:
  143. self.query_url_passed = False
  144. # Fortune
  145. try:
  146. print "VERIFYING Fortune (" + self.fortune_url + ") ..."
  147. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  148. subprocess.check_call(["curl", "-f", url])
  149. print ""
  150. self.fortune_url_passed = True
  151. except (AttributeError, subprocess.CalledProcessError) as e:
  152. self.fortune_url_passed = False
  153. # Update
  154. try:
  155. print "VERIFYING Update (" + self.update_url + "2) ..."
  156. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  157. subprocess.check_call(["curl", "-f", url])
  158. print ""
  159. self.update_url_passed = True
  160. except (AttributeError, subprocess.CalledProcessError) as e:
  161. self.update_url_passed = False
  162. # plaintext
  163. try:
  164. print "VERIFYING Plaintext (" + self.plaintext_url + ") ..."
  165. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  166. subprocess.check_call(["curl", "-f", url])
  167. print ""
  168. self.plaintext_url_passed = True
  169. except (AttributeError, subprocess.CalledProcessError) as e:
  170. self.plaintext_url_passed = False
  171. ############################################################
  172. # End verify_urls
  173. ############################################################
  174. ############################################################
  175. # contains_type(type)
  176. # true if this test contains an implementation of the given
  177. # test type (json, db, etc.)
  178. ############################################################
  179. def contains_type(self, type):
  180. try:
  181. if type == 'json' and self.json_url != None:
  182. return True
  183. if type == 'db' and self.db_url != None:
  184. return True
  185. if type == 'query' and self.query_url != None:
  186. return True
  187. if type == 'fortune' and self.fortune_url != None:
  188. return True
  189. if type == 'update' and self.update_url != None:
  190. return True
  191. if type == 'plaintext' and self.plaintext_url != None:
  192. return True
  193. except AttributeError:
  194. pass
  195. return False
  196. ############################################################
  197. # End stop
  198. ############################################################
  199. ############################################################
  200. # benchmark
  201. # Runs the benchmark for each type of test that it implements
  202. # JSON/DB/Query.
  203. ############################################################
  204. def benchmark(self):
  205. # JSON
  206. try:
  207. if self.json_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "json"):
  208. sys.stdout.write("BENCHMARKING JSON ... ")
  209. sys.stdout.flush()
  210. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  211. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'json'))
  212. results = self.__parse_test('json')
  213. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  214. print "Complete"
  215. except AttributeError:
  216. pass
  217. # DB
  218. try:
  219. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "db"):
  220. sys.stdout.write("BENCHMARKING DB ... ")
  221. sys.stdout.flush()
  222. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  223. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'db'))
  224. results = self.__parse_test('db')
  225. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  226. print "Complete"
  227. except AttributeError:
  228. pass
  229. # Query
  230. try:
  231. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "query"):
  232. sys.stdout.write("BENCHMARKING Query ... ")
  233. sys.stdout.flush()
  234. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  235. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'query'))
  236. results = self.__parse_test('query')
  237. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  238. print "Complete"
  239. except AttributeError:
  240. pass
  241. # fortune
  242. try:
  243. if self.fortune_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "fortune"):
  244. sys.stdout.write("BENCHMARKING Fortune ... ")
  245. sys.stdout.flush()
  246. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  247. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'fortune'))
  248. results = self.__parse_test('fortune')
  249. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  250. print "Complete"
  251. except AttributeError:
  252. pass
  253. # update
  254. try:
  255. if self.update_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "update"):
  256. sys.stdout.write("BENCHMARKING Update ... ")
  257. sys.stdout.flush()
  258. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  259. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'update'))
  260. results = self.__parse_test('update')
  261. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  262. print "Complete"
  263. except AttributeError:
  264. pass
  265. # plaintext
  266. try:
  267. if self.plaintext_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "plaintext"):
  268. sys.stdout.write("BENCHMARKING Plaintext ... ")
  269. sys.stdout.flush()
  270. 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")
  271. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'plaintext'))
  272. results = self.__parse_test('plaintext')
  273. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  274. print "Complete"
  275. except AttributeError:
  276. pass
  277. ############################################################
  278. # End benchmark
  279. ############################################################
  280. ############################################################
  281. # parse_all
  282. # Method meant to be run for a given timestamp
  283. ############################################################
  284. def parse_all(self):
  285. # JSON
  286. if os.path.exists(self.benchmarker.output_file(self.name, 'json')):
  287. results = self.__parse_test('json')
  288. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  289. # DB
  290. if os.path.exists(self.benchmarker.output_file(self.name, 'db')):
  291. results = self.__parse_test('db')
  292. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  293. # Query
  294. if os.path.exists(self.benchmarker.output_file(self.name, 'query')):
  295. results = self.__parse_test('query')
  296. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  297. # Fortune
  298. if os.path.exists(self.benchmarker.output_file(self.name, 'fortune')):
  299. results = self.__parse_test('fortune')
  300. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  301. # Update
  302. if os.path.exists(self.benchmarker.output_file(self.name, 'update')):
  303. results = self.__parse_test('update')
  304. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  305. # Plaintext
  306. if os.path.exists(self.benchmarker.output_file(self.name, 'plaintext')):
  307. results = self.__parse_test('plaintext')
  308. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  309. ############################################################
  310. # End parse_all
  311. ############################################################
  312. ############################################################
  313. # __parse_test(test_type)
  314. ############################################################
  315. def __parse_test(self, test_type):
  316. try:
  317. results = dict()
  318. results['results'] = []
  319. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  320. is_warmup = True
  321. rawData = None
  322. for line in raw_data:
  323. if "Queries:" in line or "Concurrency:" in line:
  324. is_warmup = False
  325. rawData = None
  326. continue
  327. if "Warmup" in line or "Primer" in line:
  328. is_warmup = True
  329. continue
  330. if not is_warmup:
  331. if rawData == None:
  332. rawData = dict()
  333. results['results'].append(rawData)
  334. #if "Requests/sec:" in line:
  335. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  336. # rawData['reportedResults'] = m.group(1)
  337. # search for weighttp data such as succeeded and failed.
  338. if "Latency" in line:
  339. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  340. if len(m) == 4:
  341. rawData['latencyAvg'] = m[0]
  342. rawData['latencyStdev'] = m[1]
  343. rawData['latencyMax'] = m[2]
  344. # rawData['latencyStdevPercent'] = m[3]
  345. #if "Req/Sec" in line:
  346. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  347. # if len(m) == 4:
  348. # rawData['requestsAvg'] = m[0]
  349. # rawData['requestsStdev'] = m[1]
  350. # rawData['requestsMax'] = m[2]
  351. # rawData['requestsStdevPercent'] = m[3]
  352. #if "requests in" in line:
  353. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  354. # if m != None:
  355. # # parse out the raw time, which may be in minutes or seconds
  356. # raw_time = m.group(1)
  357. # if "ms" in raw_time:
  358. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  359. # elif "s" in raw_time:
  360. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  361. # elif "m" in raw_time:
  362. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  363. # elif "h" in raw_time:
  364. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  365. if "requests in" in line:
  366. m = re.search("([0-9]+) requests in", line)
  367. if m != None:
  368. rawData['totalRequests'] = int(m.group(1))
  369. if "Socket errors" in line:
  370. if "connect" in line:
  371. m = re.search("connect ([0-9]+)", line)
  372. rawData['connect'] = int(m.group(1))
  373. if "read" in line:
  374. m = re.search("read ([0-9]+)", line)
  375. rawData['read'] = int(m.group(1))
  376. if "write" in line:
  377. m = re.search("write ([0-9]+)", line)
  378. rawData['write'] = int(m.group(1))
  379. if "timeout" in line:
  380. m = re.search("timeout ([0-9]+)", line)
  381. rawData['timeout'] = int(m.group(1))
  382. if "Non-2xx" in line:
  383. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  384. if m != None:
  385. rawData['5xx'] = int(m.group(1))
  386. return results
  387. except IOError:
  388. return None
  389. ############################################################
  390. # End benchmark
  391. ############################################################
  392. ##########################################################################################
  393. # Private Methods
  394. ##########################################################################################
  395. ############################################################
  396. # __run_benchmark(script, output_file)
  397. # Runs a single benchmark using the script which is a bash
  398. # template that uses weighttp to run the test. All the results
  399. # outputed to the output_file.
  400. ############################################################
  401. def __run_benchmark(self, script, output_file):
  402. with open(output_file, 'w') as raw_file:
  403. p = subprocess.Popen(self.benchmarker.ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=raw_file)
  404. p.communicate(script)
  405. ############################################################
  406. # End __run_benchmark
  407. ############################################################
  408. ############################################################
  409. # __generate_concurrency_script(url, port)
  410. # Generates the string containing the bash script that will
  411. # be run on the client to benchmark a single test. This
  412. # specifically works for the variable concurrency tests (JSON
  413. # and DB)
  414. ############################################################
  415. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  416. if len(intervals) == 0:
  417. intervals = self.benchmarker.concurrency_levels
  418. headers = self.__get_request_headers(accept_header)
  419. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  420. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  421. interval=" ".join("{}".format(item) for item in intervals),
  422. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  423. pipeline=pipeline)
  424. ############################################################
  425. # End __generate_concurrency_script
  426. ############################################################
  427. ############################################################
  428. # __generate_query_script(url, port)
  429. # Generates the string containing the bash script that will
  430. # be run on the client to benchmark a single test. This
  431. # specifically works for the variable query tests (Query)
  432. ############################################################
  433. def __generate_query_script(self, url, port, accept_header):
  434. headers = self.__get_request_headers(accept_header)
  435. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  436. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  437. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  438. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  439. ############################################################
  440. # End __generate_query_script
  441. ############################################################
  442. ############################################################
  443. # __get_request_headers(accept_header)
  444. # Generates the complete HTTP header string
  445. ############################################################
  446. def __get_request_headers(self, accept_header):
  447. return self.headers_template.format(accept=accept_header)
  448. ############################################################
  449. # End __format_request_headers
  450. ############################################################
  451. ##########################################################################################
  452. # Constructor
  453. ##########################################################################################
  454. def __init__(self, name, directory, benchmarker, args):
  455. self.name = name
  456. self.directory = directory
  457. self.benchmarker = benchmarker
  458. self.__dict__.update(args)
  459. # ensure diretory has __init__.py file so that we can use it as a Python package
  460. if not os.path.exists(os.path.join(directory, "__init__.py")):
  461. open(os.path.join(directory, "__init__.py"), 'w').close()
  462. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  463. ############################################################
  464. # End __init__
  465. ############################################################
  466. ############################################################
  467. # End FrameworkTest
  468. ############################################################
  469. ##########################################################################################
  470. # Static methods
  471. ##########################################################################################
  472. ##############################################################
  473. # parse_config(config, directory, benchmarker)
  474. # parses a config file and returns a list of FrameworkTest
  475. # objects based on that config file.
  476. ##############################################################
  477. def parse_config(config, directory, benchmarker):
  478. tests = []
  479. # The config object can specify multiple tests, we neep to loop
  480. # over them and parse them out
  481. for test in config['tests']:
  482. for key, value in test.iteritems():
  483. test_name = config['framework']
  484. # if the test uses the 'defualt' keywork, then we don't
  485. # append anything to it's name. All configs should only have 1 default
  486. if key != 'default':
  487. # we need to use the key in the test_name
  488. test_name = test_name + "-" + key
  489. tests.append(FrameworkTest(test_name, directory, benchmarker, value))
  490. return tests
  491. ##############################################################
  492. # End parse_config
  493. ##############################################################