benchmarker.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. import pickle
  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. # Prints the metadata for all the available tests
  30. ############################################################
  31. def run_list_test_metadata(self):
  32. all_tests = self.__gather_tests
  33. all_tests_json = json.dumps(map(lambda test: {
  34. "name": test.name,
  35. "approach": test.approach,
  36. "classification": test.classification,
  37. "database": test.database,
  38. "framework": test.framework,
  39. "language": test.language,
  40. "orm": test.orm,
  41. "platform": test.platform,
  42. "webserver": test.webserver,
  43. "os": test.os,
  44. "database_os": test.database_os,
  45. "display_name": test.display_name,
  46. "notes": test.notes,
  47. "versus": test.versus
  48. }, all_tests))
  49. with open(os.path.join(self.full_results_directory(), "test_metadata.json"), "w") as f:
  50. f.write(all_tests_json)
  51. self.__finish()
  52. ############################################################
  53. # End run_list_test_metadata
  54. ############################################################
  55. ############################################################
  56. # parse_timestamp
  57. # Re-parses the raw data for a given timestamp
  58. ############################################################
  59. def parse_timestamp(self):
  60. all_tests = self.__gather_tests
  61. for test in all_tests:
  62. test.parse_all()
  63. self.__parse_results(all_tests)
  64. self.__finish()
  65. ############################################################
  66. # End parse_timestamp
  67. ############################################################
  68. ############################################################
  69. # Run the tests:
  70. # This process involves setting up the client/server machines
  71. # with any necessary change. Then going through each test,
  72. # running their setup script, verifying the URLs, and
  73. # running benchmarks against them.
  74. ############################################################
  75. def run(self):
  76. ##########################
  77. # Get a list of all known
  78. # tests that we can run.
  79. ##########################
  80. all_tests = self.__gather_tests
  81. ##########################
  82. # Setup client/server
  83. ##########################
  84. print textwrap.dedent("""
  85. =====================================================
  86. Preparing Server, Database, and Client ...
  87. =====================================================
  88. """)
  89. self.__setup_server()
  90. self.__setup_database()
  91. self.__setup_client()
  92. ##########################
  93. # Run tests
  94. ##########################
  95. self.__run_tests(all_tests)
  96. ##########################
  97. # Parse results
  98. ##########################
  99. if self.mode == "benchmark":
  100. print textwrap.dedent("""
  101. =====================================================
  102. Parsing Results ...
  103. =====================================================
  104. """)
  105. self.__parse_results(all_tests)
  106. self.__finish()
  107. ############################################################
  108. # End run
  109. ############################################################
  110. ############################################################
  111. # database_sftp_string(batch_file)
  112. # generates a fully qualified URL for sftp to database
  113. ############################################################
  114. def database_sftp_string(self, batch_file):
  115. sftp_string = "sftp -oStrictHostKeyChecking=no "
  116. if batch_file != None: sftp_string += " -b " + batch_file + " "
  117. if self.database_identity_file != None:
  118. sftp_string += " -i " + self.database_identity_file + " "
  119. return sftp_string + self.database_user + "@" + self.database_host
  120. ############################################################
  121. # End database_sftp_string
  122. ############################################################
  123. ############################################################
  124. # client_sftp_string(batch_file)
  125. # generates a fully qualified URL for sftp to client
  126. ############################################################
  127. def client_sftp_string(self, batch_file):
  128. sftp_string = "sftp -oStrictHostKeyChecking=no "
  129. if batch_file != None: sftp_string += " -b " + batch_file + " "
  130. if self.client_identity_file != None:
  131. sftp_string += " -i " + self.client_identity_file + " "
  132. return sftp_string + self.client_user + "@" + self.client_host
  133. ############################################################
  134. # End client_sftp_string
  135. ############################################################
  136. ############################################################
  137. # generate_url(url, port)
  138. # generates a fully qualified URL for accessing a test url
  139. ############################################################
  140. def generate_url(self, url, port):
  141. return self.server_host + ":" + str(port) + url
  142. ############################################################
  143. # End generate_url
  144. ############################################################
  145. ############################################################
  146. # output_file(test_name, test_type)
  147. # returns the output file for this test_name and test_type
  148. # timestamp/test_type/test_name/raw
  149. ############################################################
  150. def output_file(self, test_name, test_type):
  151. path = os.path.join(self.result_directory, self.timestamp, test_type, test_name, "raw")
  152. try:
  153. os.makedirs(os.path.dirname(path))
  154. except OSError:
  155. pass
  156. return path
  157. ############################################################
  158. # End output_file
  159. ############################################################
  160. ############################################################
  161. # full_results_directory
  162. ############################################################
  163. def full_results_directory(self):
  164. path = os.path.join(self.result_directory, self.timestamp)
  165. try:
  166. os.makedirs(path)
  167. except OSError:
  168. pass
  169. return path
  170. ############################################################
  171. # End output_file
  172. ############################################################
  173. ############################################################
  174. # report_results
  175. ############################################################
  176. def report_results(self, framework, test, results):
  177. if test not in self.results['rawData'].keys():
  178. self.results['rawData'][test] = dict()
  179. self.results['rawData'][test][framework.name] = results
  180. ############################################################
  181. # End report_results
  182. ############################################################
  183. ##########################################################################################
  184. # Private methods
  185. ##########################################################################################
  186. ############################################################
  187. # Gathers all the tests
  188. ############################################################
  189. @property
  190. def __gather_tests(self):
  191. tests = []
  192. # Loop through each directory (we assume we're being run from the benchmarking root)
  193. # and look for the files that signify a benchmark test
  194. for dirname, dirnames, filenames in os.walk('.'):
  195. # Look for the benchmark_config file, this will set up our tests.
  196. # Its format looks like this:
  197. #
  198. # {
  199. # "framework": "nodejs",
  200. # "tests": [{
  201. # "default": {
  202. # "setup_file": "setup",
  203. # "json_url": "/json"
  204. # },
  205. # "mysql": {
  206. # "setup_file": "setup",
  207. # "db_url": "/mysql",
  208. # "query_url": "/mysql?queries="
  209. # },
  210. # ...
  211. # }]
  212. # }
  213. if 'benchmark_config' in filenames:
  214. config = None
  215. config_file_name = os.path.join(dirname, 'benchmark_config')
  216. with open(config_file_name, 'r') as config_file:
  217. # Load json file into config object
  218. try:
  219. config = json.load(config_file)
  220. except:
  221. print("Error loading '%s'." % config_file_name)
  222. raise
  223. if config == None:
  224. continue
  225. tests = tests + framework_test.parse_config(config, dirname[2:], self)
  226. tests.sort(key=lambda x: x.name)
  227. return tests
  228. ############################################################
  229. # End __gather_tests
  230. ############################################################
  231. ############################################################
  232. # Makes any necessary changes to the server that should be
  233. # made before running the tests. This involves setting kernal
  234. # settings to allow for more connections, or more file
  235. # descriptiors
  236. #
  237. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  238. ############################################################
  239. def __setup_server(self):
  240. try:
  241. if os.name == 'nt':
  242. return True
  243. 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"])
  244. subprocess.check_call("sudo sysctl -w net.core.somaxconn=5000".rsplit(" "))
  245. subprocess.check_call("sudo -s ulimit -n 16384".rsplit(" "))
  246. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  247. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  248. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  249. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  250. except subprocess.CalledProcessError:
  251. return False
  252. ############################################################
  253. # End __setup_server
  254. ############################################################
  255. ############################################################
  256. # Makes any necessary changes to the database machine that
  257. # should be made before running the tests. Is very similar
  258. # to the server setup, but may also include database specific
  259. # changes.
  260. ############################################################
  261. def __setup_database(self):
  262. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  263. p.communicate("""
  264. sudo sysctl -w net.core.somaxconn=5000
  265. sudo -s ulimit -n 16384
  266. sudo sysctl net.ipv4.tcp_tw_reuse=1
  267. sudo sysctl net.ipv4.tcp_tw_recycle=1
  268. sudo sysctl -w kernel.shmmax=2147483648
  269. sudo sysctl -w kernel.shmall=2097152
  270. """)
  271. ############################################################
  272. # End __setup_database
  273. ############################################################
  274. ############################################################
  275. # Makes any necessary changes to the client machine that
  276. # should be made before running the tests. Is very similar
  277. # to the server setup, but may also include client specific
  278. # changes.
  279. ############################################################
  280. def __setup_client(self):
  281. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  282. p.communicate("""
  283. sudo sysctl -w net.core.somaxconn=5000
  284. sudo -s ulimit -n 16384
  285. sudo sysctl net.ipv4.tcp_tw_reuse=1
  286. sudo sysctl net.ipv4.tcp_tw_recycle=1
  287. sudo sysctl -w kernel.shmmax=2147483648
  288. sudo sysctl -w kernel.shmall=2097152
  289. """)
  290. ############################################################
  291. # End __setup_client
  292. ############################################################
  293. ############################################################
  294. # __run_tests
  295. # Ensures that the system has all necessary software to run
  296. # the tests. This does not include that software for the individual
  297. # test, but covers software such as curl and weighttp that
  298. # are needed.
  299. ############################################################
  300. def __run_tests(self, tests):
  301. for test in tests:
  302. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  303. # the operating system requirements of this test for the
  304. # application server or the database server don't match
  305. # our current environment
  306. continue
  307. # If the user specified which tests to run, then
  308. # we can skip over tests that are not in that list
  309. if self.test != None and test.name not in self.test:
  310. continue
  311. # If the test is in the excludes list, we skip it
  312. if self.exclude != None and test.name in self.exclude:
  313. continue
  314. # If the test does not contain an implementation of the current test-type, skip it
  315. if self.type != 'all' and not test.contains_type(self.type):
  316. continue
  317. if results['frameworks'] != None and test.name in results['frameworks']:
  318. continue
  319. print textwrap.dedent("""
  320. =====================================================
  321. Beginning {name}
  322. -----------------------------------------------------
  323. """.format(name=test.name))
  324. ##########################
  325. # Start this test
  326. ##########################
  327. print textwrap.dedent("""
  328. -----------------------------------------------------
  329. Starting {name}
  330. -----------------------------------------------------
  331. """.format(name=test.name))
  332. try:
  333. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  334. p.communicate("""
  335. sudo restart mysql
  336. sudo restart mongodb
  337. sudo /etc/init.d/postgresql restart
  338. """)
  339. time.sleep(10)
  340. result = test.start()
  341. if result != 0:
  342. test.stop()
  343. time.sleep(5)
  344. print "ERROR: Problem starting " + test.name
  345. print textwrap.dedent("""
  346. -----------------------------------------------------
  347. Stopped {name}
  348. -----------------------------------------------------
  349. """.format(name=test.name))
  350. continue
  351. time.sleep(self.sleep)
  352. ##########################
  353. # Verify URLs
  354. ##########################
  355. print textwrap.dedent("""
  356. -----------------------------------------------------
  357. Verifying URLs for {name}
  358. -----------------------------------------------------
  359. """.format(name=test.name))
  360. test.verify_urls()
  361. ##########################
  362. # Benchmark this test
  363. ##########################
  364. if self.mode == "benchmark":
  365. print textwrap.dedent("""
  366. -----------------------------------------------------
  367. Benchmarking {name} ...
  368. -----------------------------------------------------
  369. """.format(name=test.name))
  370. test.benchmark()
  371. ##########################
  372. # Stop this test
  373. ##########################
  374. test.stop()
  375. time.sleep(5)
  376. print textwrap.dedent("""
  377. -----------------------------------------------------
  378. Stopped {name}
  379. -----------------------------------------------------
  380. """.format(name=test.name))
  381. time.sleep(5)
  382. ##########################################################
  383. # Save results thus far into toolset/benchmark/latest.json
  384. ##########################################################
  385. print textwrap.dedent("""
  386. ----------------------------------------------------
  387. Saving results through {name}
  388. ----------------------------------------------------
  389. )""".format(name=test.name))
  390. try:
  391. with open(os.path.join('toolset/benchmark/', 'latest.json'), 'w') as f:
  392. f.write(json.dumps(self.results))
  393. except (IOError):
  394. print("Error writing latest.json")
  395. except (OSError, subprocess.CalledProcessError):
  396. print textwrap.dedent("""
  397. -----------------------------------------------------
  398. Subprocess Error {name}
  399. -----------------------------------------------------
  400. """.format(name=test.name))
  401. try:
  402. test.stop()
  403. except (subprocess.CalledProcessError):
  404. print textwrap.dedent("""
  405. -----------------------------------------------------
  406. Subprocess Error: Test .stop() raised exception {name}
  407. -----------------------------------------------------
  408. """.format(name=test.name))
  409. except (KeyboardInterrupt, SystemExit):
  410. test.stop()
  411. print """
  412. -----------------------------------------------------
  413. Cleaning up....
  414. -----------------------------------------------------
  415. """
  416. self.__finish()
  417. sys.exit()
  418. ############################################################
  419. # End __run_tests
  420. ############################################################
  421. ############################################################
  422. # __parse_results
  423. # Ensures that the system has all necessary software to run
  424. # the tests. This does not include that software for the individual
  425. # test, but covers software such as curl and weighttp that
  426. # are needed.
  427. ############################################################
  428. def __parse_results(self, tests):
  429. # Time to create parsed files
  430. # Aggregate JSON file
  431. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  432. f.write(json.dumps(self.results))
  433. # JSON CSV
  434. # with open(os.path.join(self.full_results_directory(), "json.csv"), 'wb') as csvfile:
  435. # writer = csv.writer(csvfile)
  436. # writer.writerow(["Framework"] + self.concurrency_levels)
  437. # for key, value in self.results['rawData']['json'].iteritems():
  438. # framework = self.results['frameworks'][int(key)]
  439. # writer.writerow([framework] + value)
  440. # DB CSV
  441. #with open(os.path.join(self.full_results_directory(), "db.csv"), 'wb') as csvfile:
  442. # writer = csv.writer(csvfile)
  443. # writer.writerow(["Framework"] + self.concurrency_levels)
  444. # for key, value in self.results['rawData']['db'].iteritems():
  445. # framework = self.results['frameworks'][int(key)]
  446. # writer.writerow([framework] + value)
  447. # Query CSV
  448. #with open(os.path.join(self.full_results_directory(), "query.csv"), 'wb') as csvfile:
  449. # writer = csv.writer(csvfile)
  450. # writer.writerow(["Framework"] + self.query_intervals)
  451. # for key, value in self.results['rawData']['query'].iteritems():
  452. # framework = self.results['frameworks'][int(key)]
  453. # writer.writerow([framework] + value)
  454. # Fortune CSV
  455. #with open(os.path.join(self.full_results_directory(), "fortune.csv"), 'wb') as csvfile:
  456. # writer = csv.writer(csvfile)
  457. # writer.writerow(["Framework"] + self.query_intervals)
  458. # if 'fortune' in self.results['rawData'].keys():
  459. # for key, value in self.results['rawData']['fortune'].iteritems():
  460. # framework = self.results['frameworks'][int(key)]
  461. # writer.writerow([framework] + value)
  462. ############################################################
  463. # End __parse_results
  464. ############################################################
  465. ############################################################
  466. # __finish
  467. ############################################################
  468. def __finish(self):
  469. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  470. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  471. ############################################################
  472. # End __finish
  473. ############################################################
  474. ##########################################################################################
  475. # Constructor
  476. ##########################################################################################
  477. ############################################################
  478. # Initialize the benchmarker. The args are the arguments
  479. # parsed via argparser.
  480. ############################################################
  481. def __init__(self, args):
  482. self.__dict__.update(args)
  483. self.start_time = time.time()
  484. # setup some additional variables
  485. if self.database_user == None: self.database_user = self.client_user
  486. if self.database_host == None: self.database_host = self.client_host
  487. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  488. self.result_directory = os.path.join("results", self.name)
  489. if self.parse != None:
  490. self.timestamp = self.parse
  491. else:
  492. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  493. # Setup the concurrency levels array. This array goes from
  494. # starting_concurrency to max concurrency, doubling each time
  495. self.concurrency_levels = []
  496. concurrency = self.starting_concurrency
  497. while concurrency <= self.max_concurrency:
  498. self.concurrency_levels.append(concurrency)
  499. concurrency = concurrency * 2
  500. # Setup query interval array
  501. # starts at 1, and goes up to max_queries, using the query_interval
  502. self.query_intervals = []
  503. queries = 1
  504. while queries <= self.max_queries:
  505. self.query_intervals.append(queries)
  506. if queries == 1:
  507. queries = 0
  508. queries = queries + self.query_interval
  509. # Load the latest data
  510. self.latest = None
  511. try:
  512. with open('toolset/benchmark/latest.json', 'r') as f:
  513. # Load json file into config object
  514. self.latest = json.load(f)
  515. except IOError:
  516. pass
  517. self.results = None
  518. try:
  519. if self.latest != None and self.name in self.latest.keys():
  520. with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  521. # Load json file into config object
  522. self.results = json.load(f)
  523. except IOError:
  524. pass
  525. if self.results == None:
  526. self.results = dict()
  527. self.results['concurrencyLevels'] = self.concurrency_levels
  528. self.results['queryIntervals'] = self.query_intervals
  529. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  530. self.results['duration'] = self.duration
  531. self.results['rawData'] = dict()
  532. self.results['rawData']['json'] = dict()
  533. self.results['rawData']['db'] = dict()
  534. self.results['rawData']['query'] = dict()
  535. self.results['rawData']['fortune'] = dict()
  536. self.results['rawData']['update'] = dict()
  537. self.results['rawData']['plaintext'] = dict()
  538. else:
  539. #for x in self.__gather_tests():
  540. # if x.name not in self.results['frameworks']:
  541. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  542. # Always overwrite framework list
  543. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  544. # Setup the ssh command string
  545. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  546. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  547. if self.database_identity_file != None:
  548. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  549. if self.client_identity_file != None:
  550. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  551. if self.install_software:
  552. install = Installer(self)
  553. install.install_software()
  554. ############################################################
  555. # End __init__
  556. ############################################################