benchmarker.py 42 KB

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