benchmarker.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. result = 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. return result
  120. ############################################################
  121. # End run
  122. ############################################################
  123. ############################################################
  124. # database_sftp_string(batch_file)
  125. # generates a fully qualified URL for sftp to database
  126. ############################################################
  127. def database_sftp_string(self, batch_file):
  128. sftp_string = "sftp -oStrictHostKeyChecking=no "
  129. if batch_file != None: sftp_string += " -b " + batch_file + " "
  130. if self.database_identity_file != None:
  131. sftp_string += " -i " + self.database_identity_file + " "
  132. return sftp_string + self.database_user + "@" + self.database_host
  133. ############################################################
  134. # End database_sftp_string
  135. ############################################################
  136. ############################################################
  137. # client_sftp_string(batch_file)
  138. # generates a fully qualified URL for sftp to client
  139. ############################################################
  140. def client_sftp_string(self, batch_file):
  141. sftp_string = "sftp -oStrictHostKeyChecking=no "
  142. if batch_file != None: sftp_string += " -b " + batch_file + " "
  143. if self.client_identity_file != None:
  144. sftp_string += " -i " + self.client_identity_file + " "
  145. return sftp_string + self.client_user + "@" + self.client_host
  146. ############################################################
  147. # End client_sftp_string
  148. ############################################################
  149. ############################################################
  150. # generate_url(url, port)
  151. # generates a fully qualified URL for accessing a test url
  152. ############################################################
  153. def generate_url(self, url, port):
  154. return self.server_host + ":" + str(port) + url
  155. ############################################################
  156. # End generate_url
  157. ############################################################
  158. ############################################################
  159. # get_output_file(test_name, test_type)
  160. # returns the output file name for this test_name and
  161. # test_type timestamp/test_type/test_name/raw
  162. ############################################################
  163. def get_output_file(self, test_name, test_type):
  164. return os.path.join(self.result_directory, self.timestamp, test_type, test_name, "raw")
  165. ############################################################
  166. # End get_output_file
  167. ############################################################
  168. ############################################################
  169. # output_file(test_name, test_type)
  170. # returns the output file for this test_name and test_type
  171. # timestamp/test_type/test_name/raw
  172. ############################################################
  173. def output_file(self, test_name, test_type):
  174. path = self.get_output_file(test_name, test_type)
  175. try:
  176. os.makedirs(os.path.dirname(path))
  177. except OSError:
  178. pass
  179. return path
  180. ############################################################
  181. # End output_file
  182. ############################################################
  183. ############################################################
  184. # get_warning_file(test_name, test_type)
  185. # returns the output file name for this test_name and
  186. # test_type timestamp/test_type/test_name/raw
  187. ############################################################
  188. def get_warning_file(self, test_name, test_type):
  189. return os.path.join(self.result_directory, self.timestamp, test_type, test_name, "warn")
  190. ############################################################
  191. # End get_warning_file
  192. ############################################################
  193. ############################################################
  194. # warning_file(test_name, test_type)
  195. # returns the warning file for this test_name and test_type
  196. # timestamp/test_type/test_name/raw
  197. ############################################################
  198. def warning_file(self, test_name, test_type):
  199. path = self.get_warning_file(test_name, test_type)
  200. try:
  201. os.makedirs(os.path.dirname(path))
  202. except OSError:
  203. pass
  204. return path
  205. ############################################################
  206. # End warning_file
  207. ############################################################
  208. ############################################################
  209. # get_stats_file(test_name, test_type)
  210. # returns the stats file name for this test_name and
  211. # test_type timestamp/test_type/test_name/raw
  212. ############################################################
  213. def get_stats_file(self, test_name, test_type):
  214. return os.path.join(self.result_directory, self.timestamp, test_type, test_name, "stats")
  215. ############################################################
  216. # End get_stats_file
  217. ############################################################
  218. ############################################################
  219. # stats_file(test_name, test_type)
  220. # returns the stats file for this test_name and test_type
  221. # timestamp/test_type/test_name/raw
  222. ############################################################
  223. def stats_file(self, test_name, test_type):
  224. path = self.get_stats_file(test_name, test_type)
  225. try:
  226. os.makedirs(os.path.dirname(path))
  227. except OSError:
  228. pass
  229. return path
  230. ############################################################
  231. # End stats_file
  232. ############################################################
  233. ############################################################
  234. # full_results_directory
  235. ############################################################
  236. def full_results_directory(self):
  237. path = os.path.join(self.result_directory, self.timestamp)
  238. try:
  239. os.makedirs(path)
  240. except OSError:
  241. pass
  242. return path
  243. ############################################################
  244. # End full_results_directory
  245. ############################################################
  246. ############################################################
  247. # Latest intermediate results dirctory
  248. ############################################################
  249. def latest_results_directory(self):
  250. path = os.path.join(self.result_directory,"latest")
  251. try:
  252. os.makedirs(path)
  253. except OSError:
  254. pass
  255. return path
  256. ############################################################
  257. # report_results
  258. ############################################################
  259. def report_results(self, framework, test, results):
  260. if test not in self.results['rawData'].keys():
  261. self.results['rawData'][test] = dict()
  262. # If results has a size from the parse, then it succeeded.
  263. if results:
  264. self.results['rawData'][test][framework.name] = results
  265. # This may already be set for single-tests
  266. if framework.name not in self.results['succeeded'][test]:
  267. self.results['succeeded'][test].append(framework.name)
  268. # Add this type
  269. if (os.path.exists(self.get_warning_file(framework.name, test)) and
  270. framework.name not in self.results['warning'][test]):
  271. self.results['warning'][test].append(framework.name)
  272. else:
  273. # This may already be set for single-tests
  274. if framework.name not in self.results['failed'][test]:
  275. self.results['failed'][test].append(framework.name)
  276. ############################################################
  277. # End report_results
  278. ############################################################
  279. ##########################################################################################
  280. # Private methods
  281. ##########################################################################################
  282. ############################################################
  283. # Gathers all the tests
  284. ############################################################
  285. @property
  286. def __gather_tests(self):
  287. tests = []
  288. # Assume we are running from FrameworkBenchmarks
  289. config_files = glob.glob('*/benchmark_config')
  290. for config_file_name in config_files:
  291. # Look for the benchmark_config file, this will set up our tests.
  292. # Its 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. config = None
  310. with open(config_file_name, 'r') as config_file:
  311. # Load json file into config object
  312. try:
  313. config = json.load(config_file)
  314. except:
  315. print("Error loading '%s'." % config_file_name)
  316. raise
  317. if config is None:
  318. continue
  319. test = framework_test.parse_config(config, os.path.dirname(config_file_name), self)
  320. # If the user specified which tests to run, then
  321. # we can skip over tests that are not in that list
  322. if self.test == None:
  323. tests = tests + test
  324. else:
  325. for atest in test:
  326. if atest.name in self.test:
  327. tests.append(atest)
  328. tests.sort(key=lambda x: x.name)
  329. # If the tests have been interrupted somehow, then we want to resume them where we left
  330. # off, rather than starting from the beginning
  331. if os.path.isfile('current_benchmark.txt'):
  332. with open('current_benchmark.txt', 'r') as interrupted_benchmark:
  333. interrupt_bench = interrupted_benchmark.read()
  334. for index, atest in enumerate(tests):
  335. if atest.name == interrupt_bench:
  336. tests = tests[index:]
  337. break
  338. return tests
  339. ############################################################
  340. # End __gather_tests
  341. ############################################################
  342. ############################################################
  343. # Gathers all the frameworks
  344. ############################################################
  345. def __gather_frameworks(self):
  346. frameworks = []
  347. # Loop through each directory (we assume we're being run from the benchmarking root)
  348. for dirname, dirnames, filenames in os.walk('.'):
  349. # Look for the benchmark_config file, this will contain our framework name
  350. # It's format looks like this:
  351. #
  352. # {
  353. # "framework": "nodejs",
  354. # "tests": [{
  355. # "default": {
  356. # "setup_file": "setup",
  357. # "json_url": "/json"
  358. # },
  359. # "mysql": {
  360. # "setup_file": "setup",
  361. # "db_url": "/mysql",
  362. # "query_url": "/mysql?queries="
  363. # },
  364. # ...
  365. # }]
  366. # }
  367. if 'benchmark_config' in filenames:
  368. config = None
  369. with open(os.path.join(dirname, 'benchmark_config'), 'r') as config_file:
  370. # Load json file into config object
  371. config = json.load(config_file)
  372. if config == None:
  373. continue
  374. frameworks.append(str(config['framework']))
  375. return frameworks
  376. ############################################################
  377. # End __gather_frameworks
  378. ############################################################
  379. ############################################################
  380. # Makes any necessary changes to the server that should be
  381. # made before running the tests. This involves setting kernal
  382. # settings to allow for more connections, or more file
  383. # descriptiors
  384. #
  385. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  386. ############################################################
  387. def __setup_server(self):
  388. try:
  389. if os.name == 'nt':
  390. return True
  391. 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"])
  392. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  393. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  394. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  395. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  396. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  397. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  398. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  399. except subprocess.CalledProcessError:
  400. return False
  401. ############################################################
  402. # End __setup_server
  403. ############################################################
  404. ############################################################
  405. # Makes any necessary changes to the database machine that
  406. # should be made before running the tests. Is very similar
  407. # to the server setup, but may also include database specific
  408. # changes.
  409. ############################################################
  410. def __setup_database(self):
  411. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  412. p.communicate("""
  413. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  414. sudo sysctl -w net.core.somaxconn=65535
  415. sudo -s ulimit -n 65535
  416. sudo sysctl net.ipv4.tcp_tw_reuse=1
  417. sudo sysctl net.ipv4.tcp_tw_recycle=1
  418. sudo sysctl -w kernel.shmmax=2147483648
  419. sudo sysctl -w kernel.shmall=2097152
  420. """)
  421. ############################################################
  422. # End __setup_database
  423. ############################################################
  424. ############################################################
  425. # Makes any necessary changes to the client machine that
  426. # should be made before running the tests. Is very similar
  427. # to the server setup, but may also include client specific
  428. # changes.
  429. ############################################################
  430. def __setup_client(self):
  431. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  432. p.communicate("""
  433. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  434. sudo sysctl -w net.core.somaxconn=65535
  435. sudo -s ulimit -n 65535
  436. sudo sysctl net.ipv4.tcp_tw_reuse=1
  437. sudo sysctl net.ipv4.tcp_tw_recycle=1
  438. sudo sysctl -w kernel.shmmax=2147483648
  439. sudo sysctl -w kernel.shmall=2097152
  440. """)
  441. ############################################################
  442. # End __setup_client
  443. ############################################################
  444. ############################################################
  445. # __run_tests
  446. #
  447. # 2013-10-02 ASB Calls each test passed in tests to
  448. # __run_test in a separate process. Each
  449. # test is given a set amount of time and if
  450. # kills the child process (and subsequently
  451. # all of its child processes). Uses
  452. # multiprocessing module.
  453. ############################################################
  454. def __run_tests(self, tests):
  455. logging.debug("Start __run_tests.")
  456. logging.debug("__name__ = %s",__name__)
  457. if self.os.lower() == 'windows':
  458. logging.debug("Executing __run_tests on Windows")
  459. for test in tests:
  460. with open('current_benchmark.txt', 'w') as benchmark_resume_file:
  461. benchmark_resume_file.write(test.name)
  462. self.__run_test(test)
  463. else:
  464. logging.debug("Executing __run_tests on Linux")
  465. # These features do not work on Windows
  466. for test in tests:
  467. if __name__ == 'benchmark.benchmarker':
  468. print textwrap.dedent("""
  469. -----------------------------------------------------
  470. Running Test: {name} ...
  471. -----------------------------------------------------
  472. """.format(name=test.name))
  473. with open('current_benchmark.txt', 'w') as benchmark_resume_file:
  474. benchmark_resume_file.write(test.name)
  475. test_process = Process(target=self.__run_test, args=(test,))
  476. test_process.start()
  477. test_process.join(self.run_test_timeout_seconds)
  478. self.__load_results() # Load intermediate result from child process
  479. if(test_process.is_alive()):
  480. logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
  481. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  482. test_process.terminate()
  483. os.remove('current_benchmark.txt')
  484. logging.debug("End __run_tests.")
  485. ############################################################
  486. # End __run_tests
  487. ############################################################
  488. ############################################################
  489. # __run_test
  490. # 2013-10-02 ASB Previously __run_tests. This code now only
  491. # processes a single test.
  492. #
  493. # Ensures that the system has all necessary software to run
  494. # the tests. This does not include that software for the individual
  495. # test, but covers software such as curl and weighttp that
  496. # are needed.
  497. ############################################################
  498. def __run_test(self, test):
  499. try:
  500. os.makedirs(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name)))
  501. except:
  502. pass
  503. with open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'out.txt'), 'w') as out, \
  504. open(os.path.join(self.latest_results_directory, 'logs', "{name}".format(name=test.name), 'err.txt'), 'w') as err:
  505. if hasattr(test, 'skip'):
  506. if test.skip.lower() == "true":
  507. out.write("Test {name} benchmark_config specifies to skip this test. Skipping.\n".format(name=test.name))
  508. return
  509. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  510. # the operating system requirements of this test for the
  511. # application server or the database server don't match
  512. # our current environment
  513. out.write("OS or Database OS specified in benchmark_config does not match the current environment. Skipping.\n")
  514. return 0
  515. # If the test is in the excludes list, we skip it
  516. if self.exclude != None and test.name in self.exclude:
  517. out.write("Test {name} has been added to the excludes list. Skipping.\n".format(name=test.name))
  518. return 0
  519. # If the test does not contain an implementation of the current test-type, skip it
  520. if self.type != 'all' and not test.contains_type(self.type):
  521. out.write("Test type {type} does not contain an implementation of the current test-type. Skipping.\n".format(type=self.type))
  522. return 0
  523. out.write("test.os.lower() = {os} test.database_os.lower() = {dbos}\n".format(os=test.os.lower(),dbos=test.database_os.lower()))
  524. out.write("self.results['frameworks'] != None: {val}\n".format(val=str(self.results['frameworks'] != None)))
  525. out.write("test.name: {name}\n".format(name=str(test.name)))
  526. out.write("self.results['completed']: {completed}\n".format(completed=str(self.results['completed'])))
  527. if self.results['frameworks'] != None and test.name in self.results['completed']:
  528. out.write('Framework {name} found in latest saved data. Skipping.\n'.format(name=str(test.name)))
  529. return
  530. out.flush()
  531. out.write( textwrap.dedent("""
  532. =====================================================
  533. Beginning {name}
  534. -----------------------------------------------------
  535. """.format(name=test.name)) )
  536. out.flush()
  537. ##########################
  538. # Start this test
  539. ##########################
  540. out.write( textwrap.dedent("""
  541. -----------------------------------------------------
  542. Starting {name}
  543. -----------------------------------------------------
  544. """.format(name=test.name)) )
  545. out.flush()
  546. try:
  547. if test.requires_database():
  548. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=err, shell=True)
  549. p.communicate("""
  550. sudo restart mysql
  551. sudo restart mongodb
  552. sudo service redis-server restart
  553. sudo /etc/init.d/postgresql restart
  554. """)
  555. time.sleep(10)
  556. if self.__is_port_bound(test.port):
  557. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  558. err.write( textwrap.dedent("""
  559. ---------------------------------------------------------
  560. Error: Port {port} is not available before start {name}
  561. ---------------------------------------------------------
  562. """.format(name=test.name, port=str(test.port))) )
  563. err.flush()
  564. return
  565. result = test.start(out, err)
  566. if result != 0:
  567. test.stop(out, err)
  568. time.sleep(5)
  569. err.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  570. err.write( textwrap.dedent("""
  571. -----------------------------------------------------
  572. Stopped {name}
  573. -----------------------------------------------------
  574. """.format(name=test.name)) )
  575. err.flush()
  576. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  577. return
  578. time.sleep(self.sleep)
  579. ##########################
  580. # Verify URLs
  581. ##########################
  582. passed_verify = test.verify_urls(out, err)
  583. out.flush()
  584. err.flush()
  585. ##########################
  586. # Benchmark this test
  587. ##########################
  588. if self.mode == "benchmark":
  589. out.write( textwrap.dedent("""
  590. -----------------------------------------------------
  591. Benchmarking {name} ...
  592. -----------------------------------------------------
  593. """.format(name=test.name)) )
  594. out.flush()
  595. test.benchmark(out, err)
  596. out.flush()
  597. err.flush()
  598. ##########################
  599. # Stop this test
  600. ##########################
  601. out.write( textwrap.dedent("""
  602. -----------------------------------------------------
  603. Stopping {name}
  604. -----------------------------------------------------
  605. """.format(name=test.name)) )
  606. out.flush()
  607. test.stop(out, err)
  608. out.flush()
  609. err.flush()
  610. time.sleep(5)
  611. if self.__is_port_bound(test.port):
  612. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  613. err.write( textwrap.dedent("""
  614. -----------------------------------------------------
  615. Error: Port {port} was not released by stop {name}
  616. -----------------------------------------------------
  617. """.format(name=test.name, port=str(test.port))) )
  618. err.flush()
  619. return
  620. out.write( textwrap.dedent("""
  621. -----------------------------------------------------
  622. Stopped {name}
  623. -----------------------------------------------------
  624. """.format(name=test.name)) )
  625. out.flush()
  626. time.sleep(5)
  627. ##########################################################
  628. # Save results thus far into toolset/benchmark/latest.json
  629. ##########################################################
  630. out.write( textwrap.dedent("""
  631. ----------------------------------------------------
  632. Saving results through {name}
  633. ----------------------------------------------------
  634. """.format(name=test.name)) )
  635. out.flush()
  636. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  637. except (OSError, IOError, subprocess.CalledProcessError) as e:
  638. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  639. err.write( textwrap.dedent("""
  640. -----------------------------------------------------
  641. Subprocess Error {name}
  642. -----------------------------------------------------
  643. {err}
  644. {trace}
  645. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  646. err.flush()
  647. try:
  648. test.stop(out, err)
  649. except (subprocess.CalledProcessError) as e:
  650. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  651. err.write( textwrap.dedent("""
  652. -----------------------------------------------------
  653. Subprocess Error: Test .stop() raised exception {name}
  654. -----------------------------------------------------
  655. {err}
  656. {trace}
  657. """.format(name=test.name, err=e, trace=sys.exc_info()[:2])) )
  658. err.flush()
  659. out.close()
  660. err.close()
  661. return 1
  662. except (KeyboardInterrupt, SystemExit) as e:
  663. test.stop(out)
  664. out.write( """
  665. -----------------------------------------------------
  666. Cleaning up....
  667. -----------------------------------------------------
  668. """)
  669. out.flush()
  670. self.__finish()
  671. sys.exit()
  672. out.close()
  673. err.close()
  674. return 0
  675. ############################################################
  676. # End __run_tests
  677. ############################################################
  678. ############################################################
  679. # __is_port_bound
  680. # Check if the requested port is available. If it
  681. # isn't available, then a previous test probably didn't
  682. # shutdown properly.
  683. ############################################################
  684. def __is_port_bound(self, port):
  685. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  686. try:
  687. # Try to bind to all IP addresses, this port
  688. s.bind(("", port))
  689. # If we get here, we were able to bind successfully,
  690. # which means the port is free.
  691. except:
  692. # If we get an exception, it might be because the port is still bound
  693. # which would be bad, or maybe it is a privileged port (<1024) and we
  694. # are not running as root, or maybe the server is gone, but sockets are
  695. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  696. # connect.
  697. try:
  698. s.connect(("127.0.0.1", port))
  699. # If we get here, we were able to connect to something, which means
  700. # that the port is still bound.
  701. return True
  702. except:
  703. # An exception means that we couldn't connect, so a server probably
  704. # isn't still running on the port.
  705. pass
  706. finally:
  707. s.close()
  708. return False
  709. ############################################################
  710. # End __is_port_bound
  711. ############################################################
  712. ############################################################
  713. # __parse_results
  714. # Ensures that the system has all necessary software to run
  715. # the tests. This does not include that software for the individual
  716. # test, but covers software such as curl and weighttp that
  717. # are needed.
  718. ############################################################
  719. def __parse_results(self, tests):
  720. # Run the method to get the commmit count of each framework.
  721. self.__count_commits()
  722. # Call the method which counts the sloc for each framework
  723. self.__count_sloc()
  724. # Time to create parsed files
  725. # Aggregate JSON file
  726. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  727. f.write(json.dumps(self.results))
  728. ############################################################
  729. # End __parse_results
  730. ############################################################
  731. #############################################################
  732. # __count_sloc
  733. # This is assumed to be run from the benchmark root directory
  734. #############################################################
  735. def __count_sloc(self):
  736. all_frameworks = self.__gather_frameworks()
  737. jsonResult = {}
  738. for framework in all_frameworks:
  739. try:
  740. command = "cloc --list-file=" + framework['directory'] + "/source_code --yaml"
  741. lineCount = subprocess.check_output(command, shell=True)
  742. # Find the last instance of the word 'code' in the yaml output. This should
  743. # be the line count for the sum of all listed files or just the line count
  744. # for the last file in the case where there's only one file listed.
  745. lineCount = lineCount[lineCount.rfind('code'):len(lineCount)]
  746. lineCount = lineCount.strip('code: ')
  747. lineCount = lineCount[0:lineCount.rfind('comment')]
  748. jsonResult[framework['name']] = int(lineCount)
  749. except:
  750. continue
  751. self.results['rawData']['slocCounts'] = jsonResult
  752. ############################################################
  753. # End __count_sloc
  754. ############################################################
  755. ############################################################
  756. # __count_commits
  757. ############################################################
  758. def __count_commits(self):
  759. all_frameworks = self.__gather_frameworks()
  760. jsonResult = {}
  761. for framework in all_frameworks:
  762. try:
  763. command = "git rev-list HEAD -- " + framework + " | sort -u | wc -l"
  764. commitCount = subprocess.check_output(command, shell=True)
  765. jsonResult[framework] = int(commitCount)
  766. except:
  767. continue
  768. self.results['rawData']['commitCounts'] = jsonResult
  769. self.commits = jsonResult
  770. ############################################################
  771. # End __count_commits
  772. ############################################################
  773. ############################################################
  774. # __write_intermediate_results
  775. ############################################################
  776. def __write_intermediate_results(self,test_name,status_message):
  777. try:
  778. self.results["completed"][test_name] = status_message
  779. with open(os.path.join(self.latest_results_directory, 'results.json'), 'w') as f:
  780. f.write(json.dumps(self.results))
  781. except (IOError):
  782. logging.error("Error writing results.json")
  783. ############################################################
  784. # End __write_intermediate_results
  785. ############################################################
  786. def __load_results(self):
  787. try:
  788. with open(os.path.join(self.latest_results_directory, 'results.json')) as f:
  789. self.results = json.load(f)
  790. except (ValueError, IOError):
  791. pass
  792. ############################################################
  793. # __finish
  794. ############################################################
  795. def __finish(self):
  796. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  797. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  798. ############################################################
  799. # End __finish
  800. ############################################################
  801. ##########################################################################################
  802. # Constructor
  803. ##########################################################################################
  804. ############################################################
  805. # Initialize the benchmarker. The args are the arguments
  806. # parsed via argparser.
  807. ############################################################
  808. def __init__(self, args):
  809. self.__dict__.update(args)
  810. self.start_time = time.time()
  811. self.run_test_timeout_seconds = 3600
  812. # setup logging
  813. logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
  814. # setup some additional variables
  815. if self.database_user == None: self.database_user = self.client_user
  816. if self.database_host == None: self.database_host = self.client_host
  817. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  818. # Remember root directory
  819. self.fwroot = setup_util.get_fwroot()
  820. # setup results and latest_results directories
  821. self.result_directory = os.path.join("results", self.name)
  822. self.latest_results_directory = self.latest_results_directory()
  823. if self.parse != None:
  824. self.timestamp = self.parse
  825. else:
  826. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  827. # Setup the concurrency levels array. This array goes from
  828. # starting_concurrency to max concurrency, doubling each time
  829. self.concurrency_levels = []
  830. concurrency = self.starting_concurrency
  831. while concurrency <= self.max_concurrency:
  832. self.concurrency_levels.append(concurrency)
  833. concurrency = concurrency * 2
  834. # Setup query interval array
  835. # starts at 1, and goes up to max_queries, using the query_interval
  836. self.query_intervals = []
  837. queries = 1
  838. while queries <= self.max_queries:
  839. self.query_intervals.append(queries)
  840. if queries == 1:
  841. queries = 0
  842. queries = queries + self.query_interval
  843. # Load the latest data
  844. #self.latest = None
  845. #try:
  846. # with open('toolset/benchmark/latest.json', 'r') as f:
  847. # # Load json file into config object
  848. # self.latest = json.load(f)
  849. # logging.info("toolset/benchmark/latest.json loaded to self.latest")
  850. # logging.debug("contents of latest.json: " + str(json.dumps(self.latest)))
  851. #except IOError:
  852. # logging.warn("IOError on attempting to read toolset/benchmark/latest.json")
  853. #
  854. #self.results = None
  855. #try:
  856. # if self.latest != None and self.name in self.latest.keys():
  857. # with open(os.path.join(self.result_directory, str(self.latest[self.name]), 'results.json'), 'r') as f:
  858. # # Load json file into config object
  859. # self.results = json.load(f)
  860. #except IOError:
  861. # pass
  862. self.results = None
  863. try:
  864. with open(os.path.join(self.latest_results_directory, 'results.json'), 'r') as f:
  865. #Load json file into results object
  866. self.results = json.load(f)
  867. except IOError:
  868. logging.warn("results.json for test %s not found.",self.name)
  869. if self.results == None:
  870. self.results = dict()
  871. self.results['name'] = self.name
  872. self.results['concurrencyLevels'] = self.concurrency_levels
  873. self.results['queryIntervals'] = self.query_intervals
  874. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  875. self.results['duration'] = self.duration
  876. self.results['rawData'] = dict()
  877. self.results['rawData']['json'] = dict()
  878. self.results['rawData']['db'] = dict()
  879. self.results['rawData']['query'] = dict()
  880. self.results['rawData']['fortune'] = dict()
  881. self.results['rawData']['update'] = dict()
  882. self.results['rawData']['plaintext'] = dict()
  883. self.results['completed'] = dict()
  884. self.results['succeeded'] = dict()
  885. self.results['succeeded']['json'] = []
  886. self.results['succeeded']['db'] = []
  887. self.results['succeeded']['query'] = []
  888. self.results['succeeded']['fortune'] = []
  889. self.results['succeeded']['update'] = []
  890. self.results['succeeded']['plaintext'] = []
  891. self.results['failed'] = dict()
  892. self.results['failed']['json'] = []
  893. self.results['failed']['db'] = []
  894. self.results['failed']['query'] = []
  895. self.results['failed']['fortune'] = []
  896. self.results['failed']['update'] = []
  897. self.results['failed']['plaintext'] = []
  898. self.results['warning'] = dict()
  899. self.results['warning']['json'] = []
  900. self.results['warning']['db'] = []
  901. self.results['warning']['query'] = []
  902. self.results['warning']['fortune'] = []
  903. self.results['warning']['update'] = []
  904. self.results['warning']['plaintext'] = []
  905. else:
  906. #for x in self.__gather_tests():
  907. # if x.name not in self.results['frameworks']:
  908. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  909. # Always overwrite framework list
  910. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  911. # Setup the ssh command string
  912. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  913. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  914. if self.database_identity_file != None:
  915. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  916. if self.client_identity_file != None:
  917. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  918. if self.install is not None:
  919. install = Installer(self, self.install_strategy)
  920. install.install_software()
  921. ############################################################
  922. # End __init__
  923. ############################################################