benchmarker.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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. #try:
  302. # runattempts_file = open('run_attempts.pickle','b')
  303. # runattempts = pickle.load(runattempts_file)
  304. #except:
  305. # runattempts = list()
  306. for test in tests:
  307. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  308. # the operating system requirements of this test for the
  309. # application server or the database server don't match
  310. # our current environment
  311. continue
  312. # If the user specified which tests to run, then
  313. # we can skip over tests that are not in that list
  314. if self.test != None and test.name not in self.test:
  315. continue
  316. # If the test is in the excludes list, we skip it
  317. if self.exclude != None and test.name in self.exclude:
  318. continue
  319. # If the test does not contain an implementation of the current test-type, skip it
  320. if self.type != 'all' and not test.contains_type(self.type):
  321. continue
  322. #if runattempts != None and test.name in runattempts:
  323. # continue
  324. #runattempts.append(test.name)
  325. print textwrap.dedent("""
  326. =====================================================
  327. Beginning {name}
  328. -----------------------------------------------------
  329. """.format(name=test.name))
  330. ##########################
  331. # Start this test
  332. ##########################
  333. print textwrap.dedent("""
  334. -----------------------------------------------------
  335. Starting {name}
  336. -----------------------------------------------------
  337. """.format(name=test.name))
  338. try:
  339. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  340. p.communicate("""
  341. sudo restart mysql
  342. sudo restart mongodb
  343. sudo /etc/init.d/postgresql restart
  344. """)
  345. time.sleep(10)
  346. result = test.start()
  347. if result != 0:
  348. test.stop()
  349. time.sleep(5)
  350. print "ERROR: Problem starting " + test.name
  351. print textwrap.dedent("""
  352. -----------------------------------------------------
  353. Stopped {name}
  354. -----------------------------------------------------
  355. """.format(name=test.name))
  356. continue
  357. time.sleep(self.sleep)
  358. ##########################
  359. # Verify URLs
  360. ##########################
  361. print textwrap.dedent("""
  362. -----------------------------------------------------
  363. Verifying URLs for {name}
  364. -----------------------------------------------------
  365. """.format(name=test.name))
  366. test.verify_urls()
  367. ##########################
  368. # Benchmark this test
  369. ##########################
  370. if self.mode == "benchmark":
  371. print textwrap.dedent("""
  372. -----------------------------------------------------
  373. Benchmarking {name} ...
  374. -----------------------------------------------------
  375. """.format(name=test.name))
  376. test.benchmark()
  377. ##########################
  378. # Stop this test
  379. ##########################
  380. test.stop()
  381. time.sleep(5)
  382. print textwrap.dedent("""
  383. -----------------------------------------------------
  384. Stopped {name}
  385. -----------------------------------------------------
  386. """.format(name=test.name))
  387. time.sleep(5)
  388. except (OSError, subprocess.CalledProcessError):
  389. print textwrap.dedent("""
  390. -----------------------------------------------------
  391. Subprocess Error {name}
  392. -----------------------------------------------------
  393. """.format(name=test.name))
  394. except (KeyboardInterrupt, SystemExit):
  395. #pickle.dump(runattempts, 'run_attempts.pickle')
  396. #runattempts_file.close()
  397. test.stop()
  398. print """
  399. -----------------------------------------------------
  400. Cleaning up....
  401. -----------------------------------------------------
  402. """
  403. self.__finish()
  404. sys.exit()
  405. #runattempts = list()
  406. #pickle.dump(runattempts, 'run_attempts.pickle')
  407. #runattempts_file.close()
  408. ############################################################
  409. # End __run_tests
  410. ############################################################
  411. ############################################################
  412. # __parse_results
  413. # Ensures that the system has all necessary software to run
  414. # the tests. This does not include that software for the individual
  415. # test, but covers software such as curl and weighttp that
  416. # are needed.
  417. ############################################################
  418. def __parse_results(self, tests):
  419. # Time to create parsed files
  420. # Aggregate JSON file
  421. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  422. f.write(json.dumps(self.results))
  423. # JSON CSV
  424. # with open(os.path.join(self.full_results_directory(), "json.csv"), 'wb') as csvfile:
  425. # writer = csv.writer(csvfile)
  426. # writer.writerow(["Framework"] + self.concurrency_levels)
  427. # for key, value in self.results['rawData']['json'].iteritems():
  428. # framework = self.results['frameworks'][int(key)]
  429. # writer.writerow([framework] + value)
  430. # DB CSV
  431. #with open(os.path.join(self.full_results_directory(), "db.csv"), 'wb') as csvfile:
  432. # writer = csv.writer(csvfile)
  433. # writer.writerow(["Framework"] + self.concurrency_levels)
  434. # for key, value in self.results['rawData']['db'].iteritems():
  435. # framework = self.results['frameworks'][int(key)]
  436. # writer.writerow([framework] + value)
  437. # Query CSV
  438. #with open(os.path.join(self.full_results_directory(), "query.csv"), 'wb') as csvfile:
  439. # writer = csv.writer(csvfile)
  440. # writer.writerow(["Framework"] + self.query_intervals)
  441. # for key, value in self.results['rawData']['query'].iteritems():
  442. # framework = self.results['frameworks'][int(key)]
  443. # writer.writerow([framework] + value)
  444. # Fortune CSV
  445. #with open(os.path.join(self.full_results_directory(), "fortune.csv"), 'wb') as csvfile:
  446. # writer = csv.writer(csvfile)
  447. # writer.writerow(["Framework"] + self.query_intervals)
  448. # if 'fortune' in self.results['rawData'].keys():
  449. # for key, value in self.results['rawData']['fortune'].iteritems():
  450. # framework = self.results['frameworks'][int(key)]
  451. # writer.writerow([framework] + value)
  452. ############################################################
  453. # End __parse_results
  454. ############################################################
  455. ############################################################
  456. # __finish
  457. ############################################################
  458. def __finish(self):
  459. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  460. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  461. ############################################################
  462. # End __finish
  463. ############################################################
  464. ##########################################################################################
  465. # Constructor
  466. ##########################################################################################
  467. ############################################################
  468. # Initialize the benchmarker. The args are the arguments
  469. # parsed via argparser.
  470. ############################################################
  471. def __init__(self, args):
  472. self.__dict__.update(args)
  473. self.start_time = time.time()
  474. # setup some additional variables
  475. if self.database_user == None: self.database_user = self.client_user
  476. if self.database_host == None: self.database_host = self.client_host
  477. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  478. self.result_directory = os.path.join("results", self.name)
  479. if self.parse != None:
  480. self.timestamp = self.parse
  481. else:
  482. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  483. # Setup the concurrency levels array. This array goes from
  484. # starting_concurrency to max concurrency, doubling each time
  485. self.concurrency_levels = []
  486. concurrency = self.starting_concurrency
  487. while concurrency <= self.max_concurrency:
  488. self.concurrency_levels.append(concurrency)
  489. concurrency = concurrency * 2
  490. # Setup query interval array
  491. # starts at 1, and goes up to max_queries, using the query_interval
  492. self.query_intervals = []
  493. queries = 1
  494. while queries <= self.max_queries:
  495. self.query_intervals.append(queries)
  496. if queries == 1:
  497. queries = 0
  498. queries = queries + self.query_interval
  499. # Load the latest data
  500. self.latest = None
  501. try:
  502. with open('toolset/benchmark/latest.json', 'r') as f:
  503. # Load json file into config object
  504. self.latest = json.load(f)
  505. except IOError:
  506. pass
  507. self.results = None
  508. try:
  509. if self.latest != None and self.name in self.latest.keys():
  510. with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  511. # Load json file into config object
  512. self.results = json.load(f)
  513. except IOError:
  514. pass
  515. if self.results == None:
  516. self.results = dict()
  517. self.results['concurrencyLevels'] = self.concurrency_levels
  518. self.results['queryIntervals'] = self.query_intervals
  519. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  520. self.results['duration'] = self.duration
  521. self.results['rawData'] = dict()
  522. self.results['rawData']['json'] = dict()
  523. self.results['rawData']['db'] = dict()
  524. self.results['rawData']['query'] = dict()
  525. self.results['rawData']['fortune'] = dict()
  526. self.results['rawData']['update'] = dict()
  527. self.results['rawData']['plaintext'] = dict()
  528. else:
  529. #for x in self.__gather_tests():
  530. # if x.name not in self.results['frameworks']:
  531. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  532. # Always overwrite framework list
  533. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  534. # Setup the ssh command string
  535. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  536. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  537. if self.database_identity_file != None:
  538. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  539. if self.client_identity_file != None:
  540. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  541. if self.install_software:
  542. install = Installer(self)
  543. install.install_software()
  544. ############################################################
  545. # End __init__
  546. ############################################################