benchmarker.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. from installer import Installer
  2. from framework_test import FrameworkTest
  3. import framework_test
  4. import os
  5. import json
  6. import subprocess
  7. import time
  8. import textwrap
  9. import pprint
  10. import csv
  11. import sys
  12. from datetime import datetime
  13. class Benchmarker:
  14. ##########################################################################################
  15. # Public methods
  16. ##########################################################################################
  17. ############################################################
  18. # Prints all the available tests
  19. ############################################################
  20. def run_list_tests(self):
  21. all_tests = self.__gather_tests()
  22. for test in all_tests:
  23. print test.name
  24. self.__finish()
  25. ############################################################
  26. # End run_list_tests
  27. ############################################################
  28. ############################################################
  29. # next_sort
  30. # Prints the next available sort number that should be used
  31. # for any new tests
  32. ############################################################
  33. def next_sort_value(self):
  34. all_tests = self.__gather_tests()
  35. # all_tests is already sorted by sort, so we can just get
  36. # the last one and add one to it.
  37. print " Next sort number is: " + str(all_tests[-1].sort + 1)
  38. self.__finish()
  39. ############################################################
  40. # End next_sort_value
  41. ############################################################
  42. ############################################################
  43. # parse_timestamp
  44. # Re-parses the raw data for a given timestamp
  45. ############################################################
  46. def parse_timestamp(self):
  47. all_tests = self.__gather_tests()
  48. for test in all_tests:
  49. test.parse_all()
  50. self.__parse_results(all_tests)
  51. self.__finish()
  52. ############################################################
  53. # End run_list_tests
  54. ############################################################
  55. ############################################################
  56. # Run the tests:
  57. # This process involves setting up the client/server machines
  58. # with any necessary change. Then going through each test,
  59. # running their setup script, verifying the URLs, and
  60. # running benchmarks against them.
  61. ############################################################
  62. def run(self):
  63. ##########################
  64. # Get a list of all known
  65. # tests that we can run.
  66. ##########################
  67. all_tests = self.__gather_tests()
  68. ##########################
  69. # Setup client/server
  70. ##########################
  71. print textwrap.dedent("""
  72. =====================================================
  73. Preparing up Server and Client ...
  74. =====================================================
  75. """)
  76. self.__setup_server()
  77. self.__setup_client()
  78. ##########################
  79. # Run tests
  80. ##########################
  81. self.__run_tests(all_tests)
  82. ##########################
  83. # Parse results
  84. ##########################
  85. if self.mode == "benchmark":
  86. print textwrap.dedent("""
  87. =====================================================
  88. Parsing Results ...
  89. =====================================================
  90. """)
  91. self.__parse_results(all_tests)
  92. self.__finish()
  93. ############################################################
  94. # End run
  95. ############################################################
  96. ############################################################
  97. # sftp_string(batch_file)
  98. # generates a fully qualified URL for sftp to client
  99. ############################################################
  100. def sftp_string(self, batch_file):
  101. sftp_string = "sftp -oStrictHostKeyChecking=no "
  102. if batch_file != None: sftp_string += " -b " + batch_file + " "
  103. if self.identity_file != None:
  104. sftp_string += " -i " + self.identity_file + " "
  105. return sftp_string + self.client_user + "@" + self.client_host
  106. ############################################################
  107. # End sftp_string
  108. ############################################################
  109. ############################################################
  110. # generate_url(url, port)
  111. # generates a fully qualified URL for accessing a test url
  112. ############################################################
  113. def generate_url(self, url, port):
  114. return self.server_host + ":" + str(port) + url
  115. ############################################################
  116. # End generate_url
  117. ############################################################
  118. ############################################################
  119. # output_file(test_name, test_type)
  120. # returns the output file for this test_name and test_type
  121. # timestamp/test_type/test_name/raw
  122. ############################################################
  123. def output_file(self, test_name, test_type):
  124. path = os.path.join(self.result_directory, self.timestamp, test_type, test_name, "raw")
  125. try:
  126. os.makedirs(os.path.dirname(path))
  127. except OSError:
  128. pass
  129. return path
  130. ############################################################
  131. # End output_file
  132. ############################################################
  133. ############################################################
  134. # full_results_directory
  135. ############################################################
  136. def full_results_directory(self):
  137. path = os.path.join(self.result_directory, self.timestamp)
  138. try:
  139. os.makedirs(path)
  140. except OSError:
  141. pass
  142. return path
  143. ############################################################
  144. # End output_file
  145. ############################################################
  146. ############################################################
  147. # report_results
  148. ############################################################
  149. def report_results(self, framework, test, results, latency, requests, total_time):
  150. # Try to get the id in the result array if it exists.
  151. try:
  152. framework_id = str(self.results['frameworks'].index(framework.name))
  153. except ValueError:
  154. framework_id = str(framework.sort)
  155. self.results['rawData'][test][framework_id] = results
  156. self.results['weighttpData'][test][framework_id] = dict()
  157. self.results['weighttpData'][test][framework_id]['latency'] = latency
  158. self.results['weighttpData'][test][framework_id]['requests'] = requests
  159. self.results['weighttpData'][test][framework_id]['totalTime'] = total_time
  160. ############################################################
  161. # End report_results
  162. ############################################################
  163. ##########################################################################################
  164. # Private methods
  165. ##########################################################################################
  166. ############################################################
  167. # Gathers all the tests
  168. ############################################################
  169. def __gather_tests(self):
  170. tests = []
  171. # Loop through each directory (we assume we're being run from the benchmarking root)
  172. # and look for the files that signify a benchmark test
  173. for dirname, dirnames, filenames in os.walk('.'):
  174. # Look for the benchmark_config file, this will set up our tests
  175. # It's format looks like this:
  176. #
  177. # {
  178. # "framework": "nodejs",
  179. # "tests": [{
  180. # "default": {
  181. # "setup_file": "setup",
  182. # "json_url": "/json"
  183. # },
  184. # "mysql": {
  185. # "setup_file": "setup",
  186. # "db_url": "/mysql",
  187. # "query_url": "/mysql?queries="
  188. # },
  189. # ...
  190. # }]
  191. # }
  192. if 'benchmark_config' in filenames:
  193. config = None
  194. with open(os.path.join(dirname, 'benchmark_config'), 'r') as config_file:
  195. # Load json file into config object
  196. config = json.load(config_file)
  197. if config == None:
  198. continue
  199. tests = tests + framework_test.parse_config(config, dirname[2:], self)
  200. tests.sort(key=lambda x: x.sort)
  201. return tests
  202. ############################################################
  203. # End __gather_tests
  204. ############################################################
  205. ############################################################
  206. # Makes any necessary changes to the server that should be
  207. # made before running the tests. This involves setting kernal
  208. # settings to allow for more connections, or more file
  209. # descriptiors
  210. #
  211. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  212. ############################################################
  213. def __setup_server(self):
  214. try:
  215. subprocess.check_call("sudo sysctl -w net.core.somaxconn=1024".rsplit(" "))
  216. subprocess.check_call("sudo -s ulimit -n 4096".rsplit(" "))
  217. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  218. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  219. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  220. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  221. except subprocess.CalledProcessError:
  222. return False
  223. ############################################################
  224. # End __setup_server
  225. ############################################################
  226. ############################################################
  227. # Makes any necessary changes to the client machine that
  228. # should be made before running the tests. Is very similar
  229. # to the server setup, but may also include client specific
  230. # changes.
  231. ############################################################
  232. def __setup_client(self):
  233. p = subprocess.Popen(self.ssh_string, stdin=subprocess.PIPE, shell=True)
  234. p.communicate("""
  235. sudo sysctl -w net.core.somaxconn=1024
  236. sudo -s ulimit -n 4096
  237. sudo sysctl net.ipv4.tcp_tw_reuse=1
  238. sudo sysctl net.ipv4.tcp_tw_recycle=1
  239. sudo sysctl -w kernel.shmmax=134217728
  240. sudo sysctl -w kernel.shmall=2097152
  241. """)
  242. ############################################################
  243. # End __setup_client
  244. ############################################################
  245. ############################################################
  246. # __run_tests
  247. # Ensures that the system has all necessary software to run
  248. # the tests. This does not include that software for the individual
  249. # test, but covers software such as curl and weighttp that
  250. # are needed.
  251. ############################################################
  252. def __run_tests(self, tests):
  253. for test in tests:
  254. # If the user specified which tests to run, then
  255. # we can skip over tests that are not in that list
  256. if self.test != None and test.name not in self.test:
  257. continue
  258. # If the test is in the excludes list, we skip it
  259. if self.exclude != None and test.name in self.exclude:
  260. continue
  261. print textwrap.dedent("""
  262. =====================================================
  263. Beginning {name}
  264. -----------------------------------------------------
  265. """.format(name=test.name))
  266. ##########################
  267. # Start this test
  268. ##########################
  269. print textwrap.dedent("""
  270. -----------------------------------------------------
  271. Starting {name}
  272. -----------------------------------------------------
  273. """.format(name=test.name))
  274. try:
  275. p = subprocess.Popen(self.ssh_string, stdin=subprocess.PIPE, shell=True)
  276. p.communicate("""
  277. sudo restart mysql
  278. sudo restart mongodb
  279. """)
  280. time.sleep(10)
  281. result = test.start()
  282. if result != 0:
  283. test.stop()
  284. time.sleep(5)
  285. print "ERROR: Problem starting " + test.name
  286. print textwrap.dedent("""
  287. -----------------------------------------------------
  288. Stopped {name}
  289. -----------------------------------------------------
  290. """.format(name=test.name))
  291. continue
  292. time.sleep(self.sleep)
  293. ##########################
  294. # Verify URLs
  295. ##########################
  296. print textwrap.dedent("""
  297. -----------------------------------------------------
  298. Verifying URLs for {name}
  299. -----------------------------------------------------
  300. """.format(name=test.name))
  301. test.verify_urls()
  302. ##########################
  303. # Benchmark this test
  304. ##########################
  305. if self.mode == "benchmark":
  306. print textwrap.dedent("""
  307. -----------------------------------------------------
  308. Benchmarking {name} ...
  309. -----------------------------------------------------
  310. """.format(name=test.name))
  311. test.benchmark()
  312. ##########################
  313. # Stop this test
  314. ##########################
  315. test.stop()
  316. time.sleep(5)
  317. print textwrap.dedent("""
  318. -----------------------------------------------------
  319. Stopped {name}
  320. -----------------------------------------------------
  321. """.format(name=test.name))
  322. time.sleep(5)
  323. except (KeyboardInterrupt, SystemExit):
  324. test.stop()
  325. print """
  326. -----------------------------------------------------
  327. Cleaning up....
  328. -----------------------------------------------------
  329. """
  330. self.__finish()
  331. sys.exit()
  332. ############################################################
  333. # End __run_tests
  334. ############################################################
  335. ############################################################
  336. # __parse_results
  337. # Ensures that the system has all necessary software to run
  338. # the tests. This does not include that software for the individual
  339. # test, but covers software such as curl and weighttp that
  340. # are needed.
  341. ############################################################
  342. def __parse_results(self, tests):
  343. # Time to create parsed files
  344. # Aggregate JSON file
  345. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  346. f.write(json.dumps(self.results))
  347. # JSON CSV
  348. with open(os.path.join(self.full_results_directory(), "json.csv"), 'wb') as csvfile:
  349. writer = csv.writer(csvfile)
  350. writer.writerow(["Framework"] + self.concurrency_levels)
  351. for key, value in self.results['rawData']['json'].iteritems():
  352. framework = self.results['frameworks'][int(key)]
  353. writer.writerow([framework] + value)
  354. # DB CSV
  355. with open(os.path.join(self.full_results_directory(), "db.csv"), 'wb') as csvfile:
  356. writer = csv.writer(csvfile)
  357. writer.writerow(["Framework"] + self.concurrency_levels)
  358. for key, value in self.results['rawData']['db'].iteritems():
  359. framework = self.results['frameworks'][int(key)]
  360. writer.writerow([framework] + value)
  361. # Query CSV
  362. with open(os.path.join(self.full_results_directory(), "query.csv"), 'wb') as csvfile:
  363. writer = csv.writer(csvfile)
  364. writer.writerow(["Framework"] + self.query_intervals)
  365. for key, value in self.results['rawData']['query'].iteritems():
  366. framework = self.results['frameworks'][int(key)]
  367. writer.writerow([framework] + value)
  368. ############################################################
  369. # End __parse_results
  370. ############################################################
  371. ############################################################
  372. # __finish
  373. ############################################################
  374. def __finish(self):
  375. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  376. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  377. ############################################################
  378. # End __finish
  379. ############################################################
  380. ##########################################################################################
  381. # Constructor
  382. ##########################################################################################
  383. ############################################################
  384. # Initialize the benchmarker. The args are the arguments
  385. # parsed via argparser.
  386. ############################################################
  387. def __init__(self, args):
  388. self.__dict__.update(args)
  389. self.start_time = time.time()
  390. # setup some additional variables
  391. if self.database_host == None: self.database_host = self.client_host
  392. self.result_directory = os.path.join("results", self.name)
  393. if self.parse != None:
  394. self.timestamp = self.parse
  395. else:
  396. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  397. # Setup the concurrency levels array. This array goes from
  398. # starting_concurrency to max concurrency, doubling each time
  399. self.concurrency_levels = []
  400. concurrency = self.starting_concurrency
  401. while concurrency <= self.max_concurrency:
  402. self.concurrency_levels.append(concurrency)
  403. concurrency = concurrency * 2
  404. # Setup query interval array
  405. # starts at 1, and goes up to max_queries, using the query_interval
  406. self.query_intervals = []
  407. queries = 1
  408. while queries <= self.max_queries:
  409. self.query_intervals.append(queries)
  410. if queries == 1:
  411. queries = 0
  412. queries = queries + self.query_interval
  413. # Load the latest data
  414. self.latest = None
  415. try:
  416. with open('latest.json', 'r') as f:
  417. # Load json file into config object
  418. self.latest = json.load(f)
  419. except IOError:
  420. pass
  421. self.results = None
  422. try:
  423. if self.latest != None and self.name in self.latest.keys():
  424. with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  425. # Load json file into config object
  426. self.results = json.load(f)
  427. except IOError:
  428. pass
  429. if self.results == None:
  430. self.results = dict()
  431. self.results['concurrencyLevels'] = self.concurrency_levels
  432. self.results['queryIntervals'] = self.query_intervals
  433. self.results['frameworks'] = [t.name for t in self.__gather_tests()]
  434. self.results['rawData'] = dict()
  435. self.results['rawData']['json'] = dict()
  436. self.results['rawData']['db'] = dict()
  437. self.results['rawData']['query'] = dict()
  438. self.results['weighttpData'] = dict()
  439. self.results['weighttpData']['json'] = dict()
  440. self.results['weighttpData']['db'] = dict()
  441. self.results['weighttpData']['query'] = dict()
  442. else:
  443. for x in self.__gather_tests():
  444. if x.name not in self.results['frameworks']:
  445. self.results['frameworks'] = self.results['frameworks'] + [x.name]
  446. # Setup the ssh command string
  447. self.ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  448. if self.identity_file != None:
  449. self.ssh_string = self.ssh_string + " -i " + self.identity_file
  450. if self.install_software:
  451. install = Installer(self)
  452. install.install_software()
  453. ############################################################
  454. # End __init__
  455. ############################################################