benchmarker.py 42 KB

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