benchmarker.py 40 KB

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