framework_test.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. headers = "-H 'Host: localhost' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) Gecko/20130501 Firefox/30.0 AppleWebKit/600.00 Chrome/30.0.0000.0 Trident/10.0 Safari/600.00' -H 'Cookie: uid=12345678901234567890; __utma=1.1234567890.1234567890.1234567890.1234567890.12; wd=2560x1600' -H 'Connection: keep-alive'"
  13. concurrency_template = """
  14. mysqladmin flush-hosts -uroot -psecret
  15. echo ""
  16. echo "---------------------------------------------------------"
  17. echo " Running Primer {name}"
  18. echo " wrk {headers} -d 60 -c 8 -t 8 http://{server_host}:{port}{url}"
  19. echo "---------------------------------------------------------"
  20. echo ""
  21. wrk {headers} -d 5 -c 8 -t 8 http://{server_host}:{port}{url}
  22. sleep 5
  23. echo ""
  24. echo "---------------------------------------------------------"
  25. echo " Running Warmup {name}"
  26. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}"
  27. echo "---------------------------------------------------------"
  28. echo ""
  29. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}
  30. sleep 5
  31. for c in {interval}
  32. do
  33. echo ""
  34. echo "---------------------------------------------------------"
  35. echo " Concurrency: $c for {name}"
  36. echo " wrk {headers} -d {duration} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) http://{server_host}:{port}{url}"
  37. echo "---------------------------------------------------------"
  38. echo ""
  39. wrk {headers} -d {duration} -c "$c" -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  40. sleep 2
  41. done
  42. """
  43. query_template = """
  44. mysqladmin flush-hosts -uroot -psecret
  45. echo ""
  46. echo "---------------------------------------------------------"
  47. echo " Running Primer {name}"
  48. echo " wrk {headers} -d 5 -c 8 -t 8 http://{server_host}:{port}{url}2"
  49. echo "---------------------------------------------------------"
  50. echo ""
  51. wrk {headers} -d 5 -c 8 -t 8 http://{server_host}:{port}{url}2
  52. sleep 5
  53. echo ""
  54. echo "---------------------------------------------------------"
  55. echo " Running Warmup {name}"
  56. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}2"
  57. echo "---------------------------------------------------------"
  58. echo ""
  59. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}2
  60. sleep 5
  61. for c in {interval}
  62. do
  63. echo ""
  64. echo "---------------------------------------------------------"
  65. echo " Queries: $c for {name}"
  66. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}$c"
  67. echo "---------------------------------------------------------"
  68. echo ""
  69. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} http://{server_host}:{port}{url}"$c"
  70. sleep 2
  71. done
  72. """
  73. # The sort value is the order in which we represent all the tests. (Mainly helpful for our charts to give the underlying data)
  74. # a consistent ordering even when we add or remove tests. Each test should give a sort value in it's benchmark_config file.
  75. sort = 1000
  76. os = 'linux'
  77. ##########################################################################################
  78. # Public Methods
  79. ##########################################################################################
  80. ############################################################
  81. # start(benchmarker)
  82. # Start the test using it's setup file
  83. ############################################################
  84. def start(self):
  85. return self.setup_module.start(self.benchmarker)
  86. ############################################################
  87. # End start
  88. ############################################################
  89. ############################################################
  90. # stop(benchmarker)
  91. # Stops the test using it's setup file
  92. ############################################################
  93. def stop(self):
  94. return self.setup_module.stop()
  95. ############################################################
  96. # End stop
  97. ############################################################
  98. ############################################################
  99. # verify_urls
  100. # Verifys each of the URLs for this test. THis will sinply
  101. # curl the URL and check for it's return status.
  102. # For each url, a flag will be set on this object for whether
  103. # or not it passed
  104. ############################################################
  105. def verify_urls(self):
  106. # JSON
  107. try:
  108. print "VERIFYING JSON (" + self.json_url + ") ..."
  109. url = self.benchmarker.generate_url(self.json_url, self.port)
  110. subprocess.check_call(["curl", "-f", url])
  111. print ""
  112. self.json_url_passed = True
  113. except (AttributeError, subprocess.CalledProcessError) as e:
  114. self.json_url_passed = False
  115. # DB
  116. try:
  117. print "VERIFYING DB (" + self.db_url + ") ..."
  118. url = self.benchmarker.generate_url(self.db_url, self.port)
  119. subprocess.check_call(["curl", "-f", url])
  120. print ""
  121. self.db_url_passed = True
  122. except (AttributeError, subprocess.CalledProcessError) as e:
  123. self.db_url_passed = False
  124. # Query
  125. try:
  126. print "VERIFYING Query (" + self.query_url + "2) ..."
  127. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  128. subprocess.check_call(["curl", "-f", url])
  129. print ""
  130. self.query_url_passed = True
  131. except (AttributeError, subprocess.CalledProcessError) as e:
  132. self.query_url_passed = False
  133. # Fortune
  134. try:
  135. print "VERIFYING Fortune (" + self.fortune_url + ") ..."
  136. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  137. subprocess.check_call(["curl", "-f", url])
  138. print ""
  139. self.fortune_url_passed = True
  140. except (AttributeError, subprocess.CalledProcessError) as e:
  141. self.fortune_url_passed = False
  142. # Update
  143. try:
  144. print "VERIFYING Update (" + self.update_url + "2) ..."
  145. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  146. subprocess.check_call(["curl", "-f", url])
  147. print ""
  148. self.update_url_passed = True
  149. except (AttributeError, subprocess.CalledProcessError) as e:
  150. self.update_url_passed = False
  151. # plaintext
  152. try:
  153. print "VERIFYING Plaintext (" + self.plaintext_url + ") ..."
  154. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  155. subprocess.check_call(["curl", "-f", url])
  156. print ""
  157. self.plaintext_url_passed = True
  158. except (AttributeError, subprocess.CalledProcessError) as e:
  159. self.plaintext_url_passed = False
  160. ############################################################
  161. # End verify_urls
  162. ############################################################
  163. ############################################################
  164. # contains_type(type)
  165. # true if this test contains an implementation of the given
  166. # test type (json, db, etc.)
  167. ############################################################
  168. def contains_type(self, type):
  169. try:
  170. if type == 'json' and self.json_url != None:
  171. return True
  172. if type == 'db' and self.db_url != None:
  173. return True
  174. if type == 'query' and self.query_url != None:
  175. return True
  176. if type == 'fortune' and self.fortune_url != None:
  177. return True
  178. if type == 'update' and self.update_url != None:
  179. return True
  180. if type == 'plaintext' and self.plaintext_url != None:
  181. return True
  182. except AttributeError:
  183. pass
  184. return False
  185. ############################################################
  186. # End stop
  187. ############################################################
  188. ############################################################
  189. # benchmark
  190. # Runs the benchmark for each type of test that it implements
  191. # JSON/DB/Query.
  192. ############################################################
  193. def benchmark(self):
  194. # JSON
  195. try:
  196. if self.json_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "json"):
  197. sys.stdout.write("BENCHMARKING JSON ... ")
  198. sys.stdout.flush()
  199. remote_script = self.__generate_concurrency_script(self.json_url, self.port)
  200. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'json'))
  201. results = self.__parse_test('json')
  202. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  203. print "Complete"
  204. except AttributeError:
  205. pass
  206. # DB
  207. try:
  208. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "db"):
  209. sys.stdout.write("BENCHMARKING DB ... ")
  210. sys.stdout.flush()
  211. remote_script = self.__generate_concurrency_script(self.db_url, self.port)
  212. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'db'))
  213. results = self.__parse_test('db')
  214. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  215. print "Complete"
  216. except AttributeError:
  217. pass
  218. # Query
  219. try:
  220. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "query"):
  221. sys.stdout.write("BENCHMARKING Query ... ")
  222. sys.stdout.flush()
  223. remote_script = self.__generate_query_script(self.query_url, self.port)
  224. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'query'))
  225. results = self.__parse_test('query')
  226. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  227. print "Complete"
  228. except AttributeError:
  229. pass
  230. # fortune
  231. try:
  232. if self.fortune_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "fortune"):
  233. sys.stdout.write("BENCHMARKING Fortune ... ")
  234. sys.stdout.flush()
  235. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port)
  236. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'fortune'))
  237. results = self.__parse_test('fortune')
  238. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  239. print "Complete"
  240. except AttributeError:
  241. pass
  242. # update
  243. try:
  244. if self.update_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "update"):
  245. sys.stdout.write("BENCHMARKING Update ... ")
  246. sys.stdout.flush()
  247. remote_script = self.__generate_query_script(self.update_url, self.port)
  248. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'update'))
  249. results = self.__parse_test('update')
  250. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  251. print "Complete"
  252. except AttributeError:
  253. pass
  254. # plaintext
  255. try:
  256. if self.plaintext_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "plaintext"):
  257. sys.stdout.write("BENCHMARKING Plaintext ... ")
  258. sys.stdout.flush()
  259. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port)
  260. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'plaintext'))
  261. results = self.__parse_test('plaintext')
  262. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  263. print "Complete"
  264. except AttributeError:
  265. pass
  266. ############################################################
  267. # End benchmark
  268. ############################################################
  269. ############################################################
  270. # parse_all
  271. # Method meant to be run for a given timestamp
  272. ############################################################
  273. def parse_all(self):
  274. # JSON
  275. if os.path.exists(self.benchmarker.output_file(self.name, 'json')):
  276. results = self.__parse_test('json')
  277. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  278. # DB
  279. if os.path.exists(self.benchmarker.output_file(self.name, 'db')):
  280. results = self.__parse_test('db')
  281. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  282. # Query
  283. if os.path.exists(self.benchmarker.output_file(self.name, 'query')):
  284. results = self.__parse_test('query')
  285. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  286. # Fortune
  287. if os.path.exists(self.benchmarker.output_file(self.name, 'fortune')):
  288. results = self.__parse_test('fortune')
  289. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  290. # Update
  291. if os.path.exists(self.benchmarker.output_file(self.name, 'update')):
  292. results = self.__parse_test('update')
  293. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  294. # Plaintext
  295. if os.path.exists(self.benchmarker.output_file(self.name, 'plaintext')):
  296. results = self.__parse_test('plaintext')
  297. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  298. ############################################################
  299. # End parse_all
  300. ############################################################
  301. ############################################################
  302. # __parse_test(test_type)
  303. ############################################################
  304. def __parse_test(self, test_type):
  305. try:
  306. results = dict()
  307. results['results'] = []
  308. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  309. is_warmup = True
  310. rawData = None
  311. for line in raw_data:
  312. if "Queries:" in line or "Concurrency:" in line:
  313. is_warmup = False
  314. rawData = None
  315. continue
  316. if "Warmup" in line or "Primer" in line:
  317. is_warmup = True
  318. continue
  319. if not is_warmup:
  320. if rawData == None:
  321. rawData = dict()
  322. results['results'].append(rawData)
  323. #if "Requests/sec:" in line:
  324. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  325. # rawData['reportedResults'] = m.group(1)
  326. # search for weighttp data such as succeeded and failed.
  327. if "Latency" in line:
  328. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  329. if len(m) == 4:
  330. rawData['latencyAvg'] = m[0]
  331. rawData['latencyStdev'] = m[1]
  332. rawData['latencyMax'] = m[2]
  333. # rawData['latencyStdevPercent'] = m[3]
  334. #if "Req/Sec" in line:
  335. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  336. # if len(m) == 4:
  337. # rawData['requestsAvg'] = m[0]
  338. # rawData['requestsStdev'] = m[1]
  339. # rawData['requestsMax'] = m[2]
  340. # rawData['requestsStdevPercent'] = m[3]
  341. #if "requests in" in line:
  342. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  343. # if m != None:
  344. # # parse out the raw time, which may be in minutes or seconds
  345. # raw_time = m.group(1)
  346. # if "ms" in raw_time:
  347. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  348. # elif "s" in raw_time:
  349. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  350. # elif "m" in raw_time:
  351. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  352. # elif "h" in raw_time:
  353. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  354. if "requests in" in line:
  355. m = re.search("([0-9]+) requests in", line)
  356. if m != None:
  357. rawData['totalRequests'] = int(m.group(1))
  358. if "Socket errors" in line:
  359. if "connect" in line:
  360. m = re.search("connect ([0-9]+)", line)
  361. rawData['connect'] = int(m.group(1))
  362. if "read" in line:
  363. m = re.search("read ([0-9]+)", line)
  364. rawData['read'] = int(m.group(1))
  365. if "write" in line:
  366. m = re.search("write ([0-9]+)", line)
  367. rawData['write'] = int(m.group(1))
  368. if "timeout" in line:
  369. m = re.search("timeout ([0-9]+)", line)
  370. rawData['timeout'] = int(m.group(1))
  371. if "Non-2xx" in line:
  372. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  373. if m != None:
  374. rawData['5xx'] = int(m.group(1))
  375. return results
  376. except IOError:
  377. return None
  378. ############################################################
  379. # End benchmark
  380. ############################################################
  381. ##########################################################################################
  382. # Private Methods
  383. ##########################################################################################
  384. ############################################################
  385. # __run_benchmark(script, output_file)
  386. # Runs a single benchmark using the script which is a bash
  387. # template that uses weighttp to run the test. All the results
  388. # outputed to the output_file.
  389. ############################################################
  390. def __run_benchmark(self, script, output_file):
  391. with open(output_file, 'w') as raw_file:
  392. p = subprocess.Popen(self.benchmarker.ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=raw_file)
  393. p.communicate(script)
  394. ############################################################
  395. # End __run_benchmark
  396. ############################################################
  397. ############################################################
  398. # __generate_concurrency_script(url, port)
  399. # Generates the string containing the bash script that will
  400. # be run on the client to benchmark a single test. This
  401. # specifically works for the variable concurrency tests (JSON
  402. # and DB)
  403. ############################################################
  404. def __generate_concurrency_script(self, url, port, wrk_command="wrk", intervals=[]):
  405. if len(intervals) == 0:
  406. intervals = self.benchmarker.concurrency_levels
  407. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  408. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  409. interval=" ".join("{}".format(item) for item in intervals),
  410. server_host=self.benchmarker.server_host, port=port, url=url, headers=self.headers)
  411. ############################################################
  412. # End __generate_concurrency_script
  413. ############################################################
  414. ############################################################
  415. # __generate_query_script(url, port)
  416. # Generates the string containing the bash script that will
  417. # be run on the client to benchmark a single test. This
  418. # specifically works for the variable query tests (Query)
  419. ############################################################
  420. def __generate_query_script(self, url, port):
  421. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  422. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  423. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  424. server_host=self.benchmarker.server_host, port=port, url=url, headers=self.headers)
  425. ############################################################
  426. # End __generate_query_script
  427. ############################################################
  428. ##########################################################################################
  429. # Constructor
  430. ##########################################################################################
  431. def __init__(self, name, directory, benchmarker, args):
  432. self.name = name
  433. self.directory = directory
  434. self.benchmarker = benchmarker
  435. self.__dict__.update(args)
  436. # ensure diretory has __init__.py file so that we can use it as a pythong package
  437. if not os.path.exists(os.path.join(directory, "__init__.py")):
  438. open(os.path.join(directory, "__init__.py"), 'w').close()
  439. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  440. ############################################################
  441. # End __init__
  442. ############################################################
  443. ############################################################
  444. # End FrameworkTest
  445. ############################################################
  446. ##########################################################################################
  447. # Static methods
  448. ##########################################################################################
  449. ##############################################################
  450. # parse_config(config, directory, benchmarker)
  451. # parses a config file and returns a list of FrameworkTest
  452. # objects based on that config file.
  453. ##############################################################
  454. def parse_config(config, directory, benchmarker):
  455. tests = []
  456. # The config object can specify multiple tests, we neep to loop
  457. # over them and parse them out
  458. for test in config['tests']:
  459. for key, value in test.iteritems():
  460. test_name = config['framework']
  461. # if the test uses the 'defualt' keywork, then we don't
  462. # append anything to it's name. All configs should only have 1 default
  463. if key != 'default':
  464. # we need to use the key in the test_name
  465. test_name = test_name + "-" + key
  466. tests.append(FrameworkTest(test_name, directory, benchmarker, value))
  467. return tests
  468. ##############################################################
  469. # End parse_config
  470. ##############################################################