benchmarker.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. # Add this type
  241. if os.path.exists(self.get_warning_file(framework.name, test)):
  242. self.results['warning'][test].append(framework.name)
  243. else:
  244. # This may already be set for single-tests
  245. if framework.name not in self.results['failed'][test]:
  246. self.results['failed'][test].append(framework.name)
  247. ############################################################
  248. # End report_results
  249. ############################################################
  250. ##########################################################################################
  251. # Private methods
  252. ##########################################################################################
  253. ############################################################
  254. # Gathers all the tests
  255. ############################################################
  256. @property
  257. def __gather_tests(self):
  258. tests = []
  259. # Loop through each directory (we assume we're being run from the benchmarking root)
  260. # and look for the files that signify a benchmark test
  261. for dirname, dirnames, filenames in os.walk('.'):
  262. # Look for the benchmark_config file, this will set up our tests.
  263. # Its format looks like this:
  264. #
  265. # {
  266. # "framework": "nodejs",
  267. # "tests": [{
  268. # "default": {
  269. # "setup_file": "setup",
  270. # "json_url": "/json"
  271. # },
  272. # "mysql": {
  273. # "setup_file": "setup",
  274. # "db_url": "/mysql",
  275. # "query_url": "/mysql?queries="
  276. # },
  277. # ...
  278. # }]
  279. # }
  280. if 'benchmark_config' in filenames:
  281. config = None
  282. config_file_name = os.path.join(dirname, 'benchmark_config')
  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 == None:
  291. continue
  292. test = framework_test.parse_config(config, dirname[2:], 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*|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. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=err, shell=True)
  506. p.communicate("""
  507. sudo restart mysql
  508. sudo restart mongodb
  509. sudo /etc/init.d/postgresql restart
  510. """)
  511. time.sleep(10)
  512. if self.__is_port_bound(test.port):
  513. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  514. err.write( textwrap.dedent("""
  515. ---------------------------------------------------------
  516. Error: Port {port} is not available before start {name}
  517. ---------------------------------------------------------
  518. """.format(name=test.name, port=str(test.port))) )
  519. err.flush()
  520. return
  521. result = test.start(out, err)
  522. if result != 0:
  523. test.stop(out, err)
  524. time.sleep(5)
  525. err.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  526. err.write( textwrap.dedent("""
  527. -----------------------------------------------------
  528. Stopped {name}
  529. -----------------------------------------------------
  530. """.format(name=test.name)) )
  531. err.flush()
  532. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  533. return
  534. time.sleep(self.sleep)
  535. ##########################
  536. # Verify URLs
  537. ##########################
  538. out.write( textwrap.dedent("""
  539. -----------------------------------------------------
  540. Verifying URLs for {name}
  541. -----------------------------------------------------
  542. """.format(name=test.name)) )
  543. test.verify_urls(out, err)
  544. out.flush()
  545. err.flush()
  546. ##########################
  547. # Benchmark this test
  548. ##########################
  549. if self.mode == "benchmark":
  550. out.write( textwrap.dedent("""
  551. -----------------------------------------------------
  552. Benchmarking {name} ...
  553. -----------------------------------------------------
  554. """.format(name=test.name)) )
  555. out.flush()
  556. test.benchmark(out, err)
  557. out.flush()
  558. err.flush()
  559. ##########################
  560. # Stop this test
  561. ##########################
  562. out.write( textwrap.dedent("""
  563. -----------------------------------------------------
  564. Stopping {name}
  565. -----------------------------------------------------
  566. """.format(name=test.name)) )
  567. out.flush()
  568. test.stop(out, err)
  569. out.flush()
  570. err.flush()
  571. time.sleep(5)
  572. if self.__is_port_bound(test.port):
  573. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  574. err.write( textwrap.dedent("""
  575. -----------------------------------------------------
  576. Error: Port {port} was not released by stop {name}
  577. -----------------------------------------------------
  578. """.format(name=test.name, port=str(test.port))) )
  579. err.flush()
  580. return
  581. out.write( textwrap.dedent("""
  582. -----------------------------------------------------
  583. Stopped {name}
  584. -----------------------------------------------------
  585. """.format(name=test.name)) )
  586. out.flush()
  587. time.sleep(5)
  588. ##########################################################
  589. # Save results thus far into toolset/benchmark/latest.json
  590. ##########################################################
  591. out.write( textwrap.dedent("""
  592. ----------------------------------------------------
  593. Saving results through {name}
  594. ----------------------------------------------------
  595. """.format(name=test.name)) )
  596. out.flush()
  597. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  598. except (OSError, IOError, subprocess.CalledProcessError) as e:
  599. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  600. err.write( textwrap.dedent("""
  601. -----------------------------------------------------
  602. Subprocess Error {name}
  603. -----------------------------------------------------
  604. {err}
  605. {trace}
  606. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  607. err.flush()
  608. try:
  609. test.stop(out, err)
  610. except (subprocess.CalledProcessError) as e:
  611. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  612. err.write( textwrap.dedent("""
  613. -----------------------------------------------------
  614. Subprocess Error: Test .stop() raised exception {name}
  615. -----------------------------------------------------
  616. {err}
  617. {trace}
  618. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  619. err.flush()
  620. except (KeyboardInterrupt, SystemExit) as e:
  621. test.stop(out)
  622. out.write( """
  623. -----------------------------------------------------
  624. Cleaning up....
  625. -----------------------------------------------------
  626. """)
  627. out.flush()
  628. self.__finish()
  629. sys.exit()
  630. out.close()
  631. err.close()
  632. ############################################################
  633. # End __run_tests
  634. ############################################################
  635. ############################################################
  636. # __is_port_bound
  637. # Check if the requested port is available. If it
  638. # isn't available, then a previous test probably didn't
  639. # shutdown properly.
  640. ############################################################
  641. def __is_port_bound(self, port):
  642. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  643. try:
  644. # Try to bind to all IP addresses, this port
  645. s.bind(("", port))
  646. # If we get here, we were able to bind successfully,
  647. # which means the port is free.
  648. except:
  649. # If we get an exception, it might be because the port is still bound
  650. # which would be bad, or maybe it is a privileged port (<1024) and we
  651. # are not running as root, or maybe the server is gone, but sockets are
  652. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  653. # connect.
  654. try:
  655. s.connect(("127.0.0.1", port))
  656. # If we get here, we were able to connect to something, which means
  657. # that the port is still bound.
  658. return True
  659. except:
  660. # An exception means that we couldn't connect, so a server probably
  661. # isn't still running on the port.
  662. pass
  663. finally:
  664. s.close()
  665. return False
  666. ############################################################
  667. # End __is_port_bound
  668. ############################################################
  669. ############################################################
  670. # __parse_results
  671. # Ensures that the system has all necessary software to run
  672. # the tests. This does not include that software for the individual
  673. # test, but covers software such as curl and weighttp that
  674. # are needed.
  675. ############################################################
  676. def __parse_results(self, tests):
  677. # Run the method to get the commmit count of each framework.
  678. self.__count_commits()
  679. # Call the method which counts the sloc for each framework
  680. self.__count_sloc()
  681. # Time to create parsed files
  682. # Aggregate JSON file
  683. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  684. f.write(json.dumps(self.results))
  685. ############################################################
  686. # End __parse_results
  687. ############################################################
  688. #############################################################
  689. # __count_sloc
  690. # This is assumed to be run from the benchmark root directory
  691. #############################################################
  692. def __count_sloc(self):
  693. all_frameworks = self.__gather_frameworks()
  694. jsonResult = {}
  695. for framework in all_frameworks:
  696. try:
  697. command = "cloc --list-file=" + framework['directory'] + "/source_code --yaml"
  698. lineCount = subprocess.check_output(command, shell=True)
  699. # Find the last instance of the word 'code' in the yaml output. This should
  700. # be the line count for the sum of all listed files or just the line count
  701. # for the last file in the case where there's only one file listed.
  702. lineCount = lineCount[lineCount.rfind('code'):len(lineCount)]
  703. lineCount = lineCount.strip('code: ')
  704. lineCount = lineCount[0:lineCount.rfind('comment')]
  705. jsonResult[framework['name']] = int(lineCount)
  706. except:
  707. continue
  708. self.results['rawData']['slocCounts'] = jsonResult
  709. ############################################################
  710. # End __count_sloc
  711. ############################################################
  712. ############################################################
  713. # __count_commits
  714. ############################################################
  715. def __count_commits(self):
  716. all_frameworks = self.__gather_frameworks()
  717. jsonResult = {}
  718. for framework in all_frameworks:
  719. try:
  720. command = "git rev-list HEAD -- " + framework + " | sort -u | wc -l"
  721. commitCount = subprocess.check_output(command, shell=True)
  722. jsonResult[framework] = int(commitCount)
  723. except:
  724. continue
  725. self.results['rawData']['commitCounts'] = jsonResult
  726. self.commits = jsonResult
  727. ############################################################
  728. # End __count_commits
  729. ############################################################
  730. ############################################################
  731. # __write_intermediate_results
  732. ############################################################
  733. def __write_intermediate_results(self,test_name,status_message):
  734. try:
  735. self.results["completed"][test_name] = status_message
  736. with open(os.path.join(self.latest_results_directory, 'results.json'), 'w') as f:
  737. f.write(json.dumps(self.results))
  738. except (IOError):
  739. logging.error("Error writing results.json")
  740. ############################################################
  741. # End __write_intermediate_results
  742. ############################################################
  743. ############################################################
  744. # __finish
  745. ############################################################
  746. def __finish(self):
  747. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  748. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  749. ############################################################
  750. # End __finish
  751. ############################################################
  752. ##########################################################################################
  753. # Constructor
  754. ##########################################################################################
  755. ############################################################
  756. # Initialize the benchmarker. The args are the arguments
  757. # parsed via argparser.
  758. ############################################################
  759. def __init__(self, args):
  760. self.__dict__.update(args)
  761. self.start_time = time.time()
  762. self.run_test_timeout_seconds = 3600
  763. # setup logging
  764. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  765. # setup some additional variables
  766. if self.database_user == None: self.database_user = self.client_user
  767. if self.database_host == None: self.database_host = self.client_host
  768. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  769. # setup results and latest_results directories
  770. self.result_directory = os.path.join("results", self.name)
  771. self.latest_results_directory = self.latest_results_directory()
  772. if self.parse != None:
  773. self.timestamp = self.parse
  774. else:
  775. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  776. # Setup the concurrency levels array. This array goes from
  777. # starting_concurrency to max concurrency, doubling each time
  778. self.concurrency_levels = []
  779. concurrency = self.starting_concurrency
  780. while concurrency <= self.max_concurrency:
  781. self.concurrency_levels.append(concurrency)
  782. concurrency = concurrency * 2
  783. # Setup query interval array
  784. # starts at 1, and goes up to max_queries, using the query_interval
  785. self.query_intervals = []
  786. queries = 1
  787. while queries <= self.max_queries:
  788. self.query_intervals.append(queries)
  789. if queries == 1:
  790. queries = 0
  791. queries = queries + self.query_interval
  792. # Load the latest data
  793. #self.latest = None
  794. #try:
  795. # with open('toolset/benchmark/latest.json', 'r') as f:
  796. # # Load json file into config object
  797. # self.latest = json.load(f)
  798. # logging.info("toolset/benchmark/latest.json loaded to self.latest")
  799. # logging.debug("contents of latest.json: " + str(json.dumps(self.latest)))
  800. #except IOError:
  801. # logging.warn("IOError on attempting to read toolset/benchmark/latest.json")
  802. #
  803. #self.results = None
  804. #try:
  805. # if self.latest != None and self.name in self.latest.keys():
  806. # with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  807. # # Load json file into config object
  808. # self.results = json.load(f)
  809. #except IOError:
  810. # pass
  811. self.results = None
  812. try:
  813. with open(os.path.join(self.latest_results_directory, 'results.json'), 'r') as f:
  814. #Load json file into results object
  815. self.results = json.load(f)
  816. except IOError:
  817. logging.warn("results.json for test %s not found.",self.name)
  818. if self.results == None:
  819. self.results = dict()
  820. self.results['name'] = self.name
  821. self.results['concurrencyLevels'] = self.concurrency_levels
  822. self.results['queryIntervals'] = self.query_intervals
  823. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  824. self.results['duration'] = self.duration
  825. self.results['rawData'] = dict()
  826. self.results['rawData']['json'] = dict()
  827. self.results['rawData']['db'] = dict()
  828. self.results['rawData']['query'] = dict()
  829. self.results['rawData']['fortune'] = dict()
  830. self.results['rawData']['update'] = dict()
  831. self.results['rawData']['plaintext'] = dict()
  832. self.results['completed'] = dict()
  833. self.results['succeeded'] = dict()
  834. self.results['succeeded']['json'] = []
  835. self.results['succeeded']['db'] = []
  836. self.results['succeeded']['query'] = []
  837. self.results['succeeded']['fortune'] = []
  838. self.results['succeeded']['update'] = []
  839. self.results['succeeded']['plaintext'] = []
  840. self.results['failed'] = dict()
  841. self.results['failed']['json'] = []
  842. self.results['failed']['db'] = []
  843. self.results['failed']['query'] = []
  844. self.results['failed']['fortune'] = []
  845. self.results['failed']['update'] = []
  846. self.results['failed']['plaintext'] = []
  847. self.results['warning'] = dict()
  848. self.results['warning']['json'] = []
  849. self.results['warning']['db'] = []
  850. self.results['warning']['query'] = []
  851. self.results['warning']['fortune'] = []
  852. self.results['warning']['update'] = []
  853. self.results['warning']['plaintext'] = []
  854. else:
  855. #for x in self.__gather_tests():
  856. # if x.name not in self.results['frameworks']:
  857. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  858. # Always overwrite framework list
  859. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  860. # Setup the ssh command string
  861. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  862. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  863. if self.database_identity_file != None:
  864. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  865. if self.client_identity_file != None:
  866. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  867. if self.install_software:
  868. install = Installer(self)
  869. install.install_software()
  870. ############################################################
  871. # End __init__
  872. ############################################################