framework_test.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. concurrency_template = """
  13. mysqladmin flush-hosts -uroot -psecret
  14. echo ""
  15. echo "---------------------------------------------------------"
  16. echo " Running Warmup {name}"
  17. echo " wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}"
  18. echo "---------------------------------------------------------"
  19. echo ""
  20. wrk -r 1000 -c 8 -t 8 http://{server_host}:{port}{url}
  21. sleep 5
  22. wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}
  23. for c in {interval}
  24. do
  25. echo ""
  26. echo "---------------------------------------------------------"
  27. echo " Concurrency: $c for {name}"
  28. echo " wrk -n {runs} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) http://{server_host}:{port}{url}"
  29. echo "---------------------------------------------------------"
  30. echo ""
  31. wrk -r {runs} -c "$c" -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  32. done
  33. """
  34. query_template = """
  35. mysqladmin flush-hosts -uroot -psecret
  36. echo ""
  37. echo "---------------------------------------------------------"
  38. echo " Running Warmup {name}"
  39. echo " wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}2"
  40. echo "---------------------------------------------------------"
  41. echo ""
  42. wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}2
  43. for c in {interval}
  44. do
  45. echo ""
  46. echo "---------------------------------------------------------"
  47. echo " Queries: $c for {name}"
  48. echo " wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}$c"
  49. echo "---------------------------------------------------------"
  50. echo ""
  51. wrk -r {runs} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}"$c"
  52. done
  53. """
  54. # The sort value is the order in which we represent all the tests. (Mainly helpful for our charts to give the underlying data)
  55. # a consistent ordering even when we add or remove tests. Each test should give a sort value in it's benchmark_config file.
  56. sort = 1000
  57. ##########################################################################################
  58. # Public Methods
  59. ##########################################################################################
  60. ############################################################
  61. # start(benchmarker)
  62. # Start the test using it's setup file
  63. ############################################################
  64. def start(self):
  65. return self.setup_module.start(self.benchmarker)
  66. ############################################################
  67. # End start
  68. ############################################################
  69. ############################################################
  70. # stop(benchmarker)
  71. # Stops the test using it's setup file
  72. ############################################################
  73. def stop(self):
  74. return self.setup_module.stop()
  75. ############################################################
  76. # End stop
  77. ############################################################
  78. ############################################################
  79. # verify_urls
  80. # Verifys each of the URLs for this test. THis will sinply
  81. # curl the URL and check for it's return status.
  82. # For each url, a flag will be set on this object for whether
  83. # or not it passed
  84. ############################################################
  85. def verify_urls(self):
  86. # JSON
  87. try:
  88. print "VERIFYING JSON (" + self.json_url + ") ..."
  89. url = self.benchmarker.generate_url(self.json_url, self.port)
  90. subprocess.check_call(["curl", "-f", url])
  91. print ""
  92. self.json_url_passed = True
  93. except (AttributeError, subprocess.CalledProcessError) as e:
  94. self.json_url_passed = False
  95. # DB
  96. try:
  97. print "VERIFYING DB (" + self.db_url + ") ..."
  98. url = self.benchmarker.generate_url(self.db_url, self.port)
  99. subprocess.check_call(["curl", "-f", url])
  100. print ""
  101. self.db_url_passed = True
  102. except (AttributeError, subprocess.CalledProcessError) as e:
  103. self.db_url_passed = False
  104. # Query
  105. try:
  106. print "VERIFYING Query (" + self.query_url + "2) ..."
  107. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  108. subprocess.check_call(["curl", "-f", url])
  109. print ""
  110. self.query_url_passed = True
  111. except (AttributeError, subprocess.CalledProcessError) as e:
  112. self.query_url_passed = False
  113. ############################################################
  114. # End verify_urls
  115. ############################################################
  116. ############################################################
  117. # benchmark
  118. # Runs the benchmark for each type of test that it implements
  119. # JSON/DB/Query.
  120. ############################################################
  121. def benchmark(self):
  122. # JSON
  123. try:
  124. if self.json_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "json"):
  125. sys.stdout.write("BENCHMARKING JSON ... ")
  126. remote_script = self.__generate_concurrency_script(self.json_url, self.port)
  127. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'json'))
  128. results = self.__parse_test('json')
  129. self.benchmarker.report_results(framework=self, test="json", requests=results['requests'], latency=results['latency'],
  130. results=results['results'], total_time=results['total_time'])
  131. print "Complete"
  132. except AttributeError:
  133. pass
  134. # DB
  135. try:
  136. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "db"):
  137. sys.stdout.write("BENCHMARKING DB ... ")
  138. remote_script = self.__generate_concurrency_script(self.db_url, self.port)
  139. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'db'))
  140. results = self.__parse_test('db')
  141. self.benchmarker.report_results(framework=self, test="db", requests=results['requests'], latency=results['latency'],
  142. results=results['results'], total_time=results['total_time'])
  143. print "Complete"
  144. except AttributeError:
  145. pass
  146. # Query
  147. try:
  148. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "query"):
  149. sys.stdout.write("BENCHMARKING Query ... ")
  150. remote_script = self.__generate_query_script(self.query_url, self.port)
  151. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'query'))
  152. results = self.__parse_test('query')
  153. self.benchmarker.report_results(framework=self, test="query", requests=results['requests'], latency=results['latency'],
  154. results=results['results'], total_time=results['total_time'])
  155. print "Complete"
  156. except AttributeError:
  157. pass
  158. ############################################################
  159. # End benchmark
  160. ############################################################
  161. ############################################################
  162. # parse_all
  163. # Method meant to be run for a given timestamp
  164. ############################################################
  165. def parse_all(self):
  166. # JSON
  167. if os.path.exists(self.benchmarker.output_file(self.name, 'json')):
  168. results = self.__parse_test('json')
  169. self.benchmarker.report_results(framework=self, test="json", requests=results['requests'], latency=results['latency'],
  170. results=results['results'], total_time=results['total_time'])
  171. # DB
  172. if os.path.exists(self.benchmarker.output_file(self.name, 'db')):
  173. results = self.__parse_test('db')
  174. self.benchmarker.report_results(framework=self, test="db", requests=results['requests'], latency=results['latency'],
  175. results=results['results'], total_time=results['total_time'])
  176. # Query
  177. if os.path.exists(self.benchmarker.output_file(self.name, 'query')):
  178. results = self.__parse_test('query')
  179. self.benchmarker.report_results(framework=self, test="query", requests=results['requests'], latency=results['latency'],
  180. results=results['results'], total_time=results['total_time'])
  181. ############################################################
  182. # End parse_all
  183. ############################################################
  184. ############################################################
  185. # __parse_test(test_type)
  186. ############################################################
  187. def __parse_test(self, test_type):
  188. try:
  189. results = dict()
  190. results['results'] = []
  191. results['total_time'] = 0
  192. results['latency'] = dict()
  193. results['latency']['avg'] = 0
  194. results['latency']['stdev'] = 0
  195. results['latency']['max'] = 0
  196. results['latency']['stdevPercent'] = 0
  197. results['requests'] = dict()
  198. results['requests']['avg'] = 0
  199. results['requests']['stdev'] = 0
  200. results['requests']['max'] = 0
  201. results['requests']['stdevPercent'] = 0
  202. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  203. found_warmup = False
  204. for line in raw_data:
  205. # wrk outputs a line with the "Requests/sec:" number for each run
  206. if "Requests/sec:" in line:
  207. # Every raw data file first has a warmup run, so we need to pass over that before we begin parsing
  208. if not found_warmup:
  209. found_warmup = True
  210. continue
  211. m = re.search("Requests/sec:\s+([0-9]+)", line)
  212. results['results'].append(m.group(1))
  213. if found_warmup:
  214. # search for weighttp data such as succeeded and failed.
  215. if "Latency" in line:
  216. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  217. if len(m) == 4:
  218. results['latency']['avg'] = m[0]
  219. results['latency']['stdev'] = m[1]
  220. results['latency']['max'] = m[2]
  221. results['latency']['stdevPercent'] = m[3]
  222. if "Req/Sec" in line:
  223. m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  224. if len(m) == 4:
  225. results['requests']['avg'] = m[0]
  226. results['requests']['stdev'] = m[1]
  227. results['requests']['max'] = m[2]
  228. results['requests']['stdevPercent'] = m[3]
  229. if "requests in" in line:
  230. m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  231. if m != None:
  232. # parse out the raw time, which may be in minutes or seconds
  233. raw_time = m.group(1)
  234. if "ms" in raw_time:
  235. results['total_time'] += float(raw_time[:len(raw_time)-2]) / 1000.0
  236. elif "s" in raw_time:
  237. results['total_time'] += float(raw_time[:len(raw_time)-1])
  238. elif "m" in raw_time:
  239. results['total_time'] += float(raw_time[:len(raw_time)-1]) * 60.0
  240. elif "h" in raw_time:
  241. results['total_time'] += float(raw_time[:len(raw_time)-1]) * 3600.0
  242. return results
  243. except IOError:
  244. return None
  245. ############################################################
  246. # End benchmark
  247. ############################################################
  248. ##########################################################################################
  249. # Private Methods
  250. ##########################################################################################
  251. ############################################################
  252. # __run_benchmark(script, output_file)
  253. # Runs a single benchmark using the script which is a bash
  254. # template that uses weighttp to run the test. All the results
  255. # outputed to the output_file.
  256. ############################################################
  257. def __run_benchmark(self, script, output_file):
  258. with open(output_file, 'w') as raw_file:
  259. p = subprocess.Popen(self.benchmarker.ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=raw_file)
  260. p.communicate(script)
  261. ############################################################
  262. # End __run_benchmark
  263. ############################################################
  264. ############################################################
  265. # __generate_concurrency_script(url, port)
  266. # Generates the string containing the bash script that will
  267. # be run on the client to benchmark a single test. This
  268. # specifically works for the variable concurrency tests (JSON
  269. # and DB)
  270. ############################################################
  271. def __generate_concurrency_script(self, url, port):
  272. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  273. max_threads=self.benchmarker.max_threads, name=self.name, runs=self.benchmarker.number_of_runs,
  274. interval=" ".join("{}".format(item) for item in self.benchmarker.concurrency_levels),
  275. server_host=self.benchmarker.server_host, port=port, url=url)
  276. ############################################################
  277. # End __generate_concurrency_script
  278. ############################################################
  279. ############################################################
  280. # __generate_query_script(url, port)
  281. # Generates the string containing the bash script that will
  282. # be run on the client to benchmark a single test. This
  283. # specifically works for the variable query tests (Query)
  284. ############################################################
  285. def __generate_query_script(self, url, port):
  286. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  287. max_threads=self.benchmarker.max_threads, name=self.name, runs=self.benchmarker.number_of_runs,
  288. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  289. server_host=self.benchmarker.server_host, port=port, url=url)
  290. ############################################################
  291. # End __generate_query_script
  292. ############################################################
  293. ##########################################################################################
  294. # Constructor
  295. ##########################################################################################
  296. def __init__(self, name, directory, benchmarker, args):
  297. self.name = name
  298. self.directory = directory
  299. self.benchmarker = benchmarker
  300. self.__dict__.update(args)
  301. # ensure diretory has __init__.py file so that we can use it as a pythong package
  302. if not os.path.exists(os.path.join(directory, "__init__.py")):
  303. open(os.path.join(directory, "__init__.py"), 'w').close()
  304. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  305. ############################################################
  306. # End __init__
  307. ############################################################
  308. ############################################################
  309. # End FrameworkTest
  310. ############################################################
  311. ##########################################################################################
  312. # Static methods
  313. ##########################################################################################
  314. ##############################################################
  315. # parse_config(config, directory, benchmarker)
  316. # parses a config file and returns a list of FrameworkTest
  317. # objects based on that config file.
  318. ##############################################################
  319. def parse_config(config, directory, benchmarker):
  320. tests = []
  321. # The config object can specify multiple tests, we neep to loop
  322. # over them and parse them out
  323. for test in config['tests']:
  324. for key, value in test.iteritems():
  325. test_name = config['framework']
  326. # if the test uses the 'defualt' keywork, then we don't
  327. # append anything to it's name. All configs should only have 1 default
  328. if key != 'default':
  329. # we need to use the key in the test_name
  330. test_name = test_name + "-" + key
  331. tests.append(FrameworkTest(test_name, directory, benchmarker, value))
  332. return tests
  333. ##############################################################
  334. # End parse_config
  335. ##############################################################