benchmarker.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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):
  150. if test not in self.results['rawData'].keys():
  151. self.results['rawData'][test] = dict()
  152. self.results['rawData'][test][framework.sort] = results
  153. ############################################################
  154. # End report_results
  155. ############################################################
  156. ##########################################################################################
  157. # Private methods
  158. ##########################################################################################
  159. ############################################################
  160. # Gathers all the tests
  161. ############################################################
  162. def __gather_tests(self):
  163. tests = []
  164. # Loop through each directory (we assume we're being run from the benchmarking root)
  165. # and look for the files that signify a benchmark test
  166. for dirname, dirnames, filenames in os.walk('.'):
  167. # Look for the benchmark_config file, this will set up our tests
  168. # It's format looks like this:
  169. #
  170. # {
  171. # "framework": "nodejs",
  172. # "tests": [{
  173. # "default": {
  174. # "setup_file": "setup",
  175. # "json_url": "/json"
  176. # },
  177. # "mysql": {
  178. # "setup_file": "setup",
  179. # "db_url": "/mysql",
  180. # "query_url": "/mysql?queries="
  181. # },
  182. # ...
  183. # }]
  184. # }
  185. if 'benchmark_config' in filenames:
  186. config = None
  187. with open(os.path.join(dirname, 'benchmark_config'), 'r') as config_file:
  188. # Load json file into config object
  189. config = json.load(config_file)
  190. if config == None:
  191. continue
  192. tests = tests + framework_test.parse_config(config, dirname[2:], self)
  193. tests.sort(key=lambda x: x.sort)
  194. return tests
  195. ############################################################
  196. # End __gather_tests
  197. ############################################################
  198. ############################################################
  199. # Makes any necessary changes to the server that should be
  200. # made before running the tests. This involves setting kernal
  201. # settings to allow for more connections, or more file
  202. # descriptiors
  203. #
  204. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  205. ############################################################
  206. def __setup_server(self):
  207. try:
  208. subprocess.check_call("sudo sysctl -w net.core.somaxconn=1024".rsplit(" "))
  209. subprocess.check_call("sudo -s ulimit -n 8192".rsplit(" "))
  210. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  211. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  212. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  213. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  214. except subprocess.CalledProcessError:
  215. return False
  216. ############################################################
  217. # End __setup_server
  218. ############################################################
  219. ############################################################
  220. # Makes any necessary changes to the client machine that
  221. # should be made before running the tests. Is very similar
  222. # to the server setup, but may also include client specific
  223. # changes.
  224. ############################################################
  225. def __setup_client(self):
  226. p = subprocess.Popen(self.ssh_string, stdin=subprocess.PIPE, shell=True)
  227. p.communicate("""
  228. sudo sysctl -w net.core.somaxconn=1024
  229. sudo -s ulimit -n 8192
  230. sudo sysctl net.ipv4.tcp_tw_reuse=1
  231. sudo sysctl net.ipv4.tcp_tw_recycle=1
  232. sudo sysctl -w kernel.shmmax=2147483648
  233. sudo sysctl -w kernel.shmall=2097152
  234. """)
  235. ############################################################
  236. # End __setup_client
  237. ############################################################
  238. ############################################################
  239. # __run_tests
  240. # Ensures that the system has all necessary software to run
  241. # the tests. This does not include that software for the individual
  242. # test, but covers software such as curl and weighttp that
  243. # are needed.
  244. ############################################################
  245. def __run_tests(self, tests):
  246. for test in tests:
  247. # If the user specified which tests to run, then
  248. # we can skip over tests that are not in that list
  249. if self.test != None and test.name not in self.test:
  250. continue
  251. # If the test is in the excludes list, we skip it
  252. if self.exclude != None and test.name in self.exclude:
  253. continue
  254. # If the test does not contain an implementation of the current test-type, skip it
  255. if self.type != 'all' and not test.contains_type(self.type):
  256. continue
  257. print textwrap.dedent("""
  258. =====================================================
  259. Beginning {name}
  260. -----------------------------------------------------
  261. """.format(name=test.name))
  262. ##########################
  263. # Start this test
  264. ##########################
  265. print textwrap.dedent("""
  266. -----------------------------------------------------
  267. Starting {name}
  268. -----------------------------------------------------
  269. """.format(name=test.name))
  270. try:
  271. p = subprocess.Popen(self.ssh_string, stdin=subprocess.PIPE, shell=True)
  272. p.communicate("""
  273. sudo restart mysql
  274. sudo restart mongodb
  275. """)
  276. time.sleep(10)
  277. result = test.start()
  278. if result != 0:
  279. test.stop()
  280. time.sleep(5)
  281. print "ERROR: Problem starting " + test.name
  282. print textwrap.dedent("""
  283. -----------------------------------------------------
  284. Stopped {name}
  285. -----------------------------------------------------
  286. """.format(name=test.name))
  287. continue
  288. time.sleep(self.sleep)
  289. ##########################
  290. # Verify URLs
  291. ##########################
  292. print textwrap.dedent("""
  293. -----------------------------------------------------
  294. Verifying URLs for {name}
  295. -----------------------------------------------------
  296. """.format(name=test.name))
  297. test.verify_urls()
  298. ##########################
  299. # Benchmark this test
  300. ##########################
  301. if self.mode == "benchmark":
  302. print textwrap.dedent("""
  303. -----------------------------------------------------
  304. Benchmarking {name} ...
  305. -----------------------------------------------------
  306. """.format(name=test.name))
  307. test.benchmark()
  308. ##########################
  309. # Stop this test
  310. ##########################
  311. test.stop()
  312. time.sleep(5)
  313. print textwrap.dedent("""
  314. -----------------------------------------------------
  315. Stopped {name}
  316. -----------------------------------------------------
  317. """.format(name=test.name))
  318. time.sleep(5)
  319. except (KeyboardInterrupt, SystemExit):
  320. test.stop()
  321. print """
  322. -----------------------------------------------------
  323. Cleaning up....
  324. -----------------------------------------------------
  325. """
  326. self.__finish()
  327. sys.exit()
  328. ############################################################
  329. # End __run_tests
  330. ############################################################
  331. ############################################################
  332. # __parse_results
  333. # Ensures that the system has all necessary software to run
  334. # the tests. This does not include that software for the individual
  335. # test, but covers software such as curl and weighttp that
  336. # are needed.
  337. ############################################################
  338. def __parse_results(self, tests):
  339. # Time to create parsed files
  340. # Aggregate JSON file
  341. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  342. f.write(json.dumps(self.results))
  343. # JSON CSV
  344. # with open(os.path.join(self.full_results_directory(), "json.csv"), 'wb') as csvfile:
  345. # writer = csv.writer(csvfile)
  346. # writer.writerow(["Framework"] + self.concurrency_levels)
  347. # for key, value in self.results['rawData']['json'].iteritems():
  348. # framework = self.results['frameworks'][int(key)]
  349. # writer.writerow([framework] + value)
  350. # DB CSV
  351. #with open(os.path.join(self.full_results_directory(), "db.csv"), 'wb') as csvfile:
  352. # writer = csv.writer(csvfile)
  353. # writer.writerow(["Framework"] + self.concurrency_levels)
  354. # for key, value in self.results['rawData']['db'].iteritems():
  355. # framework = self.results['frameworks'][int(key)]
  356. # writer.writerow([framework] + value)
  357. # Query CSV
  358. #with open(os.path.join(self.full_results_directory(), "query.csv"), 'wb') as csvfile:
  359. # writer = csv.writer(csvfile)
  360. # writer.writerow(["Framework"] + self.query_intervals)
  361. # for key, value in self.results['rawData']['query'].iteritems():
  362. # framework = self.results['frameworks'][int(key)]
  363. # writer.writerow([framework] + value)
  364. # Fortune CSV
  365. #with open(os.path.join(self.full_results_directory(), "fortune.csv"), 'wb') as csvfile:
  366. # writer = csv.writer(csvfile)
  367. # writer.writerow(["Framework"] + self.query_intervals)
  368. # if 'fortune' in self.results['rawData'].keys():
  369. # for key, value in self.results['rawData']['fortune'].iteritems():
  370. # framework = self.results['frameworks'][int(key)]
  371. # writer.writerow([framework] + value)
  372. ############################################################
  373. # End __parse_results
  374. ############################################################
  375. ############################################################
  376. # __finish
  377. ############################################################
  378. def __finish(self):
  379. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  380. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  381. ############################################################
  382. # End __finish
  383. ############################################################
  384. ##########################################################################################
  385. # Constructor
  386. ##########################################################################################
  387. ############################################################
  388. # Initialize the benchmarker. The args are the arguments
  389. # parsed via argparser.
  390. ############################################################
  391. def __init__(self, args):
  392. self.__dict__.update(args)
  393. self.start_time = time.time()
  394. # setup some additional variables
  395. if self.database_host == None: self.database_host = self.client_host
  396. self.result_directory = os.path.join("results", self.name)
  397. if self.parse != None:
  398. self.timestamp = self.parse
  399. else:
  400. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  401. # Setup the concurrency levels array. This array goes from
  402. # starting_concurrency to max concurrency, doubling each time
  403. self.concurrency_levels = []
  404. concurrency = self.starting_concurrency
  405. while concurrency <= self.max_concurrency:
  406. self.concurrency_levels.append(concurrency)
  407. concurrency = concurrency * 2
  408. # Setup query interval array
  409. # starts at 1, and goes up to max_queries, using the query_interval
  410. self.query_intervals = []
  411. queries = 1
  412. while queries <= self.max_queries:
  413. self.query_intervals.append(queries)
  414. if queries == 1:
  415. queries = 0
  416. queries = queries + self.query_interval
  417. # Load the latest data
  418. self.latest = None
  419. try:
  420. with open('latest.json', 'r') as f:
  421. # Load json file into config object
  422. self.latest = json.load(f)
  423. except IOError:
  424. pass
  425. self.results = None
  426. try:
  427. if self.latest != None and self.name in self.latest.keys():
  428. with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  429. # Load json file into config object
  430. self.results = json.load(f)
  431. except IOError:
  432. pass
  433. if self.results == None:
  434. self.results = dict()
  435. self.results['concurrencyLevels'] = self.concurrency_levels
  436. self.results['queryIntervals'] = self.query_intervals
  437. self.results['frameworks'] = [t.name for t in self.__gather_tests()]
  438. self.results['rawData'] = dict()
  439. self.results['rawData']['json'] = dict()
  440. self.results['rawData']['db'] = dict()
  441. self.results['rawData']['query'] = dict()
  442. self.results['rawData']['fortune'] = dict()
  443. self.results['rawData']['update'] = dict()
  444. else:
  445. #for x in self.__gather_tests():
  446. # if x.name not in self.results['frameworks']:
  447. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  448. # Always overwrite framework list
  449. self.results['frameworks'] = [t.name for t in self.__gather_tests()]
  450. # Setup the ssh command string
  451. self.ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  452. if self.identity_file != None:
  453. self.ssh_string = self.ssh_string + " -i " + self.identity_file
  454. if self.install_software:
  455. install = Installer(self)
  456. install.install_software()
  457. ############################################################
  458. # End __init__
  459. ############################################################