benchmarker.py 38 KB

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