framework_test.py 17 KB

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