framework_test.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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 'Connection: keep-alive'"
  13. headers_full = "-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'"
  14. concurrency_template = """
  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} {pipeline} -d {duration} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  37. echo "---------------------------------------------------------"
  38. echo ""
  39. {wrk} {headers} {pipeline} -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. echo ""
  45. echo "---------------------------------------------------------"
  46. echo " Running Primer {name}"
  47. echo " wrk {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}2\""
  48. echo "---------------------------------------------------------"
  49. echo ""
  50. wrk {headers} -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 {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  56. echo "---------------------------------------------------------"
  57. echo ""
  58. wrk {headers} -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 {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  66. echo "---------------------------------------------------------"
  67. echo ""
  68. wrk {headers} -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. os = 'linux'
  76. ##########################################################################################
  77. # Public Methods
  78. ##########################################################################################
  79. ############################################################
  80. # start(benchmarker)
  81. # Start the test using it's setup file
  82. ############################################################
  83. def start(self):
  84. return self.setup_module.start(self.benchmarker)
  85. ############################################################
  86. # End start
  87. ############################################################
  88. ############################################################
  89. # stop(benchmarker)
  90. # Stops the test using it's setup file
  91. ############################################################
  92. def stop(self):
  93. return self.setup_module.stop()
  94. ############################################################
  95. # End stop
  96. ############################################################
  97. ############################################################
  98. # verify_urls
  99. # Verifys each of the URLs for this test. THis will sinply
  100. # curl the URL and check for it's return status.
  101. # For each url, a flag will be set on this object for whether
  102. # or not it passed
  103. ############################################################
  104. def verify_urls(self):
  105. # JSON
  106. try:
  107. print "VERIFYING JSON (" + self.json_url + ") ..."
  108. url = self.benchmarker.generate_url(self.json_url, self.port)
  109. subprocess.check_call(["curl", "-f", url])
  110. print ""
  111. self.json_url_passed = True
  112. except (AttributeError, subprocess.CalledProcessError) as e:
  113. self.json_url_passed = False
  114. # DB
  115. try:
  116. print "VERIFYING DB (" + self.db_url + ") ..."
  117. url = self.benchmarker.generate_url(self.db_url, self.port)
  118. subprocess.check_call(["curl", "-f", url])
  119. print ""
  120. self.db_url_passed = True
  121. except (AttributeError, subprocess.CalledProcessError) as e:
  122. self.db_url_passed = False
  123. # Query
  124. try:
  125. print "VERIFYING Query (" + self.query_url + "2) ..."
  126. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  127. subprocess.check_call(["curl", "-f", url])
  128. print ""
  129. self.query_url_passed = True
  130. except (AttributeError, subprocess.CalledProcessError) as e:
  131. self.query_url_passed = False
  132. # Fortune
  133. try:
  134. print "VERIFYING Fortune (" + self.fortune_url + ") ..."
  135. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  136. subprocess.check_call(["curl", "-f", url])
  137. print ""
  138. self.fortune_url_passed = True
  139. except (AttributeError, subprocess.CalledProcessError) as e:
  140. self.fortune_url_passed = False
  141. # Update
  142. try:
  143. print "VERIFYING Update (" + self.update_url + "2) ..."
  144. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  145. subprocess.check_call(["curl", "-f", url])
  146. print ""
  147. self.update_url_passed = True
  148. except (AttributeError, subprocess.CalledProcessError) as e:
  149. self.update_url_passed = False
  150. # plaintext
  151. try:
  152. print "VERIFYING Plaintext (" + self.plaintext_url + ") ..."
  153. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  154. subprocess.check_call(["curl", "-f", url])
  155. print ""
  156. self.plaintext_url_passed = True
  157. except (AttributeError, subprocess.CalledProcessError) as e:
  158. self.plaintext_url_passed = False
  159. ############################################################
  160. # End verify_urls
  161. ############################################################
  162. ############################################################
  163. # contains_type(type)
  164. # true if this test contains an implementation of the given
  165. # test type (json, db, etc.)
  166. ############################################################
  167. def contains_type(self, type):
  168. try:
  169. if type == 'json' and self.json_url != None:
  170. return True
  171. if type == 'db' and self.db_url != None:
  172. return True
  173. if type == 'query' and self.query_url != None:
  174. return True
  175. if type == 'fortune' and self.fortune_url != None:
  176. return True
  177. if type == 'update' and self.update_url != None:
  178. return True
  179. if type == 'plaintext' and self.plaintext_url != None:
  180. return True
  181. except AttributeError:
  182. pass
  183. return False
  184. ############################################################
  185. # End stop
  186. ############################################################
  187. ############################################################
  188. # benchmark
  189. # Runs the benchmark for each type of test that it implements
  190. # JSON/DB/Query.
  191. ############################################################
  192. def benchmark(self):
  193. # JSON
  194. try:
  195. if self.json_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "json"):
  196. sys.stdout.write("BENCHMARKING JSON ... ")
  197. sys.stdout.flush()
  198. remote_script = self.__generate_concurrency_script(self.json_url, self.port)
  199. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'json'))
  200. results = self.__parse_test('json')
  201. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  202. print "Complete"
  203. except AttributeError:
  204. pass
  205. # DB
  206. try:
  207. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "db"):
  208. sys.stdout.write("BENCHMARKING DB ... ")
  209. sys.stdout.flush()
  210. remote_script = self.__generate_concurrency_script(self.db_url, self.port)
  211. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'db'))
  212. results = self.__parse_test('db')
  213. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  214. print "Complete"
  215. except AttributeError:
  216. pass
  217. # Query
  218. try:
  219. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "query"):
  220. sys.stdout.write("BENCHMARKING Query ... ")
  221. sys.stdout.flush()
  222. remote_script = self.__generate_query_script(self.query_url, self.port)
  223. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'query'))
  224. results = self.__parse_test('query')
  225. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  226. print "Complete"
  227. except AttributeError:
  228. pass
  229. # fortune
  230. try:
  231. if self.fortune_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "fortune"):
  232. sys.stdout.write("BENCHMARKING Fortune ... ")
  233. sys.stdout.flush()
  234. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port)
  235. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'fortune'))
  236. results = self.__parse_test('fortune')
  237. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  238. print "Complete"
  239. except AttributeError:
  240. pass
  241. # update
  242. try:
  243. if self.update_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "update"):
  244. sys.stdout.write("BENCHMARKING Update ... ")
  245. sys.stdout.flush()
  246. remote_script = self.__generate_query_script(self.update_url, self.port)
  247. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'update'))
  248. results = self.__parse_test('update')
  249. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  250. print "Complete"
  251. except AttributeError:
  252. pass
  253. # plaintext
  254. try:
  255. if self.plaintext_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == "plaintext"):
  256. sys.stdout.write("BENCHMARKING Plaintext ... ")
  257. sys.stdout.flush()
  258. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, wrk_command="wrk-pipeline", intervals=[256,1024,4096,16384], pipeline="--pipeline 16")
  259. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, 'plaintext'))
  260. results = self.__parse_test('plaintext')
  261. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  262. print "Complete"
  263. except AttributeError:
  264. pass
  265. ############################################################
  266. # End benchmark
  267. ############################################################
  268. ############################################################
  269. # parse_all
  270. # Method meant to be run for a given timestamp
  271. ############################################################
  272. def parse_all(self):
  273. # JSON
  274. if os.path.exists(self.benchmarker.output_file(self.name, 'json')):
  275. results = self.__parse_test('json')
  276. self.benchmarker.report_results(framework=self, test="json", results=results['results'])
  277. # DB
  278. if os.path.exists(self.benchmarker.output_file(self.name, 'db')):
  279. results = self.__parse_test('db')
  280. self.benchmarker.report_results(framework=self, test="db", results=results['results'])
  281. # Query
  282. if os.path.exists(self.benchmarker.output_file(self.name, 'query')):
  283. results = self.__parse_test('query')
  284. self.benchmarker.report_results(framework=self, test="query", results=results['results'])
  285. # Fortune
  286. if os.path.exists(self.benchmarker.output_file(self.name, 'fortune')):
  287. results = self.__parse_test('fortune')
  288. self.benchmarker.report_results(framework=self, test="fortune", results=results['results'])
  289. # Update
  290. if os.path.exists(self.benchmarker.output_file(self.name, 'update')):
  291. results = self.__parse_test('update')
  292. self.benchmarker.report_results(framework=self, test="update", results=results['results'])
  293. # Plaintext
  294. if os.path.exists(self.benchmarker.output_file(self.name, 'plaintext')):
  295. results = self.__parse_test('plaintext')
  296. self.benchmarker.report_results(framework=self, test="plaintext", results=results['results'])
  297. ############################################################
  298. # End parse_all
  299. ############################################################
  300. ############################################################
  301. # __parse_test(test_type)
  302. ############################################################
  303. def __parse_test(self, test_type):
  304. try:
  305. results = dict()
  306. results['results'] = []
  307. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  308. is_warmup = True
  309. rawData = None
  310. for line in raw_data:
  311. if "Queries:" in line or "Concurrency:" in line:
  312. is_warmup = False
  313. rawData = None
  314. continue
  315. if "Warmup" in line or "Primer" in line:
  316. is_warmup = True
  317. continue
  318. if not is_warmup:
  319. if rawData == None:
  320. rawData = dict()
  321. results['results'].append(rawData)
  322. #if "Requests/sec:" in line:
  323. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  324. # rawData['reportedResults'] = m.group(1)
  325. # search for weighttp data such as succeeded and failed.
  326. if "Latency" in line:
  327. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  328. if len(m) == 4:
  329. rawData['latencyAvg'] = m[0]
  330. rawData['latencyStdev'] = m[1]
  331. rawData['latencyMax'] = m[2]
  332. # rawData['latencyStdevPercent'] = m[3]
  333. #if "Req/Sec" in line:
  334. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  335. # if len(m) == 4:
  336. # rawData['requestsAvg'] = m[0]
  337. # rawData['requestsStdev'] = m[1]
  338. # rawData['requestsMax'] = m[2]
  339. # rawData['requestsStdevPercent'] = m[3]
  340. #if "requests in" in line:
  341. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  342. # if m != None:
  343. # # parse out the raw time, which may be in minutes or seconds
  344. # raw_time = m.group(1)
  345. # if "ms" in raw_time:
  346. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  347. # elif "s" in raw_time:
  348. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  349. # elif "m" in raw_time:
  350. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  351. # elif "h" in raw_time:
  352. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  353. if "requests in" in line:
  354. m = re.search("([0-9]+) requests in", line)
  355. if m != None:
  356. rawData['totalRequests'] = int(m.group(1))
  357. if "Socket errors" in line:
  358. if "connect" in line:
  359. m = re.search("connect ([0-9]+)", line)
  360. rawData['connect'] = int(m.group(1))
  361. if "read" in line:
  362. m = re.search("read ([0-9]+)", line)
  363. rawData['read'] = int(m.group(1))
  364. if "write" in line:
  365. m = re.search("write ([0-9]+)", line)
  366. rawData['write'] = int(m.group(1))
  367. if "timeout" in line:
  368. m = re.search("timeout ([0-9]+)", line)
  369. rawData['timeout'] = int(m.group(1))
  370. if "Non-2xx" in line:
  371. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  372. if m != None:
  373. rawData['5xx'] = int(m.group(1))
  374. return results
  375. except IOError:
  376. return None
  377. ############################################################
  378. # End benchmark
  379. ############################################################
  380. ##########################################################################################
  381. # Private Methods
  382. ##########################################################################################
  383. ############################################################
  384. # __run_benchmark(script, output_file)
  385. # Runs a single benchmark using the script which is a bash
  386. # template that uses weighttp to run the test. All the results
  387. # outputed to the output_file.
  388. ############################################################
  389. def __run_benchmark(self, script, output_file):
  390. with open(output_file, 'w') as raw_file:
  391. p = subprocess.Popen(self.benchmarker.ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=raw_file)
  392. p.communicate(script)
  393. ############################################################
  394. # End __run_benchmark
  395. ############################################################
  396. ############################################################
  397. # __generate_concurrency_script(url, port)
  398. # Generates the string containing the bash script that will
  399. # be run on the client to benchmark a single test. This
  400. # specifically works for the variable concurrency tests (JSON
  401. # and DB)
  402. ############################################################
  403. def __generate_concurrency_script(self, url, port, wrk_command="wrk", intervals=[], pipeline=""):
  404. if len(intervals) == 0:
  405. intervals = self.benchmarker.concurrency_levels
  406. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  407. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  408. interval=" ".join("{}".format(item) for item in intervals),
  409. server_host=self.benchmarker.server_host, port=port, url=url, headers=self.headers, wrk=wrk_command,
  410. pipeline=pipeline)
  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. ##############################################################