benchmarker.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. subprocess.check_call(["sudo","bash","-c","cd /sys/devices/system/cpu; ls -d cpu[0-9]*|while read x; do echo performance > $x/cpufreq/scaling_governor; done"])
  356. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  357. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  358. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  359. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  360. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  361. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  362. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  363. except subprocess.CalledProcessError:
  364. return False
  365. ############################################################
  366. # End __setup_server
  367. ############################################################
  368. ############################################################
  369. # Makes any necessary changes to the database machine that
  370. # should be made before running the tests. Is very similar
  371. # to the server setup, but may also include database specific
  372. # changes.
  373. ############################################################
  374. def __setup_database(self):
  375. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  376. p.communicate("""
  377. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  378. sudo sysctl -w net.core.somaxconn=65535
  379. sudo -s ulimit -n 65535
  380. sudo sysctl net.ipv4.tcp_tw_reuse=1
  381. sudo sysctl net.ipv4.tcp_tw_recycle=1
  382. sudo sysctl -w kernel.shmmax=2147483648
  383. sudo sysctl -w kernel.shmall=2097152
  384. """)
  385. ############################################################
  386. # End __setup_database
  387. ############################################################
  388. ############################################################
  389. # Makes any necessary changes to the client machine that
  390. # should be made before running the tests. Is very similar
  391. # to the server setup, but may also include client specific
  392. # changes.
  393. ############################################################
  394. def __setup_client(self):
  395. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  396. p.communicate("""
  397. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  398. sudo sysctl -w net.core.somaxconn=65535
  399. sudo -s ulimit -n 65535
  400. sudo sysctl net.ipv4.tcp_tw_reuse=1
  401. sudo sysctl net.ipv4.tcp_tw_recycle=1
  402. sudo sysctl -w kernel.shmmax=2147483648
  403. sudo sysctl -w kernel.shmall=2097152
  404. """)
  405. ############################################################
  406. # End __setup_client
  407. ############################################################
  408. ############################################################
  409. # __run_tests
  410. #
  411. # 2013-10-02 ASB Calls each test passed in tests to
  412. # __run_test in a separate process. Each
  413. # test is given a set amount of time and if
  414. # kills the child process (and subsequently
  415. # all of its child processes). Uses
  416. # multiprocessing module.
  417. ############################################################
  418. def __run_tests(self, tests):
  419. logging.debug("Start __run_tests.")
  420. logging.debug("__name__ = %s",__name__)
  421. if self.os.lower() == 'windows':
  422. logging.debug("Executing __run_tests on Windows")
  423. for test in tests:
  424. self.__run_test(test)
  425. else:
  426. logging.debug("Executing __run_tests on Linux")
  427. # These features do not work on Windows
  428. for test in tests:
  429. if __name__ == 'benchmark.benchmarker':
  430. print textwrap.dedent("""
  431. -----------------------------------------------------
  432. Running Test: {name} ...
  433. -----------------------------------------------------
  434. """.format(name=test.name))
  435. test_process = Process(target=self.__run_test, args=(test,))
  436. test_process.start()
  437. test_process.join(self.run_test_timeout_seconds)
  438. if(test_process.is_alive()):
  439. logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
  440. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  441. test_process.terminate()
  442. logging.debug("End __run_tests.")
  443. ############################################################
  444. # End __run_tests
  445. ############################################################
  446. ############################################################
  447. # __run_test
  448. # 2013-10-02 ASB Previously __run_tests. This code now only
  449. # processes a single test.
  450. #
  451. # Ensures that the system has all necessary software to run
  452. # the tests. This does not include that software for the individual
  453. # test, but covers software such as curl and weighttp that
  454. # are needed.
  455. ############################################################
  456. def __run_test(self, test):
  457. try:
  458. os.makedirs(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name)))
  459. except:
  460. pass
  461. with open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'out.txt'), 'w') as out, \
  462. open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'err.txt'), 'w') as err:
  463. if hasattr(test, 'skip'):
  464. if test.skip.lower() == "true":
  465. out.write("Test {name} benchmark_config specifies to skip this test. Skipping.\n".format(name=test.name))
  466. return
  467. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  468. # the operating system requirements of this test for the
  469. # application server or the database server don't match
  470. # our current environment
  471. out.write("OS or Database OS specified in benchmark_config does not match the current environment. Skipping.\n")
  472. return
  473. # If the test is in the excludes list, we skip it
  474. if self.exclude != None and test.name in self.exclude:
  475. out.write("Test {name} has been added to the excludes list. Skipping.\n".format(name=test.name))
  476. return
  477. # If the test does not contain an implementation of the current test-type, skip it
  478. if self.type != 'all' and not test.contains_type(self.type):
  479. out.write("Test type {type} does not contain an implementation of the current test-type. Skipping.\n".format(type=self.type))
  480. return
  481. out.write("test.os.lower() = {os} test.database_os.lower() = {dbos}\n".format(os=test.os.lower(),dbos=test.database_os.lower()))
  482. out.write("self.results['frameworks'] != None: {val}\n".format(val=str(self.results['frameworks'] != None)))
  483. out.write("test.name: {name}\n".format(name=str(test.name)))
  484. out.write("self.results['completed']: {completed}\n".format(completed=str(self.results['completed'])))
  485. if self.results['frameworks'] != None and test.name in self.results['completed']:
  486. out.write('Framework {name} found in latest saved data. Skipping.\n'.format(name=str(test.name)))
  487. return
  488. out.flush()
  489. out.write( textwrap.dedent("""
  490. =====================================================
  491. Beginning {name}
  492. -----------------------------------------------------
  493. """.format(name=test.name)) )
  494. out.flush()
  495. ##########################
  496. # Start this test
  497. ##########################
  498. out.write( textwrap.dedent("""
  499. -----------------------------------------------------
  500. Starting {name}
  501. -----------------------------------------------------
  502. """.format(name=test.name)) )
  503. out.flush()
  504. try:
  505. if test.requires_database():
  506. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=err, shell=True)
  507. p.communicate("""
  508. sudo restart mysql
  509. sudo restart mongodb
  510. sudo /etc/init.d/postgresql restart
  511. """)
  512. time.sleep(10)
  513. if self.__is_port_bound(test.port):
  514. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  515. err.write( textwrap.dedent("""
  516. ---------------------------------------------------------
  517. Error: Port {port} is not available before start {name}
  518. ---------------------------------------------------------
  519. """.format(name=test.name, port=str(test.port))) )
  520. err.flush()
  521. return
  522. result = test.start(out, err)
  523. if result != 0:
  524. test.stop(out, err)
  525. time.sleep(5)
  526. err.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  527. err.write( textwrap.dedent("""
  528. -----------------------------------------------------
  529. Stopped {name}
  530. -----------------------------------------------------
  531. """.format(name=test.name)) )
  532. err.flush()
  533. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  534. return
  535. time.sleep(self.sleep)
  536. ##########################
  537. # Verify URLs
  538. ##########################
  539. test.verify_urls(out, err)
  540. out.flush()
  541. err.flush()
  542. ##########################
  543. # Benchmark this test
  544. ##########################
  545. if self.mode == "benchmark":
  546. out.write( textwrap.dedent("""
  547. -----------------------------------------------------
  548. Benchmarking {name} ...
  549. -----------------------------------------------------
  550. """.format(name=test.name)) )
  551. out.flush()
  552. test.benchmark(out, err)
  553. out.flush()
  554. err.flush()
  555. ##########################
  556. # Stop this test
  557. ##########################
  558. out.write( textwrap.dedent("""
  559. -----------------------------------------------------
  560. Stopping {name}
  561. -----------------------------------------------------
  562. """.format(name=test.name)) )
  563. out.flush()
  564. test.stop(out, err)
  565. out.flush()
  566. err.flush()
  567. time.sleep(5)
  568. if self.__is_port_bound(test.port):
  569. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  570. err.write( textwrap.dedent("""
  571. -----------------------------------------------------
  572. Error: Port {port} was not released by stop {name}
  573. -----------------------------------------------------
  574. """.format(name=test.name, port=str(test.port))) )
  575. err.flush()
  576. return
  577. out.write( textwrap.dedent("""
  578. -----------------------------------------------------
  579. Stopped {name}
  580. -----------------------------------------------------
  581. """.format(name=test.name)) )
  582. out.flush()
  583. time.sleep(5)
  584. ##########################################################
  585. # Save results thus far into toolset/benchmark/latest.json
  586. ##########################################################
  587. out.write( textwrap.dedent("""
  588. ----------------------------------------------------
  589. Saving results through {name}
  590. ----------------------------------------------------
  591. """.format(name=test.name)) )
  592. out.flush()
  593. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  594. except (OSError, IOError, subprocess.CalledProcessError) as e:
  595. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  596. err.write( textwrap.dedent("""
  597. -----------------------------------------------------
  598. Subprocess Error {name}
  599. -----------------------------------------------------
  600. {err}
  601. {trace}
  602. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  603. err.flush()
  604. try:
  605. test.stop(out, err)
  606. except (subprocess.CalledProcessError) as e:
  607. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  608. err.write( textwrap.dedent("""
  609. -----------------------------------------------------
  610. Subprocess Error: Test .stop() raised exception {name}
  611. -----------------------------------------------------
  612. {err}
  613. {trace}
  614. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  615. err.flush()
  616. except (KeyboardInterrupt, SystemExit) as e:
  617. test.stop(out)
  618. out.write( """
  619. -----------------------------------------------------
  620. Cleaning up....
  621. -----------------------------------------------------
  622. """)
  623. out.flush()
  624. self.__finish()
  625. sys.exit()
  626. out.close()
  627. err.close()
  628. ############################################################
  629. # End __run_tests
  630. ############################################################
  631. ############################################################
  632. # __is_port_bound
  633. # Check if the requested port is available. If it
  634. # isn't available, then a previous test probably didn't
  635. # shutdown properly.
  636. ############################################################
  637. def __is_port_bound(self, port):
  638. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  639. try:
  640. # Try to bind to all IP addresses, this port
  641. s.bind(("", port))
  642. # If we get here, we were able to bind successfully,
  643. # which means the port is free.
  644. except:
  645. # If we get an exception, it might be because the port is still bound
  646. # which would be bad, or maybe it is a privileged port (<1024) and we
  647. # are not running as root, or maybe the server is gone, but sockets are
  648. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  649. # connect.
  650. try:
  651. s.connect(("127.0.0.1", port))
  652. # If we get here, we were able to connect to something, which means
  653. # that the port is still bound.
  654. return True
  655. except:
  656. # An exception means that we couldn't connect, so a server probably
  657. # isn't still running on the port.
  658. pass
  659. finally:
  660. s.close()
  661. return False
  662. ############################################################
  663. # End __is_port_bound
  664. ############################################################
  665. ############################################################
  666. # __parse_results
  667. # Ensures that the system has all necessary software to run
  668. # the tests. This does not include that software for the individual
  669. # test, but covers software such as curl and weighttp that
  670. # are needed.
  671. ############################################################
  672. def __parse_results(self, tests):
  673. # Run the method to get the commmit count of each framework.
  674. self.__count_commits()
  675. # Call the method which counts the sloc for each framework
  676. self.__count_sloc()
  677. # Time to create parsed files
  678. # Aggregate JSON file
  679. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  680. f.write(json.dumps(self.results))
  681. ############################################################
  682. # End __parse_results
  683. ############################################################
  684. #############################################################
  685. # __count_sloc
  686. # This is assumed to be run from the benchmark root directory
  687. #############################################################
  688. def __count_sloc(self):
  689. all_frameworks = self.__gather_frameworks()
  690. jsonResult = {}
  691. for framework in all_frameworks:
  692. try:
  693. command = "cloc --list-file=" + framework['directory'] + "/source_code --yaml"
  694. lineCount = subprocess.check_output(command, shell=True)
  695. # Find the last instance of the word 'code' in the yaml output. This should
  696. # be the line count for the sum of all listed files or just the line count
  697. # for the last file in the case where there's only one file listed.
  698. lineCount = lineCount[lineCount.rfind('code'):len(lineCount)]
  699. lineCount = lineCount.strip('code: ')
  700. lineCount = lineCount[0:lineCount.rfind('comment')]
  701. jsonResult[framework['name']] = int(lineCount)
  702. except:
  703. continue
  704. self.results['rawData']['slocCounts'] = jsonResult
  705. ############################################################
  706. # End __count_sloc
  707. ############################################################
  708. ############################################################
  709. # __count_commits
  710. ############################################################
  711. def __count_commits(self):
  712. all_frameworks = self.__gather_frameworks()
  713. jsonResult = {}
  714. for framework in all_frameworks:
  715. try:
  716. command = "git rev-list HEAD -- " + framework + " | sort -u | wc -l"
  717. commitCount = subprocess.check_output(command, shell=True)
  718. jsonResult[framework] = int(commitCount)
  719. except:
  720. continue
  721. self.results['rawData']['commitCounts'] = jsonResult
  722. self.commits = jsonResult
  723. ############################################################
  724. # End __count_commits
  725. ############################################################
  726. ############################################################
  727. # __write_intermediate_results
  728. ############################################################
  729. def __write_intermediate_results(self,test_name,status_message):
  730. try:
  731. self.results["completed"][test_name] = status_message
  732. with open(os.path.join(self.latest_results_directory, 'results.json'), 'w') as f:
  733. f.write(json.dumps(self.results))
  734. except (IOError):
  735. logging.error("Error writing results.json")
  736. ############################################################
  737. # End __write_intermediate_results
  738. ############################################################
  739. ############################################################
  740. # __finish
  741. ############################################################
  742. def __finish(self):
  743. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  744. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  745. ############################################################
  746. # End __finish
  747. ############################################################
  748. ##########################################################################################
  749. # Constructor
  750. ##########################################################################################
  751. ############################################################
  752. # Initialize the benchmarker. The args are the arguments
  753. # parsed via argparser.
  754. ############################################################
  755. def __init__(self, args):
  756. self.__dict__.update(args)
  757. self.start_time = time.time()
  758. self.run_test_timeout_seconds = 3600
  759. # setup logging
  760. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  761. # setup some additional variables
  762. if self.database_user == None: self.database_user = self.client_user
  763. if self.database_host == None: self.database_host = self.client_host
  764. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  765. # setup results and latest_results directories
  766. self.result_directory = os.path.join("results", self.name)
  767. self.latest_results_directory = self.latest_results_directory()
  768. if self.parse != None:
  769. self.timestamp = self.parse
  770. else:
  771. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  772. # Setup the concurrency levels array. This array goes from
  773. # starting_concurrency to max concurrency, doubling each time
  774. self.concurrency_levels = []
  775. concurrency = self.starting_concurrency
  776. while concurrency <= self.max_concurrency:
  777. self.concurrency_levels.append(concurrency)
  778. concurrency = concurrency * 2
  779. # Setup query interval array
  780. # starts at 1, and goes up to max_queries, using the query_interval
  781. self.query_intervals = []
  782. queries = 1
  783. while queries <= self.max_queries:
  784. self.query_intervals.append(queries)
  785. if queries == 1:
  786. queries = 0
  787. queries = queries + self.query_interval
  788. # Load the latest data
  789. #self.latest = None
  790. #try:
  791. # with open('toolset/benchmark/latest.json', 'r') as f:
  792. # # Load json file into config object
  793. # self.latest = json.load(f)
  794. # logging.info("toolset/benchmark/latest.json loaded to self.latest")
  795. # logging.debug("contents of latest.json: " + str(json.dumps(self.latest)))
  796. #except IOError:
  797. # logging.warn("IOError on attempting to read toolset/benchmark/latest.json")
  798. #
  799. #self.results = None
  800. #try:
  801. # if self.latest != None and self.name in self.latest.keys():
  802. # with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  803. # # Load json file into config object
  804. # self.results = json.load(f)
  805. #except IOError:
  806. # pass
  807. self.results = None
  808. try:
  809. with open(os.path.join(self.latest_results_directory, 'results.json'), 'r') as f:
  810. #Load json file into results object
  811. self.results = json.load(f)
  812. except IOError:
  813. logging.warn("results.json for test %s not found.",self.name)
  814. if self.results == None:
  815. self.results = dict()
  816. self.results['name'] = self.name
  817. self.results['concurrencyLevels'] = self.concurrency_levels
  818. self.results['queryIntervals'] = self.query_intervals
  819. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  820. self.results['duration'] = self.duration
  821. self.results['rawData'] = dict()
  822. self.results['rawData']['json'] = dict()
  823. self.results['rawData']['db'] = dict()
  824. self.results['rawData']['query'] = dict()
  825. self.results['rawData']['fortune'] = dict()
  826. self.results['rawData']['update'] = dict()
  827. self.results['rawData']['plaintext'] = dict()
  828. self.results['completed'] = dict()
  829. self.results['succeeded'] = dict()
  830. self.results['succeeded']['json'] = []
  831. self.results['succeeded']['db'] = []
  832. self.results['succeeded']['query'] = []
  833. self.results['succeeded']['fortune'] = []
  834. self.results['succeeded']['update'] = []
  835. self.results['succeeded']['plaintext'] = []
  836. self.results['failed'] = dict()
  837. self.results['failed']['json'] = []
  838. self.results['failed']['db'] = []
  839. self.results['failed']['query'] = []
  840. self.results['failed']['fortune'] = []
  841. self.results['failed']['update'] = []
  842. self.results['failed']['plaintext'] = []
  843. self.results['warning'] = dict()
  844. self.results['warning']['json'] = []
  845. self.results['warning']['db'] = []
  846. self.results['warning']['query'] = []
  847. self.results['warning']['fortune'] = []
  848. self.results['warning']['update'] = []
  849. self.results['warning']['plaintext'] = []
  850. else:
  851. #for x in self.__gather_tests():
  852. # if x.name not in self.results['frameworks']:
  853. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  854. # Always overwrite framework list
  855. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  856. # Setup the ssh command string
  857. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  858. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  859. if self.database_identity_file != None:
  860. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  861. if self.client_identity_file != None:
  862. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  863. if self.install_software:
  864. install = Installer(self)
  865. install.install_software()
  866. ############################################################
  867. # End __init__
  868. ############################################################