framework_test.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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. # Fortune
  132. try:
  133. print "VERIFYING Fortune (" + self.fortune_url + ") ..."
  134. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  135. subprocess.check_call(["curl", "-f", url])
  136. print ""
  137. self.fortune_url_passed = True
  138. except (AttributeError, subprocess.CalledProcessError) as e:
  139. self.fortune_url_passed = False
  140. # Update
  141. try:
  142. print "VERIFYING Update (" + self.update_url + "2) ..."
  143. url = self.benchmarker.generate_url(self.update_url, self.port)
  144. subprocess.check_call(["curl", "-f", url])
  145. print ""
  146. self.update_url_passed = True
  147. except (AttributeError, subprocess.CalledProcessError) as e:
  148. self.update_url_passed = False
  149. ############################################################
  150. # End verify_urls
  151. ############################################################
  152. ############################################################
  153. # contains_type(type)
  154. # true if this test contains an implementation of the given
  155. # test type (json, db, etc.)
  156. ############################################################
  157. def contains_type(self, type):
  158. try:
  159. if type == 'json' and self.json_url != None:
  160. return True
  161. if type == 'db' and self.db_url != None:
  162. return True
  163. if type == 'query' and self.query_url != None:
  164. return True
  165. if type == 'fortune' and self.fortune_url != None:
  166. return True
  167. if type == 'update' and self.update_url != None:
  168. return True
  169. except AttributeError:
  170. pass
  171. return False
  172. ############################################################
  173. # End stop
  174. ############################################################
  175. ############################################################
  176. # benchmark
  177. # Runs the benchmark for each type of test that it implements
  178. # JSON/DB/Query.
  179. ############################################################
  180. def benchmark(self):
  181. # JSON
  182. try:
  183. if self.json_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "json"):
  184. sys.stdout.write("BENCHMARKING JSON ... ")
  185. remote_script = self.__generate_concurrency_script(self.json_url, self.port)
  186. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'json'))
  187. results = self.__parse_test('json')
  188. self.benchmarker.report_results(framework=self, test="json", requests=results['requests'], latency=results['latency'],
  189. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  190. print "Complete"
  191. except AttributeError:
  192. pass
  193. # DB
  194. try:
  195. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "db"):
  196. sys.stdout.write("BENCHMARKING DB ... ")
  197. remote_script = self.__generate_concurrency_script(self.db_url, self.port)
  198. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'db'))
  199. results = self.__parse_test('db')
  200. self.benchmarker.report_results(framework=self, test="db", requests=results['requests'], latency=results['latency'],
  201. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  202. print "Complete"
  203. except AttributeError:
  204. pass
  205. # Query
  206. try:
  207. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "query"):
  208. sys.stdout.write("BENCHMARKING Query ... ")
  209. remote_script = self.__generate_query_script(self.query_url, self.port)
  210. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'query'))
  211. results = self.__parse_test('query')
  212. self.benchmarker.report_results(framework=self, test="query", requests=results['requests'], latency=results['latency'],
  213. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  214. print "Complete"
  215. except AttributeError:
  216. pass
  217. # fortune
  218. try:
  219. if self.fortune_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "fortune"):
  220. sys.stdout.write("BENCHMARKING Fortune ... ")
  221. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port)
  222. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'fortune'))
  223. results = self.__parse_test('fortune')
  224. self.benchmarker.report_results(framework=self, test="fortune", requests=results['requests'], latency=results['latency'],
  225. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  226. print "Complete"
  227. except AttributeError:
  228. pass
  229. # update
  230. try:
  231. if self.update_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "update"):
  232. sys.stdout.write("BENCHMARKING Update ... ")
  233. remote_script = self.__generate_query_script(self.update_url, self.port)
  234. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'update'))
  235. results = self.__parse_test('update')
  236. self.benchmarker.report_results(framework=self, test="update", requests=results['requests'], latency=results['latency'],
  237. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  238. print "Complete"
  239. except AttributeError:
  240. pass
  241. ############################################################
  242. # End benchmark
  243. ############################################################
  244. ############################################################
  245. # parse_all
  246. # Method meant to be run for a given timestamp
  247. ############################################################
  248. def parse_all(self):
  249. # JSON
  250. if os.path.exists(self.benchmarker.output_file(self.name, 'json')):
  251. results = self.__parse_test('json')
  252. self.benchmarker.report_results(framework=self, test="json", requests=results['requests'], latency=results['latency'],
  253. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  254. # DB
  255. if os.path.exists(self.benchmarker.output_file(self.name, 'db')):
  256. results = self.__parse_test('db')
  257. self.benchmarker.report_results(framework=self, test="db", requests=results['requests'], latency=results['latency'],
  258. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  259. # Query
  260. if os.path.exists(self.benchmarker.output_file(self.name, 'query')):
  261. results = self.__parse_test('query')
  262. self.benchmarker.report_results(framework=self, test="query", requests=results['requests'], latency=results['latency'],
  263. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  264. # Fortune
  265. if os.path.exists(self.benchmarker.output_file(self.name, 'fortune')):
  266. results = self.__parse_test('fortune')
  267. self.benchmarker.report_results(framework=self, test="fortune", requests=results['requests'], latency=results['latency'],
  268. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  269. # Update
  270. if os.path.exists(self.benchmarker.output_file(self.name, 'update')):
  271. results = self.__parse_test('update')
  272. self.benchmarker.report_results(framework=self, test="update", requests=results['requests'], latency=results['latency'],
  273. results=results['results'], total_time=results['total_time'], errors=results['errors'], total_requests=results['totalRequests'])
  274. ############################################################
  275. # End parse_all
  276. ############################################################
  277. ############################################################
  278. # __parse_test(test_type)
  279. ############################################################
  280. def __parse_test(self, test_type):
  281. try:
  282. results = dict()
  283. results['results'] = []
  284. results['total_time'] = 0
  285. results['totalRequests'] = 0
  286. results['latency'] = dict()
  287. results['latency']['avg'] = 0
  288. results['latency']['stdev'] = 0
  289. results['latency']['max'] = 0
  290. results['latency']['stdevPercent'] = 0
  291. results['requests'] = dict()
  292. results['requests']['avg'] = 0
  293. results['requests']['stdev'] = 0
  294. results['requests']['max'] = 0
  295. results['requests']['stdevPercent'] = 0
  296. results['errors'] = dict()
  297. results['errors']['connect'] = 0
  298. results['errors']['read'] = 0
  299. results['errors']['write'] = 0
  300. results['errors']['timeout'] = 0
  301. results['errors']['5xx'] = 0
  302. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  303. is_warmup = False
  304. for line in raw_data:
  305. if "Queries:" in line or "Concurrency:" in line:
  306. is_warmup = False
  307. continue
  308. if "Warmup" in line or "Primer" in line:
  309. is_warmup = True
  310. continue
  311. if not is_warmup:
  312. if "Requests/sec:" in line:
  313. m = re.search("Requests/sec:\s+([0-9]+)", line)
  314. results['results'].append(m.group(1))
  315. # search for weighttp data such as succeeded and failed.
  316. if "Latency" in line:
  317. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  318. if len(m) == 4:
  319. results['latency']['avg'] = m[0]
  320. results['latency']['stdev'] = m[1]
  321. results['latency']['max'] = m[2]
  322. results['latency']['stdevPercent'] = m[3]
  323. if "Req/Sec" in line:
  324. m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  325. if len(m) == 4:
  326. results['requests']['avg'] = m[0]
  327. results['requests']['stdev'] = m[1]
  328. results['requests']['max'] = m[2]
  329. results['requests']['stdevPercent'] = m[3]
  330. if "requests in" in line:
  331. m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  332. if m != None:
  333. # parse out the raw time, which may be in minutes or seconds
  334. raw_time = m.group(1)
  335. if "ms" in raw_time:
  336. results['total_time'] += float(raw_time[:len(raw_time)-2]) / 1000.0
  337. elif "s" in raw_time:
  338. results['total_time'] += float(raw_time[:len(raw_time)-1])
  339. elif "m" in raw_time:
  340. results['total_time'] += float(raw_time[:len(raw_time)-1]) * 60.0
  341. elif "h" in raw_time:
  342. results['total_time'] += float(raw_time[:len(raw_time)-1]) * 3600.0
  343. if "requests in" in line:
  344. m = re.search("([0-9]+) requests in", line)
  345. if m != None:
  346. results['totalRequests'] += int(m.group(1))
  347. if "Socket errors" in line:
  348. if "connect" in line:
  349. m = re.search("connect ([0-9]+)", line)
  350. results['errors']['connect'] += int(m.group(1))
  351. if "read" in line:
  352. m = re.search("read ([0-9]+)", line)
  353. results['errors']['read'] += int(m.group(1))
  354. if "write" in line:
  355. m = re.search("write ([0-9]+)", line)
  356. results['errors']['write'] += int(m.group(1))
  357. if "timeout" in line:
  358. m = re.search("timeout ([0-9]+)", line)
  359. results['errors']['timeout'] += int(m.group(1))
  360. if "Non-2xx" in line:
  361. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  362. if m != None:
  363. results['errors']['5xx'] += int(m.group(1))
  364. return results
  365. except IOError:
  366. return None
  367. ############################################################
  368. # End benchmark
  369. ############################################################
  370. ##########################################################################################
  371. # Private Methods
  372. ##########################################################################################
  373. ############################################################
  374. # __run_benchmark(script, output_file)
  375. # Runs a single benchmark using the script which is a bash
  376. # template that uses weighttp to run the test. All the results
  377. # outputed to the output_file.
  378. ############################################################
  379. def __run_benchmark(self, script, output_file):
  380. with open(output_file, 'w') as raw_file:
  381. p = subprocess.Popen(self.benchmarker.ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=raw_file)
  382. p.communicate(script)
  383. ############################################################
  384. # End __run_benchmark
  385. ############################################################
  386. ############################################################
  387. # __generate_concurrency_script(url, port)
  388. # Generates the string containing the bash script that will
  389. # be run on the client to benchmark a single test. This
  390. # specifically works for the variable concurrency tests (JSON
  391. # and DB)
  392. ############################################################
  393. def __generate_concurrency_script(self, url, port):
  394. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  395. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  396. interval=" ".join("{}".format(item) for item in self.benchmarker.concurrency_levels),
  397. server_host=self.benchmarker.server_host, port=port, url=url)
  398. ############################################################
  399. # End __generate_concurrency_script
  400. ############################################################
  401. ############################################################
  402. # __generate_query_script(url, port)
  403. # Generates the string containing the bash script that will
  404. # be run on the client to benchmark a single test. This
  405. # specifically works for the variable query tests (Query)
  406. ############################################################
  407. def __generate_query_script(self, url, port):
  408. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  409. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  410. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  411. server_host=self.benchmarker.server_host, port=port, url=url)
  412. ############################################################
  413. # End __generate_query_script
  414. ############################################################
  415. ##########################################################################################
  416. # Constructor
  417. ##########################################################################################
  418. def __init__(self, name, directory, benchmarker, args):
  419. self.name = name
  420. self.directory = directory
  421. self.benchmarker = benchmarker
  422. self.__dict__.update(args)
  423. # ensure diretory has __init__.py file so that we can use it as a pythong package
  424. if not os.path.exists(os.path.join(directory, "__init__.py")):
  425. open(os.path.join(directory, "__init__.py"), 'w').close()
  426. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  427. ############################################################
  428. # End __init__
  429. ############################################################
  430. ############################################################
  431. # End FrameworkTest
  432. ############################################################
  433. ##########################################################################################
  434. # Static methods
  435. ##########################################################################################
  436. ##############################################################
  437. # parse_config(config, directory, benchmarker)
  438. # parses a config file and returns a list of FrameworkTest
  439. # objects based on that config file.
  440. ##############################################################
  441. def parse_config(config, directory, benchmarker):
  442. tests = []
  443. # The config object can specify multiple tests, we neep to loop
  444. # over them and parse them out
  445. for test in config['tests']:
  446. for key, value in test.iteritems():
  447. test_name = config['framework']
  448. # if the test uses the 'defualt' keywork, then we don't
  449. # append anything to it's name. All configs should only have 1 default
  450. if key != 'default':
  451. # we need to use the key in the test_name
  452. test_name = test_name + "-" + key
  453. tests.append(FrameworkTest(test_name, directory, benchmarker, value))
  454. return tests
  455. ##############################################################
  456. # End parse_config
  457. ##############################################################