benchmarker.py 20 KB

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