benchmarker.py 39 KB

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