framework_test.py 16 KB

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