benchmarker.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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. ## Check if wrk (and wrk-pipeline) is installed and executable, if not, raise an exception
  95. #if not (os.access("/usr/local/bin/wrk", os.X_OK) and os.access("/usr/local/bin/wrk-pipeline", os.X_OK)):
  96. # raise Exception("wrk and/or wrk-pipeline are not properly installed. Not running tests.")
  97. ##########################
  98. # Run tests
  99. ##########################
  100. print textwrap.dedent("""
  101. =====================================================
  102. Running Tests ...
  103. =====================================================
  104. """)
  105. self.__run_tests(all_tests)
  106. ##########################
  107. # Parse results
  108. ##########################
  109. if self.mode == "benchmark":
  110. print textwrap.dedent("""
  111. =====================================================
  112. Parsing Results ...
  113. =====================================================
  114. """)
  115. self.__parse_results(all_tests)
  116. self.__finish()
  117. ############################################################
  118. # End run
  119. ############################################################
  120. ############################################################
  121. # database_sftp_string(batch_file)
  122. # generates a fully qualified URL for sftp to database
  123. ############################################################
  124. def database_sftp_string(self, batch_file):
  125. sftp_string = "sftp -oStrictHostKeyChecking=no "
  126. if batch_file != None: sftp_string += " -b " + batch_file + " "
  127. if self.database_identity_file != None:
  128. sftp_string += " -i " + self.database_identity_file + " "
  129. return sftp_string + self.database_user + "@" + self.database_host
  130. ############################################################
  131. # End database_sftp_string
  132. ############################################################
  133. ############################################################
  134. # client_sftp_string(batch_file)
  135. # generates a fully qualified URL for sftp to client
  136. ############################################################
  137. def client_sftp_string(self, batch_file):
  138. sftp_string = "sftp -oStrictHostKeyChecking=no "
  139. if batch_file != None: sftp_string += " -b " + batch_file + " "
  140. if self.client_identity_file != None:
  141. sftp_string += " -i " + self.client_identity_file + " "
  142. return sftp_string + self.client_user + "@" + self.client_host
  143. ############################################################
  144. # End client_sftp_string
  145. ############################################################
  146. ############################################################
  147. # generate_url(url, port)
  148. # generates a fully qualified URL for accessing a test url
  149. ############################################################
  150. def generate_url(self, url, port):
  151. return self.server_host + ":" + str(port) + url
  152. ############################################################
  153. # End generate_url
  154. ############################################################
  155. ############################################################
  156. # get_output_file(test_name, test_type)
  157. # returns the output file name for this test_name and
  158. # test_type timestamp/test_type/test_name/raw
  159. ############################################################
  160. def get_output_file(self, test_name, test_type):
  161. return os.path.join(self.result_directory, self.timestamp, test_type, test_name, "raw")
  162. ############################################################
  163. # End get_output_file
  164. ############################################################
  165. ############################################################
  166. # output_file(test_name, test_type)
  167. # returns the output file for this test_name and test_type
  168. # timestamp/test_type/test_name/raw
  169. ############################################################
  170. def output_file(self, test_name, test_type):
  171. path = self.get_output_file(test_name, test_type)
  172. try:
  173. os.makedirs(os.path.dirname(path))
  174. except OSError:
  175. pass
  176. return path
  177. ############################################################
  178. # End output_file
  179. ############################################################
  180. ############################################################
  181. # get_warning_file(test_name, test_type)
  182. # returns the output file name for this test_name and
  183. # test_type timestamp/test_type/test_name/raw
  184. ############################################################
  185. def get_warning_file(self, test_name, test_type):
  186. return os.path.join(self.result_directory, self.timestamp, test_type, test_name, "warn")
  187. ############################################################
  188. # End get_warning_file
  189. ############################################################
  190. ############################################################
  191. # warning_file(test_name, test_type)
  192. # returns the warning file for this test_name and test_type
  193. # timestamp/test_type/test_name/raw
  194. ############################################################
  195. def warning_file(self, test_name, test_type):
  196. path = self.get_warning_file(test_name, test_type)
  197. try:
  198. os.makedirs(os.path.dirname(path))
  199. except OSError:
  200. pass
  201. return path
  202. ############################################################
  203. # End warning_file
  204. ############################################################
  205. ############################################################
  206. # full_results_directory
  207. ############################################################
  208. def full_results_directory(self):
  209. path = os.path.join(self.result_directory, self.timestamp)
  210. try:
  211. os.makedirs(path)
  212. except OSError:
  213. pass
  214. return path
  215. ############################################################
  216. # End full_results_directory
  217. ############################################################
  218. ############################################################
  219. # Latest intermediate results dirctory
  220. ############################################################
  221. def latest_results_directory(self):
  222. path = os.path.join(self.result_directory,"latest")
  223. try:
  224. os.makedirs(path)
  225. except OSError:
  226. pass
  227. return path
  228. ############################################################
  229. # report_results
  230. ############################################################
  231. def report_results(self, framework, test, results):
  232. if test not in self.results['rawData'].keys():
  233. self.results['rawData'][test] = dict()
  234. # If results has a size from the parse, then it succeeded.
  235. if results:
  236. self.results['rawData'][test][framework.name] = results
  237. # This may already be set for single-tests
  238. if framework.name not in self.results['succeeded'][test]:
  239. self.results['succeeded'][test].append(framework.name)
  240. else:
  241. # This may already be set for single-tests
  242. if framework.name not in self.results['failed'][test]:
  243. self.results['failed'][test].append(framework.name)
  244. ############################################################
  245. # End report_results
  246. ############################################################
  247. ##########################################################################################
  248. # Private methods
  249. ##########################################################################################
  250. ############################################################
  251. # Gathers all the tests
  252. ############################################################
  253. @property
  254. def __gather_tests(self):
  255. tests = []
  256. # Loop through each directory (we assume we're being run from the benchmarking root)
  257. # and look for the files that signify a benchmark test
  258. for dirname, dirnames, filenames in os.walk('.'):
  259. # Look for the benchmark_config file, this will set up our tests.
  260. # Its format looks like this:
  261. #
  262. # {
  263. # "framework": "nodejs",
  264. # "tests": [{
  265. # "default": {
  266. # "setup_file": "setup",
  267. # "json_url": "/json"
  268. # },
  269. # "mysql": {
  270. # "setup_file": "setup",
  271. # "db_url": "/mysql",
  272. # "query_url": "/mysql?queries="
  273. # },
  274. # ...
  275. # }]
  276. # }
  277. if 'benchmark_config' in filenames:
  278. config = None
  279. config_file_name = os.path.join(dirname, 'benchmark_config')
  280. with open(config_file_name, 'r') as config_file:
  281. # Load json file into config object
  282. try:
  283. config = json.load(config_file)
  284. except:
  285. print("Error loading '%s'." % config_file_name)
  286. raise
  287. if config == None:
  288. continue
  289. test = framework_test.parse_config(config, dirname[2:], self)
  290. # If the user specified which tests to run, then
  291. # we can skip over tests that are not in that list
  292. if self.test == None:
  293. tests = tests + test
  294. else:
  295. for atest in test:
  296. if atest.name in self.test:
  297. tests.append(atest)
  298. tests.sort(key=lambda x: x.name)
  299. return tests
  300. ############################################################
  301. # End __gather_tests
  302. ############################################################
  303. ############################################################
  304. # Gathers all the frameworks
  305. ############################################################
  306. def __gather_frameworks(self):
  307. frameworks = []
  308. # Loop through each directory (we assume we're being run from the benchmarking root)
  309. for dirname, dirnames, filenames in os.walk('.'):
  310. # Look for the benchmark_config file, this will contain our framework name
  311. # It's format looks like this:
  312. #
  313. # {
  314. # "framework": "nodejs",
  315. # "tests": [{
  316. # "default": {
  317. # "setup_file": "setup",
  318. # "json_url": "/json"
  319. # },
  320. # "mysql": {
  321. # "setup_file": "setup",
  322. # "db_url": "/mysql",
  323. # "query_url": "/mysql?queries="
  324. # },
  325. # ...
  326. # }]
  327. # }
  328. if 'benchmark_config' in filenames:
  329. config = None
  330. with open(os.path.join(dirname, 'benchmark_config'), 'r') as config_file:
  331. # Load json file into config object
  332. config = json.load(config_file)
  333. if config == None:
  334. continue
  335. frameworks.append(str(config['framework']))
  336. return frameworks
  337. ############################################################
  338. # End __gather_frameworks
  339. ############################################################
  340. ############################################################
  341. # Makes any necessary changes to the server that should be
  342. # made before running the tests. This involves setting kernal
  343. # settings to allow for more connections, or more file
  344. # descriptiors
  345. #
  346. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  347. ############################################################
  348. def __setup_server(self):
  349. try:
  350. if os.name == 'nt':
  351. return True
  352. 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"])
  353. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  354. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  355. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  356. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  357. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  358. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  359. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  360. except subprocess.CalledProcessError:
  361. return False
  362. ############################################################
  363. # End __setup_server
  364. ############################################################
  365. ############################################################
  366. # Makes any necessary changes to the database machine that
  367. # should be made before running the tests. Is very similar
  368. # to the server setup, but may also include database specific
  369. # changes.
  370. ############################################################
  371. def __setup_database(self):
  372. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  373. p.communicate("""
  374. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  375. sudo sysctl -w net.core.somaxconn=65535
  376. sudo -s ulimit -n 65535
  377. sudo sysctl net.ipv4.tcp_tw_reuse=1
  378. sudo sysctl net.ipv4.tcp_tw_recycle=1
  379. sudo sysctl -w kernel.shmmax=2147483648
  380. sudo sysctl -w kernel.shmall=2097152
  381. """)
  382. ############################################################
  383. # End __setup_database
  384. ############################################################
  385. ############################################################
  386. # Makes any necessary changes to the client machine that
  387. # should be made before running the tests. Is very similar
  388. # to the server setup, but may also include client specific
  389. # changes.
  390. ############################################################
  391. def __setup_client(self):
  392. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  393. p.communicate("""
  394. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  395. sudo sysctl -w net.core.somaxconn=65535
  396. sudo -s ulimit -n 65535
  397. sudo sysctl net.ipv4.tcp_tw_reuse=1
  398. sudo sysctl net.ipv4.tcp_tw_recycle=1
  399. sudo sysctl -w kernel.shmmax=2147483648
  400. sudo sysctl -w kernel.shmall=2097152
  401. """)
  402. ############################################################
  403. # End __setup_client
  404. ############################################################
  405. ############################################################
  406. # __run_tests
  407. #
  408. # 2013-10-02 ASB Calls each test passed in tests to
  409. # __run_test in a separate process. Each
  410. # test is given a set amount of time and if
  411. # kills the child process (and subsequently
  412. # all of its child processes). Uses
  413. # multiprocessing module.
  414. ############################################################
  415. def __run_tests(self, tests):
  416. logging.debug("Start __run_tests.")
  417. logging.debug("__name__ = %s",__name__)
  418. if self.os.lower() == 'windows':
  419. logging.debug("Executing __run_tests on Windows")
  420. for test in tests:
  421. self.__run_test(test)
  422. else:
  423. logging.debug("Executing __run_tests on Linux")
  424. # These features do not work on Windows
  425. for test in tests:
  426. if __name__ == 'benchmark.benchmarker':
  427. print textwrap.dedent("""
  428. -----------------------------------------------------
  429. Running Test: {name} ...
  430. -----------------------------------------------------
  431. """.format(name=test.name))
  432. test_process = Process(target=self.__run_test, args=(test,))
  433. test_process.start()
  434. test_process.join(self.run_test_timeout_seconds)
  435. if(test_process.is_alive()):
  436. logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
  437. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  438. test_process.terminate()
  439. logging.debug("End __run_tests.")
  440. ############################################################
  441. # End __run_tests
  442. ############################################################
  443. ############################################################
  444. # __run_test
  445. # 2013-10-02 ASB Previously __run_tests. This code now only
  446. # processes a single test.
  447. #
  448. # Ensures that the system has all necessary software to run
  449. # the tests. This does not include that software for the individual
  450. # test, but covers software such as curl and weighttp that
  451. # are needed.
  452. ############################################################
  453. def __run_test(self, test):
  454. try:
  455. os.makedirs(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name)))
  456. except:
  457. pass
  458. with open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'out.txt'), 'w') as out, \
  459. open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'err.txt'), 'w') as err:
  460. if hasattr(test, 'skip'):
  461. if test.skip.lower() == "true":
  462. out.write("Test {name} benchmark_config specifies to skip this test. Skipping.\n".format(name=test.name))
  463. return
  464. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  465. # the operating system requirements of this test for the
  466. # application server or the database server don't match
  467. # our current environment
  468. out.write("OS or Database OS specified in benchmark_config does not match the current environment. Skipping.\n")
  469. return
  470. # If the test is in the excludes list, we skip it
  471. if self.exclude != None and test.name in self.exclude:
  472. out.write("Test {name} has been added to the excludes list. Skipping.\n".format(name=test.name))
  473. return
  474. # If the test does not contain an implementation of the current test-type, skip it
  475. if self.type != 'all' and not test.contains_type(self.type):
  476. out.write("Test type {type} does not contain an implementation of the current test-type. Skipping.\n".format(type=self.type))
  477. return
  478. out.write("test.os.lower() = {os} test.database_os.lower() = {dbos}\n".format(os=test.os.lower(),dbos=test.database_os.lower()))
  479. out.write("self.results['frameworks'] != None: {val}\n".format(val=str(self.results['frameworks'] != None)))
  480. out.write("test.name: {name}\n".format(name=str(test.name)))
  481. out.write("self.results['completed']: {completed}\n".format(completed=str(self.results['completed'])))
  482. if self.results['frameworks'] != None and test.name in self.results['completed']:
  483. out.write('Framework {name} found in latest saved data. Skipping.\n'.format(name=str(test.name)))
  484. return
  485. out.flush()
  486. out.write( textwrap.dedent("""
  487. =====================================================
  488. Beginning {name}
  489. -----------------------------------------------------
  490. """.format(name=test.name)) )
  491. out.flush()
  492. ##########################
  493. # Start this test
  494. ##########################
  495. out.write( textwrap.dedent("""
  496. -----------------------------------------------------
  497. Starting {name}
  498. -----------------------------------------------------
  499. """.format(name=test.name)) )
  500. out.flush()
  501. try:
  502. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=err, shell=True)
  503. p.communicate("""
  504. sudo restart mysql
  505. sudo restart mongodb
  506. sudo /etc/init.d/postgresql restart
  507. """)
  508. time.sleep(10)
  509. if self.__is_port_bound(test.port):
  510. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  511. err.write( textwrap.dedent("""
  512. ---------------------------------------------------------
  513. Error: Port {port} is not available before start {name}
  514. ---------------------------------------------------------
  515. """.format(name=test.name, port=str(test.port))) )
  516. err.flush()
  517. return
  518. result = test.start(out, err)
  519. if result != 0:
  520. test.stop(out, err)
  521. time.sleep(5)
  522. err.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  523. err.write( textwrap.dedent("""
  524. -----------------------------------------------------
  525. Stopped {name}
  526. -----------------------------------------------------
  527. """.format(name=test.name)) )
  528. err.flush()
  529. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  530. return
  531. time.sleep(self.sleep)
  532. ##########################
  533. # Verify URLs
  534. ##########################
  535. out.write( textwrap.dedent("""
  536. -----------------------------------------------------
  537. Verifying URLs for {name}
  538. -----------------------------------------------------
  539. """.format(name=test.name)) )
  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. ############################################################