benchmarker.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. from setup.linux import setup_util
  2. from benchmark import framework_test
  3. from benchmark.test_types import *
  4. from utils import header
  5. from utils import gather_tests
  6. from utils import gather_frameworks
  7. from utils import verify_database_connections
  8. import os
  9. import shutil
  10. import stat
  11. import json
  12. import subprocess
  13. import traceback
  14. import time
  15. import pprint
  16. import csv
  17. import sys
  18. import logging
  19. import socket
  20. import threading
  21. import textwrap
  22. from pprint import pprint
  23. from multiprocessing import Process
  24. from datetime import datetime
  25. # Cross-platform colored text
  26. from colorama import Fore, Back, Style
  27. # Text-based progress indicators
  28. import progressbar
  29. class Benchmarker:
  30. ##########################################################################################
  31. # Public methods
  32. ##########################################################################################
  33. ############################################################
  34. # Prints all the available tests
  35. ############################################################
  36. def run_list_tests(self):
  37. all_tests = self.__gather_tests
  38. for test in all_tests:
  39. print test.name
  40. self.__finish()
  41. ############################################################
  42. # End run_list_tests
  43. ############################################################
  44. ############################################################
  45. # Prints the metadata for all the available tests
  46. ############################################################
  47. def run_list_test_metadata(self, run_finish=True):
  48. all_tests = self.__gather_tests
  49. all_tests_json = json.dumps(map(lambda test: {
  50. "name": test.name,
  51. "approach": test.approach,
  52. "classification": test.classification,
  53. "database": test.database,
  54. "framework": test.framework,
  55. "language": test.language,
  56. "orm": test.orm,
  57. "platform": test.platform,
  58. "webserver": test.webserver,
  59. "os": test.os,
  60. "database_os": test.database_os,
  61. "display_name": test.display_name,
  62. "notes": test.notes,
  63. "versus": test.versus
  64. }, all_tests))
  65. with open(os.path.join(self.full_results_directory(), "test_metadata.json"), "w") as f:
  66. f.write(all_tests_json)
  67. if run_finish:
  68. self.__finish()
  69. ############################################################
  70. # End run_list_test_metadata
  71. ############################################################
  72. ############################################################
  73. # parse_timestamp
  74. # Re-parses the raw data for a given timestamp
  75. ############################################################
  76. def parse_timestamp(self):
  77. all_tests = self.__gather_tests
  78. for test in all_tests:
  79. test.parse_all()
  80. self.__parse_results(all_tests)
  81. self.__finish()
  82. ############################################################
  83. # End parse_timestamp
  84. ############################################################
  85. ############################################################
  86. # Run the tests:
  87. # This process involves setting up the client/server machines
  88. # with any necessary change. Then going through each test,
  89. # running their setup script, verifying the URLs, and
  90. # running benchmarks against them.
  91. ############################################################
  92. def run(self):
  93. ##########################
  94. # Generate metadata
  95. ##########################
  96. self.run_list_test_metadata(False)
  97. ##########################
  98. # Get a list of all known
  99. # tests that we can run.
  100. ##########################
  101. all_tests = self.__gather_tests
  102. ##########################
  103. # Setup client/server
  104. ##########################
  105. print header("Preparing Server, Database, and Client ...", top='=', bottom='=')
  106. self.__setup_server()
  107. self.__setup_database()
  108. self.__setup_client()
  109. ## Check if wrk (and wrk-pipeline) is installed and executable, if not, raise an exception
  110. #if not (os.access("/usr/local/bin/wrk", os.X_OK) and os.access("/usr/local/bin/wrk-pipeline", os.X_OK)):
  111. # raise Exception("wrk and/or wrk-pipeline are not properly installed. Not running tests.")
  112. ##########################
  113. # Run tests
  114. ##########################
  115. print header("Running Tests...", top='=', bottom='=')
  116. result = self.__run_tests(all_tests)
  117. ##########################
  118. # Parse results
  119. ##########################
  120. if self.mode == "benchmark":
  121. print header("Parsing Results ...", top='=', bottom='=')
  122. self.__parse_results(all_tests)
  123. self.__finish()
  124. return result
  125. ############################################################
  126. # End run
  127. ############################################################
  128. ############################################################
  129. # database_sftp_string(batch_file)
  130. # generates a fully qualified URL for sftp to database
  131. ############################################################
  132. def database_sftp_string(self, batch_file):
  133. sftp_string = "sftp -oStrictHostKeyChecking=no "
  134. if batch_file != None: sftp_string += " -b " + batch_file + " "
  135. if self.database_identity_file != None:
  136. sftp_string += " -i " + self.database_identity_file + " "
  137. return sftp_string + self.database_user + "@" + self.database_host
  138. ############################################################
  139. # End database_sftp_string
  140. ############################################################
  141. ############################################################
  142. # client_sftp_string(batch_file)
  143. # generates a fully qualified URL for sftp to client
  144. ############################################################
  145. def client_sftp_string(self, batch_file):
  146. sftp_string = "sftp -oStrictHostKeyChecking=no "
  147. if batch_file != None: sftp_string += " -b " + batch_file + " "
  148. if self.client_identity_file != None:
  149. sftp_string += " -i " + self.client_identity_file + " "
  150. return sftp_string + self.client_user + "@" + self.client_host
  151. ############################################################
  152. # End client_sftp_string
  153. ############################################################
  154. ############################################################
  155. # generate_url(url, port)
  156. # generates a fully qualified URL for accessing a test url
  157. ############################################################
  158. def generate_url(self, url, port):
  159. return self.server_host + ":" + str(port) + url
  160. ############################################################
  161. # End generate_url
  162. ############################################################
  163. ############################################################
  164. # get_output_file(test_name, test_type)
  165. # returns the output file name for this test_name and
  166. # test_type timestamp/test_type/test_name/raw
  167. ############################################################
  168. def get_output_file(self, test_name, test_type):
  169. return os.path.join(self.result_directory, self.timestamp, test_name, test_type, "raw")
  170. ############################################################
  171. # End get_output_file
  172. ############################################################
  173. ############################################################
  174. # output_file(test_name, test_type)
  175. # returns the output file for this test_name and test_type
  176. # timestamp/test_type/test_name/raw
  177. ############################################################
  178. def output_file(self, test_name, test_type):
  179. path = self.get_output_file(test_name, test_type)
  180. try:
  181. os.makedirs(os.path.dirname(path))
  182. except OSError:
  183. pass
  184. return path
  185. ############################################################
  186. # End output_file
  187. ############################################################
  188. ############################################################
  189. # get_stats_file(test_name, test_type)
  190. # returns the stats file name for this test_name and
  191. # test_type timestamp/test_type/test_name/raw
  192. ############################################################
  193. def get_stats_file(self, test_name, test_type):
  194. return os.path.join(self.result_directory, self.timestamp, test_name, test_type, "stats")
  195. ############################################################
  196. # End get_stats_file
  197. ############################################################
  198. ############################################################
  199. # stats_file(test_name, test_type)
  200. # returns the stats file for this test_name and test_type
  201. # timestamp/test_type/test_name/raw
  202. ############################################################
  203. def stats_file(self, test_name, test_type):
  204. path = self.get_stats_file(test_name, test_type)
  205. try:
  206. os.makedirs(os.path.dirname(path))
  207. except OSError:
  208. pass
  209. return path
  210. ############################################################
  211. # End stats_file
  212. ############################################################
  213. ############################################################
  214. # full_results_directory
  215. ############################################################
  216. def full_results_directory(self):
  217. path = os.path.join(self.fwroot, self.result_directory, self.timestamp)
  218. try:
  219. os.makedirs(path)
  220. except OSError:
  221. pass
  222. return path
  223. ############################################################
  224. # End full_results_directory
  225. ############################################################
  226. ############################################################
  227. # report_verify_results
  228. # Used by FrameworkTest to add verification details to our results
  229. #
  230. # TODO: Technically this is an IPC violation - we are accessing
  231. # the parent process' memory from the child process
  232. ############################################################
  233. def report_verify_results(self, framework, test, result):
  234. if framework.name not in self.results['verify'].keys():
  235. self.results['verify'][framework.name] = dict()
  236. self.results['verify'][framework.name][test] = result
  237. ############################################################
  238. # report_benchmark_results
  239. # Used by FrameworkTest to add benchmark data to this
  240. #
  241. # TODO: Technically this is an IPC violation - we are accessing
  242. # the parent process' memory from the child process
  243. ############################################################
  244. def report_benchmark_results(self, framework, test, results):
  245. if test not in self.results['rawData'].keys():
  246. self.results['rawData'][test] = dict()
  247. # If results has a size from the parse, then it succeeded.
  248. if results:
  249. self.results['rawData'][test][framework.name] = results
  250. # This may already be set for single-tests
  251. if framework.name not in self.results['succeeded'][test]:
  252. self.results['succeeded'][test].append(framework.name)
  253. else:
  254. # This may already be set for single-tests
  255. if framework.name not in self.results['failed'][test]:
  256. self.results['failed'][test].append(framework.name)
  257. ############################################################
  258. # End report_results
  259. ############################################################
  260. ##########################################################################################
  261. # Private methods
  262. ##########################################################################################
  263. ############################################################
  264. # Gathers all the tests
  265. ############################################################
  266. @property
  267. def __gather_tests(self):
  268. tests = gather_tests(include=self.test,
  269. exclude=self.exclude,
  270. benchmarker=self)
  271. # If the tests have been interrupted somehow, then we want to resume them where we left
  272. # off, rather than starting from the beginning
  273. if os.path.isfile(self.current_benchmark):
  274. with open(self.current_benchmark, 'r') as interrupted_benchmark:
  275. interrupt_bench = interrupted_benchmark.read().strip()
  276. for index, atest in enumerate(tests):
  277. if atest.name == interrupt_bench:
  278. tests = tests[index:]
  279. break
  280. return tests
  281. ############################################################
  282. # End __gather_tests
  283. ############################################################
  284. ############################################################
  285. # Makes any necessary changes to the server that should be
  286. # made before running the tests. This involves setting kernal
  287. # settings to allow for more connections, or more file
  288. # descriptiors
  289. #
  290. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  291. ############################################################
  292. def __setup_server(self):
  293. try:
  294. if os.name == 'nt':
  295. return True
  296. subprocess.call(['sudo', 'sysctl', '-w', 'net.ipv4.tcp_max_syn_backlog=65535'])
  297. subprocess.call(['sudo', 'sysctl', '-w', 'net.core.somaxconn=65535'])
  298. subprocess.call(['sudo', '-s', 'ulimit', '-n', '65535'])
  299. subprocess.call(['sudo', 'sysctl', 'net.ipv4.tcp_tw_reuse=1'])
  300. subprocess.call(['sudo', 'sysctl', 'net.ipv4.tcp_tw_recycle=1'])
  301. subprocess.call(['sudo', 'sysctl', '-w', 'kernel.shmmax=134217728'])
  302. subprocess.call(['sudo', 'sysctl', '-w', 'kernel.shmall=2097152'])
  303. with open(os.path.join(self.full_results_directory(), 'sysctl.txt'), 'w') as f:
  304. f.write(subprocess.check_output(['sudo','sysctl','-a']))
  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(self.current_benchmark, '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(self.current_benchmark, '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(self.current_benchmark):
  420. os.remove(self.current_benchmark)
  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(), 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 postgresql restart
  481. sudo service cassandra restart
  482. /opt/elasticsearch/elasticsearch restart
  483. """)
  484. time.sleep(10)
  485. st = verify_database_connections([
  486. ("mysql", self.database_host, 3306),
  487. ("mongodb", self.database_host, 27017),
  488. ("postgresql", self.database_host, 5432),
  489. ("cassandra", self.database_host, 9160),
  490. ("elasticsearch", self.database_host, 9200)
  491. ])
  492. print "database connection test results:\n" + "\n".join(st[1])
  493. self.__cleanup_leftover_processes_before_test();
  494. if self.__is_port_bound(test.port):
  495. # We gave it our all
  496. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  497. out.write(header("Error: Port %s is not available, cannot start %s" % (test.port, test.name)))
  498. out.flush()
  499. print "Error: Unable to recover port, cannot start test"
  500. return exit_with_code(1)
  501. result, process = test.start(out)
  502. if result != 0:
  503. self.__stop_test(out, process)
  504. time.sleep(5)
  505. out.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  506. out.flush()
  507. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  508. return exit_with_code(1)
  509. logging.info("Sleeping %s seconds to ensure framework is ready" % self.sleep)
  510. time.sleep(self.sleep)
  511. ##########################
  512. # Verify URLs
  513. ##########################
  514. logging.info("Verifying framework URLs")
  515. passed_verify = test.verify_urls(logDir)
  516. ##########################
  517. # Nuke /tmp
  518. ##########################
  519. try:
  520. subprocess.check_call('sudo rm -rf /tmp/*', shell=True, stderr=out, stdout=out)
  521. except Exception:
  522. out.write(header("Error: Could not empty /tmp"))
  523. ##########################
  524. # Benchmark this test
  525. ##########################
  526. if self.mode == "benchmark":
  527. logging.info("Benchmarking")
  528. out.write(header("Benchmarking %s" % test.name))
  529. out.flush()
  530. test.benchmark(logDir)
  531. ##########################
  532. # Stop this test
  533. ##########################
  534. out.write(header("Stopping %s" % test.name))
  535. out.flush()
  536. self.__stop_test(out, process)
  537. out.flush()
  538. time.sleep(5)
  539. if self.__is_port_bound(test.port):
  540. # This can happen sometimes - let's try again
  541. self.__stop_test(out, process)
  542. out.flush()
  543. time.sleep(5)
  544. if self.__is_port_bound(test.port):
  545. # We gave it our all
  546. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  547. out.write(header("Error: Port %s was not released by stop %s" % (test.port, test.name)))
  548. out.flush()
  549. return exit_with_code(1)
  550. out.write(header("Stopped %s" % test.name))
  551. out.flush()
  552. ##########################################################
  553. # Remove contents of /tmp folder
  554. ##########################################################
  555. if self.clear_tmp:
  556. try:
  557. filelist = [ f for f in os.listdir("/tmp") ]
  558. for f in filelist:
  559. try:
  560. os.remove("/tmp/" + f)
  561. except OSError as err:
  562. print "Failed to remove " + str(f) + " from /tmp directory: " + str(err)
  563. except OSError:
  564. print "Failed to remove contents of /tmp directory."
  565. ##########################################################
  566. # Save results thus far into the latest results directory
  567. ##########################################################
  568. out.write(header("Saving results through %s" % test.name))
  569. out.flush()
  570. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  571. if self.mode == "verify" and not passed_verify:
  572. print "Failed verify!"
  573. return exit_with_code(1)
  574. except (OSError, IOError, subprocess.CalledProcessError) as e:
  575. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  576. out.write(header("Subprocess Error %s" % test.name))
  577. traceback.print_exc(file=out)
  578. out.flush()
  579. try:
  580. self.__stop_test(out, process)
  581. except (subprocess.CalledProcessError) as e:
  582. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  583. out.write(header("Subprocess Error: Test .stop() raised exception %s" % test.name))
  584. traceback.print_exc(file=out)
  585. out.flush()
  586. out.close()
  587. return exit_with_code(1)
  588. # TODO - subprocess should not catch this exception!
  589. # Parent process should catch it and cleanup/exit
  590. except (KeyboardInterrupt) as e:
  591. self.__stop_test(out, process)
  592. out.write(header("Cleaning up..."))
  593. out.flush()
  594. self.__finish()
  595. sys.exit(1)
  596. out.close()
  597. return exit_with_code(0)
  598. ############################################################
  599. # End __run_tests
  600. ############################################################
  601. ############################################################
  602. # __stop_test(benchmarker)
  603. # Stops all running tests
  604. ############################################################
  605. def __stop_test(self, out, process):
  606. if process is not None and process.poll() is None:
  607. # Stop
  608. pids = self.__find_child_processes(process.pid)
  609. if pids is not None:
  610. stop = ['kill', '-STOP'] + pids
  611. subprocess.call(stop, stderr=out, stdout=out)
  612. pids = self.__find_child_processes(process.pid)
  613. if pids is not None:
  614. term = ['kill', '-TERM'] + pids
  615. subprocess.call(term, stderr=out, stdout=out)
  616. # Okay, if there are any more PIDs, kill them harder
  617. pids = self.__find_child_processes(process.pid)
  618. if pids is not None:
  619. kill = ['kill', '-KILL'] + pids
  620. subprocess.call(kill, stderr=out, stdout=out)
  621. process.terminate()
  622. ############################################################
  623. # End __stop_test
  624. ############################################################
  625. ############################################################
  626. # __find_child_processes
  627. # Recursively finds all child processes for the given PID.
  628. ############################################################
  629. def __find_child_processes(self, pid):
  630. toRet = []
  631. try:
  632. pids = subprocess.check_output(['pgrep','-P',str(pid)]).split()
  633. toRet.extend(pids)
  634. for aPid in pids:
  635. toRet.extend(self.__find_child_processes(aPid))
  636. except:
  637. # pgrep will return a non-zero status code if there are no
  638. # processes who have a PPID of PID.
  639. pass
  640. return toRet
  641. ############################################################
  642. # End __find_child_processes
  643. ############################################################
  644. def is_port_bound(self, port):
  645. return self.__is_port_bound(port)
  646. ############################################################
  647. # __is_port_bound
  648. # Check if the requested port is available. If it
  649. # isn't available, then a previous test probably didn't
  650. # shutdown properly.
  651. ############################################################
  652. def __is_port_bound(self, port):
  653. port = int(port)
  654. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  655. try:
  656. # Try to bind to all IP addresses, this port
  657. s.bind(("", port))
  658. # If we get here, we were able to bind successfully,
  659. # which means the port is free.
  660. except socket.error:
  661. # If we get an exception, it might be because the port is still bound
  662. # which would be bad, or maybe it is a privileged port (<1024) and we
  663. # are not running as root, or maybe the server is gone, but sockets are
  664. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  665. # connect.
  666. try:
  667. s.connect(("127.0.0.1", port))
  668. # If we get here, we were able to connect to something, which means
  669. # that the port is still bound.
  670. return True
  671. except socket.error:
  672. # An exception means that we couldn't connect, so a server probably
  673. # isn't still running on the port.
  674. pass
  675. finally:
  676. s.close()
  677. return False
  678. ############################################################
  679. # End __is_port_bound
  680. ############################################################
  681. ############################################################
  682. # __parse_results
  683. # Ensures that the system has all necessary software to run
  684. # the tests. This does not include that software for the individual
  685. # test, but covers software such as curl and weighttp that
  686. # are needed.
  687. ############################################################
  688. def __parse_results(self, tests):
  689. # Run the method to get the commmit count of each framework.
  690. self.__count_commits()
  691. # Call the method which counts the sloc for each framework
  692. self.__count_sloc()
  693. # Time to create parsed files
  694. # Aggregate JSON file
  695. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  696. f.write(json.dumps(self.results, indent=2))
  697. ############################################################
  698. # End __parse_results
  699. ############################################################
  700. #############################################################
  701. # __count_sloc
  702. #############################################################
  703. def __count_sloc(self):
  704. frameworks = gather_frameworks(include=self.test,
  705. exclude=self.exclude, benchmarker=self)
  706. jsonResult = {}
  707. for framework, testlist in frameworks.iteritems():
  708. if not os.path.exists(os.path.join(testlist[0].directory, "source_code")):
  709. logging.warn("Cannot count lines of code for %s - no 'source_code' file", framework)
  710. continue
  711. # Unfortunately the source_code files use lines like
  712. # ./cpoll_cppsp/www/fortune_old instead of
  713. # ./www/fortune_old
  714. # so we have to back our working dir up one level
  715. wd = os.path.dirname(testlist[0].directory)
  716. try:
  717. command = "cloc --list-file=%s/source_code --yaml" % testlist[0].directory
  718. if os.path.exists(os.path.join(testlist[0].directory, "cloc_defs.txt")):
  719. command += " --read-lang-def %s" % os.path.join(testlist[0].directory, "cloc_defs.txt")
  720. logging.info("Using custom cloc definitions for %s", framework)
  721. # Find the last instance of the word 'code' in the yaml output. This should
  722. # be the line count for the sum of all listed files or just the line count
  723. # for the last file in the case where there's only one file listed.
  724. command = command + "| grep code | tail -1 | cut -d: -f 2"
  725. logging.debug("Running \"%s\" (cwd=%s)", command, wd)
  726. lineCount = subprocess.check_output(command, cwd=wd, shell=True)
  727. jsonResult[framework] = int(lineCount)
  728. except subprocess.CalledProcessError:
  729. continue
  730. except ValueError as ve:
  731. logging.warn("Unable to get linecount for %s due to error '%s'", framework, ve)
  732. self.results['rawData']['slocCounts'] = jsonResult
  733. ############################################################
  734. # End __count_sloc
  735. ############################################################
  736. ############################################################
  737. # __count_commits
  738. #
  739. ############################################################
  740. def __count_commits(self):
  741. frameworks = gather_frameworks(include=self.test,
  742. exclude=self.exclude, benchmarker=self)
  743. def count_commit(directory, jsonResult):
  744. command = "git rev-list HEAD -- " + directory + " | sort -u | wc -l"
  745. try:
  746. commitCount = subprocess.check_output(command, shell=True)
  747. jsonResult[framework] = int(commitCount)
  748. except subprocess.CalledProcessError:
  749. pass
  750. # Because git can be slow when run in large batches, this
  751. # calls git up to 4 times in parallel. Normal improvement is ~3-4x
  752. # in my trials, or ~100 seconds down to ~25
  753. # This is safe to parallelize as long as each thread only
  754. # accesses one key in the dictionary
  755. threads = []
  756. jsonResult = {}
  757. t1 = datetime.now()
  758. for framework, testlist in frameworks.iteritems():
  759. directory = testlist[0].directory
  760. t = threading.Thread(target=count_commit, args=(directory,jsonResult))
  761. t.start()
  762. threads.append(t)
  763. # Git has internal locks, full parallel will just cause contention
  764. # and slowness, so we rate-limit a bit
  765. if len(threads) >= 4:
  766. threads[0].join()
  767. threads.remove(threads[0])
  768. # Wait for remaining threads
  769. for t in threads:
  770. t.join()
  771. t2 = datetime.now()
  772. # print "Took %s seconds " % (t2 - t1).seconds
  773. self.results['rawData']['commitCounts'] = jsonResult
  774. self.commits = jsonResult
  775. ############################################################
  776. # End __count_commits
  777. ############################################################
  778. ############################################################
  779. # __write_intermediate_results
  780. ############################################################
  781. def __write_intermediate_results(self,test_name,status_message):
  782. try:
  783. self.results["completed"][test_name] = status_message
  784. with open(os.path.join(self.full_results_directory(), 'results.json'), 'w') as f:
  785. f.write(json.dumps(self.results, indent=2))
  786. except (IOError):
  787. logging.error("Error writing results.json")
  788. ############################################################
  789. # End __write_intermediate_results
  790. ############################################################
  791. def __load_results(self):
  792. try:
  793. with open(os.path.join(self.full_results_directory(), 'results.json')) as f:
  794. self.results = json.load(f)
  795. except (ValueError, IOError):
  796. pass
  797. ############################################################
  798. # __finish
  799. ############################################################
  800. def __finish(self):
  801. if not self.list_tests and not self.list_test_metadata and not self.parse:
  802. tests = self.__gather_tests
  803. # Normally you don't have to use Fore.BLUE before each line, but
  804. # Travis-CI seems to reset color codes on newline (see travis-ci/travis-ci#2692)
  805. # or stream flush, so we have to ensure that the color code is printed repeatedly
  806. prefix = Fore.CYAN
  807. for line in header("Verification Summary", top='=', bottom='').split('\n'):
  808. print prefix + line
  809. for test in tests:
  810. print prefix + "| Test: %s" % test.name
  811. if test.name in self.results['verify'].keys():
  812. for test_type, result in self.results['verify'][test.name].iteritems():
  813. if result.upper() == "PASS":
  814. color = Fore.GREEN
  815. elif result.upper() == "WARN":
  816. color = Fore.YELLOW
  817. else:
  818. color = Fore.RED
  819. print prefix + "| " + test_type.ljust(11) + ' : ' + color + result.upper()
  820. else:
  821. print prefix + "| " + Fore.RED + "NO RESULTS (Did framework launch?)"
  822. print prefix + header('', top='', bottom='=') + Style.RESET_ALL
  823. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  824. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  825. ############################################################
  826. # End __finish
  827. ############################################################
  828. ##########################################################################################
  829. # Constructor
  830. ##########################################################################################
  831. ############################################################
  832. # Initialize the benchmarker. The args are the arguments
  833. # parsed via argparser.
  834. ############################################################
  835. def __init__(self, args):
  836. # Map type strings to their objects
  837. types = dict()
  838. types['json'] = JsonTestType()
  839. types['db'] = DBTestType()
  840. types['query'] = QueryTestType()
  841. types['fortune'] = FortuneTestType()
  842. types['update'] = UpdateTestType()
  843. types['plaintext'] = PlaintextTestType()
  844. # Turn type into a map instead of a string
  845. if args['type'] == 'all':
  846. args['types'] = types
  847. else:
  848. args['types'] = { args['type'] : types[args['type']] }
  849. del args['type']
  850. args['max_threads'] = args['threads']
  851. args['max_concurrency'] = max(args['concurrency_levels'])
  852. self.__dict__.update(args)
  853. # pprint(self.__dict__)
  854. self.start_time = time.time()
  855. self.run_test_timeout_seconds = 7200
  856. # setup logging
  857. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  858. # setup some additional variables
  859. if self.database_user == None: self.database_user = self.client_user
  860. if self.database_host == None: self.database_host = self.client_host
  861. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  862. # Remember root directory
  863. self.fwroot = setup_util.get_fwroot()
  864. # setup current_benchmark.txt location
  865. self.current_benchmark = "/tmp/current_benchmark.txt"
  866. if hasattr(self, 'parse') and self.parse != None:
  867. self.timestamp = self.parse
  868. else:
  869. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  870. # setup results and latest_results directories
  871. self.result_directory = os.path.join(self.fwroot, "results")
  872. if (args['clean'] or args['clean_all']) and os.path.exists(os.path.join(self.fwroot, "results")):
  873. shutil.rmtree(os.path.join(self.fwroot, "results"))
  874. # remove installs directories if --clean-all provided
  875. self.install_root = "%s/%s" % (self.fwroot, "installs")
  876. if args['clean_all']:
  877. os.system("sudo rm -rf " + self.install_root)
  878. os.mkdir(self.install_root)
  879. self.results = None
  880. try:
  881. with open(os.path.join(self.full_results_directory(), 'results.json'), 'r') as f:
  882. #Load json file into results object
  883. self.results = json.load(f)
  884. except IOError:
  885. logging.warn("results.json for test not found.")
  886. if self.results == None:
  887. self.results = dict()
  888. self.results['concurrencyLevels'] = self.concurrency_levels
  889. self.results['queryIntervals'] = self.query_levels
  890. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  891. self.results['duration'] = self.duration
  892. self.results['rawData'] = dict()
  893. self.results['rawData']['json'] = dict()
  894. self.results['rawData']['db'] = dict()
  895. self.results['rawData']['query'] = dict()
  896. self.results['rawData']['fortune'] = dict()
  897. self.results['rawData']['update'] = dict()
  898. self.results['rawData']['plaintext'] = dict()
  899. self.results['completed'] = dict()
  900. self.results['succeeded'] = dict()
  901. self.results['succeeded']['json'] = []
  902. self.results['succeeded']['db'] = []
  903. self.results['succeeded']['query'] = []
  904. self.results['succeeded']['fortune'] = []
  905. self.results['succeeded']['update'] = []
  906. self.results['succeeded']['plaintext'] = []
  907. self.results['failed'] = dict()
  908. self.results['failed']['json'] = []
  909. self.results['failed']['db'] = []
  910. self.results['failed']['query'] = []
  911. self.results['failed']['fortune'] = []
  912. self.results['failed']['update'] = []
  913. self.results['failed']['plaintext'] = []
  914. self.results['verify'] = dict()
  915. else:
  916. #for x in self.__gather_tests():
  917. # if x.name not in self.results['frameworks']:
  918. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  919. # Always overwrite framework list
  920. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  921. # Setup the ssh command string
  922. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  923. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  924. if self.database_identity_file != None:
  925. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  926. if self.client_identity_file != None:
  927. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  928. ############################################################
  929. # End __init__
  930. ############################################################