framework_test.py 16 KB

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