benchmarker.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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 logging
  12. import socket
  13. from multiprocessing import Process
  14. from datetime import datetime
  15. class Benchmarker:
  16. ##########################################################################################
  17. # Public methods
  18. ##########################################################################################
  19. ############################################################
  20. # Prints all the available tests
  21. ############################################################
  22. def run_list_tests(self):
  23. all_tests = self.__gather_tests
  24. for test in all_tests:
  25. print test.name
  26. self.__finish()
  27. ############################################################
  28. # End run_list_tests
  29. ############################################################
  30. ############################################################
  31. # Prints the metadata for all the available tests
  32. ############################################################
  33. def run_list_test_metadata(self):
  34. all_tests = self.__gather_tests
  35. all_tests_json = json.dumps(map(lambda test: {
  36. "name": test.name,
  37. "approach": test.approach,
  38. "classification": test.classification,
  39. "database": test.database,
  40. "framework": test.framework,
  41. "language": test.language,
  42. "orm": test.orm,
  43. "platform": test.platform,
  44. "webserver": test.webserver,
  45. "os": test.os,
  46. "database_os": test.database_os,
  47. "display_name": test.display_name,
  48. "notes": test.notes,
  49. "versus": test.versus
  50. }, all_tests))
  51. with open(os.path.join(self.full_results_directory(), "test_metadata.json"), "w") as f:
  52. f.write(all_tests_json)
  53. self.__finish()
  54. ############################################################
  55. # End run_list_test_metadata
  56. ############################################################
  57. ############################################################
  58. # parse_timestamp
  59. # Re-parses the raw data for a given timestamp
  60. ############################################################
  61. def parse_timestamp(self):
  62. all_tests = self.__gather_tests
  63. for test in all_tests:
  64. test.parse_all()
  65. self.__parse_results(all_tests)
  66. self.__finish()
  67. ############################################################
  68. # End parse_timestamp
  69. ############################################################
  70. ############################################################
  71. # Run the tests:
  72. # This process involves setting up the client/server machines
  73. # with any necessary change. Then going through each test,
  74. # running their setup script, verifying the URLs, and
  75. # running benchmarks against them.
  76. ############################################################
  77. def run(self):
  78. ##########################
  79. # Get a list of all known
  80. # tests that we can run.
  81. ##########################
  82. all_tests = self.__gather_tests
  83. ##########################
  84. # Setup client/server
  85. ##########################
  86. print textwrap.dedent("""
  87. =====================================================
  88. Preparing Server, Database, and Client ...
  89. =====================================================
  90. """)
  91. self.__setup_server()
  92. self.__setup_database()
  93. self.__setup_client()
  94. ##########################
  95. # Run tests
  96. ##########################
  97. self.__run_tests(all_tests)
  98. ##########################
  99. # Parse results
  100. ##########################
  101. if self.mode == "benchmark":
  102. print textwrap.dedent("""
  103. =====================================================
  104. Parsing Results ...
  105. =====================================================
  106. """)
  107. self.__parse_results(all_tests)
  108. self.__finish()
  109. ############################################################
  110. # End run
  111. ############################################################
  112. ############################################################
  113. # database_sftp_string(batch_file)
  114. # generates a fully qualified URL for sftp to database
  115. ############################################################
  116. def database_sftp_string(self, batch_file):
  117. sftp_string = "sftp -oStrictHostKeyChecking=no "
  118. if batch_file != None: sftp_string += " -b " + batch_file + " "
  119. if self.database_identity_file != None:
  120. sftp_string += " -i " + self.database_identity_file + " "
  121. return sftp_string + self.database_user + "@" + self.database_host
  122. ############################################################
  123. # End database_sftp_string
  124. ############################################################
  125. ############################################################
  126. # client_sftp_string(batch_file)
  127. # generates a fully qualified URL for sftp to client
  128. ############################################################
  129. def client_sftp_string(self, batch_file):
  130. sftp_string = "sftp -oStrictHostKeyChecking=no "
  131. if batch_file != None: sftp_string += " -b " + batch_file + " "
  132. if self.client_identity_file != None:
  133. sftp_string += " -i " + self.client_identity_file + " "
  134. return sftp_string + self.client_user + "@" + self.client_host
  135. ############################################################
  136. # End client_sftp_string
  137. ############################################################
  138. ############################################################
  139. # generate_url(url, port)
  140. # generates a fully qualified URL for accessing a test url
  141. ############################################################
  142. def generate_url(self, url, port):
  143. return self.server_host + ":" + str(port) + url
  144. ############################################################
  145. # End generate_url
  146. ############################################################
  147. ############################################################
  148. # output_file(test_name, test_type)
  149. # returns the output file for this test_name and test_type
  150. # timestamp/test_type/test_name/raw
  151. ############################################################
  152. def output_file(self, test_name, test_type):
  153. path = os.path.join(self.result_directory, self.timestamp, test_type, test_name, "raw")
  154. try:
  155. os.makedirs(os.path.dirname(path))
  156. except OSError:
  157. pass
  158. return path
  159. ############################################################
  160. # End output_file
  161. ############################################################
  162. ############################################################
  163. # full_results_directory
  164. ############################################################
  165. def full_results_directory(self):
  166. path = os.path.join(self.result_directory, self.timestamp)
  167. try:
  168. os.makedirs(path)
  169. except OSError:
  170. pass
  171. return path
  172. ############################################################
  173. # End output_file
  174. ############################################################
  175. ############################################################
  176. # Latest intermediate results dirctory
  177. ############################################################
  178. def latest_results_directory(self):
  179. path = os.path.join(self.result_directory,"latest")
  180. try:
  181. os.makedirs(path)
  182. except OSError:
  183. pass
  184. return path
  185. ############################################################
  186. # report_results
  187. ############################################################
  188. def report_results(self, framework, test, results):
  189. if test not in self.results['rawData'].keys():
  190. self.results['rawData'][test] = dict()
  191. self.results['rawData'][test][framework.name] = results
  192. ############################################################
  193. # End report_results
  194. ############################################################
  195. ##########################################################################################
  196. # Private methods
  197. ##########################################################################################
  198. ############################################################
  199. # Gathers all the tests
  200. ############################################################
  201. @property
  202. def __gather_tests(self):
  203. tests = []
  204. # Loop through each directory (we assume we're being run from the benchmarking root)
  205. # and look for the files that signify a benchmark test
  206. for dirname, dirnames, filenames in os.walk('.'):
  207. # Look for the benchmark_config file, this will set up our tests.
  208. # Its format looks like this:
  209. #
  210. # {
  211. # "framework": "nodejs",
  212. # "tests": [{
  213. # "default": {
  214. # "setup_file": "setup",
  215. # "json_url": "/json"
  216. # },
  217. # "mysql": {
  218. # "setup_file": "setup",
  219. # "db_url": "/mysql",
  220. # "query_url": "/mysql?queries="
  221. # },
  222. # ...
  223. # }]
  224. # }
  225. if 'benchmark_config' in filenames:
  226. config = None
  227. config_file_name = os.path.join(dirname, 'benchmark_config')
  228. with open(config_file_name, 'r') as config_file:
  229. # Load json file into config object
  230. try:
  231. config = json.load(config_file)
  232. except:
  233. print("Error loading '%s'." % config_file_name)
  234. raise
  235. if config == None:
  236. continue
  237. tests = tests + framework_test.parse_config(config, dirname[2:], self)
  238. tests.sort(key=lambda x: x.name)
  239. return tests
  240. ############################################################
  241. # End __gather_tests
  242. ############################################################
  243. ############################################################
  244. # Gathers all the frameworks
  245. ############################################################
  246. def __gather_frameworks(self):
  247. frameworks = []
  248. # Loop through each directory (we assume we're being run from the benchmarking root)
  249. for dirname, dirnames, filenames in os.walk('.'):
  250. # Look for the benchmark_config file, this will contain our framework name
  251. # It's format looks like this:
  252. #
  253. # {
  254. # "framework": "nodejs",
  255. # "tests": [{
  256. # "default": {
  257. # "setup_file": "setup",
  258. # "json_url": "/json"
  259. # },
  260. # "mysql": {
  261. # "setup_file": "setup",
  262. # "db_url": "/mysql",
  263. # "query_url": "/mysql?queries="
  264. # },
  265. # ...
  266. # }]
  267. # }
  268. if 'benchmark_config' in filenames:
  269. config = None
  270. with open(os.path.join(dirname, 'benchmark_config'), 'r') as config_file:
  271. # Load json file into config object
  272. config = json.load(config_file)
  273. if config == None:
  274. continue
  275. frameworks.append(str(config['framework']))
  276. return frameworks
  277. ############################################################
  278. # End __gather_frameworks
  279. ############################################################
  280. ############################################################
  281. # Makes any necessary changes to the server that should be
  282. # made before running the tests. This involves setting kernal
  283. # settings to allow for more connections, or more file
  284. # descriptiors
  285. #
  286. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  287. ############################################################
  288. def __setup_server(self):
  289. try:
  290. if os.name == 'nt':
  291. return True
  292. 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"])
  293. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  294. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  295. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  296. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  297. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  298. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  299. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  300. except subprocess.CalledProcessError:
  301. return False
  302. ############################################################
  303. # End __setup_server
  304. ############################################################
  305. ############################################################
  306. # Makes any necessary changes to the database machine that
  307. # should be made before running the tests. Is very similar
  308. # to the server setup, but may also include database specific
  309. # changes.
  310. ############################################################
  311. def __setup_database(self):
  312. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  313. p.communicate("""
  314. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  315. sudo sysctl -w net.core.somaxconn=65535
  316. sudo -s ulimit -n 65535
  317. sudo sysctl net.ipv4.tcp_tw_reuse=1
  318. sudo sysctl net.ipv4.tcp_tw_recycle=1
  319. sudo sysctl -w kernel.shmmax=2147483648
  320. sudo sysctl -w kernel.shmall=2097152
  321. """)
  322. ############################################################
  323. # End __setup_database
  324. ############################################################
  325. ############################################################
  326. # Makes any necessary changes to the client machine that
  327. # should be made before running the tests. Is very similar
  328. # to the server setup, but may also include client specific
  329. # changes.
  330. ############################################################
  331. def __setup_client(self):
  332. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  333. p.communicate("""
  334. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  335. sudo sysctl -w net.core.somaxconn=65535
  336. sudo -s ulimit -n 65535
  337. sudo sysctl net.ipv4.tcp_tw_reuse=1
  338. sudo sysctl net.ipv4.tcp_tw_recycle=1
  339. sudo sysctl -w kernel.shmmax=2147483648
  340. sudo sysctl -w kernel.shmall=2097152
  341. """)
  342. ############################################################
  343. # End __setup_client
  344. ############################################################
  345. ############################################################
  346. # __run_tests
  347. #
  348. # 2013-10-02 ASB Calls each test passed in tests to
  349. # __run_test in a separate process. Each
  350. # test is given a set amount of time and if
  351. # kills the child process (and subsequently
  352. # all of its child processes). Uses
  353. # multiprocessing module.
  354. ############################################################
  355. def __run_tests(self, tests):
  356. logging.debug("Start __run_tests.")
  357. logging.debug("__name__ = %s",__name__)
  358. if self.os.lower() == 'windows':
  359. logging.debug("Executing __run_tests on Windows")
  360. for test in tests:
  361. self.__run_test(test)
  362. else:
  363. logging.debug("Executing __run_tests on Linux")
  364. # These features do not work on Windows
  365. for test in tests:
  366. if __name__ == 'benchmark.benchmarker':
  367. test_process = Process(target=self.__run_test, args=(test,))
  368. test_process.start()
  369. test_process.join(self.run_test_timeout_seconds)
  370. if(test_process.is_alive()):
  371. logging.debug("Child process for %s is still alive. Terminating.",test.name)
  372. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  373. test_process.terminate()
  374. logging.debug("End __run_tests.")
  375. ############################################################
  376. # End __run_tests
  377. ############################################################
  378. ############################################################
  379. # __run_test
  380. # 2013-10-02 ASB Previously __run_tests. This code now only
  381. # processes a single test.
  382. #
  383. # Ensures that the system has all necessary software to run
  384. # the tests. This does not include that software for the individual
  385. # test, but covers software such as curl and weighttp that
  386. # are needed.
  387. ############################################################
  388. def __run_test(self, test):
  389. # If the user specified which tests to run, then
  390. # we can skip over tests that are not in that list
  391. if self.test != None and test.name not in self.test:
  392. return
  393. if hasattr(test, 'skip'):
  394. if test.skip.lower() == "true":
  395. logging.info("Test %s benchmark_config specifies to skip this test. Skipping.", test.name)
  396. return
  397. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  398. # the operating system requirements of this test for the
  399. # application server or the database server don't match
  400. # our current environment
  401. logging.info("OS or Database OS specified in benchmark_config does not match the current environment. Skipping.")
  402. return
  403. # If the test is in the excludes list, we skip it
  404. if self.exclude != None and test.name in self.exclude:
  405. logging.info("Test %s has been added to the excludes list. Skipping.", test.name)
  406. return
  407. # If the test does not contain an implementation of the current test-type, skip it
  408. if self.type != 'all' and not test.contains_type(self.type):
  409. logging.info("Test type %s does not contain an implementation of the current test-type. Skipping", self.type)
  410. return
  411. logging.debug("test.os.lower() = %s test.database_os.lower() = %s",test.os.lower(),test.database_os.lower())
  412. logging.debug("self.results['frameworks'] != None: " + str(self.results['frameworks'] != None))
  413. logging.debug("test.name: " + str(test.name))
  414. logging.debug("self.results['completed']: " + str(self.results['completed']))
  415. if self.results['frameworks'] != None and test.name in self.results['completed']:
  416. logging.info('Framework %s found in latest saved data. Skipping.',str(test.name))
  417. return
  418. print textwrap.dedent("""
  419. =====================================================
  420. Beginning {name}
  421. -----------------------------------------------------
  422. """.format(name=test.name))
  423. ##########################
  424. # Start this test
  425. ##########################
  426. print textwrap.dedent("""
  427. -----------------------------------------------------
  428. Starting {name}
  429. -----------------------------------------------------
  430. """.format(name=test.name))
  431. try:
  432. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  433. p.communicate("""
  434. sudo restart mysql
  435. sudo restart mongodb
  436. sudo /etc/init.d/postgresql restart
  437. """)
  438. time.sleep(10)
  439. if self.__is_port_bound(test.port):
  440. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  441. print textwrap.dedent("""
  442. ---------------------------------------------------------
  443. Error: Port {port} is not available before start {name}
  444. ---------------------------------------------------------
  445. """.format(name=test.name, port=str(test.port)))
  446. return
  447. result = test.start()
  448. if result != 0:
  449. test.stop()
  450. time.sleep(5)
  451. print "ERROR: Problem starting " + test.name
  452. print textwrap.dedent("""
  453. -----------------------------------------------------
  454. Stopped {name}
  455. -----------------------------------------------------
  456. """.format(name=test.name))
  457. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  458. return
  459. time.sleep(self.sleep)
  460. ##########################
  461. # Verify URLs
  462. ##########################
  463. print textwrap.dedent("""
  464. -----------------------------------------------------
  465. Verifying URLs for {name}
  466. -----------------------------------------------------
  467. """.format(name=test.name))
  468. test.verify_urls()
  469. ##########################
  470. # Benchmark this test
  471. ##########################
  472. if self.mode == "benchmark":
  473. print textwrap.dedent("""
  474. -----------------------------------------------------
  475. Benchmarking {name} ...
  476. -----------------------------------------------------
  477. """.format(name=test.name))
  478. test.benchmark()
  479. ##########################
  480. # Stop this test
  481. ##########################
  482. test.stop()
  483. time.sleep(5)
  484. if self.__is_port_bound(test.port):
  485. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  486. print textwrap.dedent("""
  487. -----------------------------------------------------
  488. Error: Port {port} was not released by stop {name}
  489. -----------------------------------------------------
  490. """.format(name=test.name, port=str(test.port)))
  491. return
  492. print textwrap.dedent("""
  493. -----------------------------------------------------
  494. Stopped {name}
  495. -----------------------------------------------------
  496. """.format(name=test.name))
  497. time.sleep(5)
  498. ##########################################################
  499. # Save results thus far into toolset/benchmark/latest.json
  500. ##########################################################
  501. print textwrap.dedent("""
  502. ----------------------------------------------------
  503. Saving results through {name}
  504. ----------------------------------------------------
  505. """.format(name=test.name))
  506. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  507. except (OSError, IOError, subprocess.CalledProcessError):
  508. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  509. print textwrap.dedent("""
  510. -----------------------------------------------------
  511. Subprocess Error {name}
  512. -----------------------------------------------------
  513. """.format(name=test.name))
  514. try:
  515. test.stop()
  516. except (subprocess.CalledProcessError):
  517. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  518. print textwrap.dedent("""
  519. -----------------------------------------------------
  520. Subprocess Error: Test .stop() raised exception {name}
  521. -----------------------------------------------------
  522. """.format(name=test.name))
  523. except (KeyboardInterrupt, SystemExit):
  524. test.stop()
  525. print """
  526. -----------------------------------------------------
  527. Cleaning up....
  528. -----------------------------------------------------
  529. """
  530. self.__finish()
  531. sys.exit()
  532. ############################################################
  533. # End __run_tests
  534. ############################################################
  535. ############################################################
  536. # __is_port_bound
  537. # Check if the requested port is available. If it
  538. # isn't available, then a previous test probably didn't
  539. # shutdown properly.
  540. ############################################################
  541. def __is_port_bound(self, port):
  542. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  543. try:
  544. # Try to bind to all IP addresses, this port
  545. s.bind(("", port))
  546. # If we get here, we were able to bind successfully,
  547. # which means the port is free.
  548. except:
  549. # If we get an exception, it might be because the port is still bound
  550. # which would be bad, or maybe it is a privileged port (<1024) and we
  551. # are not running as root, or maybe the server is gone, but sockets are
  552. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  553. # connect.
  554. try:
  555. s.connect(("127.0.0.1", port))
  556. # If we get here, we were able to connect to something, which means
  557. # that the port is still bound.
  558. return True
  559. except:
  560. # An exception means that we couldn't connect, so a server probably
  561. # isn't still running on the port.
  562. pass
  563. finally:
  564. s.close()
  565. return False
  566. ############################################################
  567. # End __is_port_bound
  568. ############################################################
  569. ############################################################
  570. # __parse_results
  571. # Ensures that the system has all necessary software to run
  572. # the tests. This does not include that software for the individual
  573. # test, but covers software such as curl and weighttp that
  574. # are needed.
  575. ############################################################
  576. def __parse_results(self, tests):
  577. # Run the method to get the commmit count of each framework.
  578. self.__count_commits()
  579. # Call the method which counts the sloc for each framework
  580. self.__count_sloc()
  581. # Time to create parsed files
  582. # Aggregate JSON file
  583. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  584. f.write(json.dumps(self.results))
  585. ############################################################
  586. # End __parse_results
  587. ############################################################
  588. #############################################################
  589. # __count_sloc
  590. # This is assumed to be run from the benchmark root directory
  591. #############################################################
  592. def __count_sloc(self):
  593. all_frameworks = self.__gather_frameworks()
  594. jsonResult = {}
  595. for framework in all_frameworks:
  596. try:
  597. command = "cloc --list-file=" + framework['directory'] + "/source_code --yaml"
  598. lineCount = subprocess.check_output(command, shell=True)
  599. # Find the last instance of the word 'code' in the yaml output. This should
  600. # be the line count for the sum of all listed files or just the line count
  601. # for the last file in the case where there's only one file listed.
  602. lineCount = lineCount[lineCount.rfind('code'):len(lineCount)]
  603. lineCount = lineCount.strip('code: ')
  604. lineCount = lineCount[0:lineCount.rfind('comment')]
  605. jsonResult[framework['name']] = int(lineCount)
  606. except:
  607. continue
  608. self.results['rawData']['slocCounts'] = jsonResult
  609. ############################################################
  610. # End __count_sloc
  611. ############################################################
  612. ############################################################
  613. # __count_commits
  614. ############################################################
  615. def __count_commits(self):
  616. all_frameworks = self.__gather_frameworks()
  617. jsonResult = {}
  618. for framework in all_frameworks:
  619. try:
  620. command = "git rev-list HEAD -- " + framework + " | sort -u | wc -l"
  621. commitCount = subprocess.check_output(command, shell=True)
  622. jsonResult[framework] = int(commitCount)
  623. except:
  624. continue
  625. self.results['rawData']['commitCounts'] = jsonResult
  626. self.commits = jsonResult
  627. ############################################################
  628. # End __count_commits
  629. ############################################################
  630. ############################################################
  631. # __write_intermediate_results
  632. ############################################################
  633. def __write_intermediate_results(self,test_name,status_message):
  634. try:
  635. self.results["completed"][test_name] = status_message
  636. with open(os.path.join(self.latest_results_directory, 'results.json'), 'w') as f:
  637. f.write(json.dumps(self.results))
  638. except (IOError):
  639. logging.error("Error writing results.json")
  640. ############################################################
  641. # End __write_intermediate_results
  642. ############################################################
  643. ############################################################
  644. # __finish
  645. ############################################################
  646. def __finish(self):
  647. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  648. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  649. ############################################################
  650. # End __finish
  651. ############################################################
  652. ##########################################################################################
  653. # Constructor
  654. ##########################################################################################
  655. ############################################################
  656. # Initialize the benchmarker. The args are the arguments
  657. # parsed via argparser.
  658. ############################################################
  659. def __init__(self, args):
  660. self.__dict__.update(args)
  661. self.start_time = time.time()
  662. self.run_test_timeout_seconds = 3600
  663. # setup logging
  664. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  665. # setup some additional variables
  666. if self.database_user == None: self.database_user = self.client_user
  667. if self.database_host == None: self.database_host = self.client_host
  668. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  669. # setup results and latest_results directories
  670. self.result_directory = os.path.join("results", self.name)
  671. self.latest_results_directory = self.latest_results_directory()
  672. if self.parse != None:
  673. self.timestamp = self.parse
  674. else:
  675. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  676. # Setup the concurrency levels array. This array goes from
  677. # starting_concurrency to max concurrency, doubling each time
  678. self.concurrency_levels = []
  679. concurrency = self.starting_concurrency
  680. while concurrency <= self.max_concurrency:
  681. self.concurrency_levels.append(concurrency)
  682. concurrency = concurrency * 2
  683. # Setup query interval array
  684. # starts at 1, and goes up to max_queries, using the query_interval
  685. self.query_intervals = []
  686. queries = 1
  687. while queries <= self.max_queries:
  688. self.query_intervals.append(queries)
  689. if queries == 1:
  690. queries = 0
  691. queries = queries + self.query_interval
  692. # Load the latest data
  693. #self.latest = None
  694. #try:
  695. # with open('toolset/benchmark/latest.json', 'r') as f:
  696. # # Load json file into config object
  697. # self.latest = json.load(f)
  698. # logging.info("toolset/benchmark/latest.json loaded to self.latest")
  699. # logging.debug("contents of latest.json: " + str(json.dumps(self.latest)))
  700. #except IOError:
  701. # logging.warn("IOError on attempting to read toolset/benchmark/latest.json")
  702. #
  703. #self.results = None
  704. #try:
  705. # if self.latest != None and self.name in self.latest.keys():
  706. # with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  707. # # Load json file into config object
  708. # self.results = json.load(f)
  709. #except IOError:
  710. # pass
  711. self.results = None
  712. try:
  713. with open(os.path.join(self.latest_results_directory, 'results.json'), 'r') as f:
  714. #Load json file into results object
  715. self.results = json.load(f)
  716. except IOError:
  717. logging.warn("results.json for test %s not found.",self.name)
  718. if self.results == None:
  719. self.results = dict()
  720. self.results['name'] = self.name
  721. self.results['concurrencyLevels'] = self.concurrency_levels
  722. self.results['queryIntervals'] = self.query_intervals
  723. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  724. self.results['duration'] = self.duration
  725. self.results['rawData'] = dict()
  726. self.results['rawData']['json'] = dict()
  727. self.results['rawData']['db'] = dict()
  728. self.results['rawData']['query'] = dict()
  729. self.results['rawData']['fortune'] = dict()
  730. self.results['rawData']['update'] = dict()
  731. self.results['rawData']['plaintext'] = dict()
  732. self.results['completed'] = dict()
  733. else:
  734. #for x in self.__gather_tests():
  735. # if x.name not in self.results['frameworks']:
  736. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  737. # Always overwrite framework list
  738. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  739. # Setup the ssh command string
  740. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  741. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  742. if self.database_identity_file != None:
  743. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  744. if self.client_identity_file != None:
  745. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  746. if self.install_software:
  747. install = Installer(self)
  748. install.install_software()
  749. ############################################################
  750. # End __init__
  751. ############################################################