benchmarker.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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, self.logs_directory, 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, self.logs_directory, 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.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"])
  297. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  298. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  299. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  300. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  301. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  302. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  303. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  304. except subprocess.CalledProcessError:
  305. return False
  306. ############################################################
  307. # End __setup_server
  308. ############################################################
  309. ############################################################
  310. # Clean up any processes that run with root privileges
  311. ############################################################
  312. def __cleanup_leftover_processes_before_test(self):
  313. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  314. p.communicate("""
  315. sudo /etc/init.d/apache2 stop
  316. """)
  317. ############################################################
  318. # Makes any necessary changes to the database machine that
  319. # should be made before running the tests. Is very similar
  320. # to the server setup, but may also include database specific
  321. # changes.
  322. ############################################################
  323. def __setup_database(self):
  324. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  325. p.communicate("""
  326. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  327. sudo sysctl -w net.core.somaxconn=65535
  328. sudo sysctl -w kernel.sched_autogroup_enabled=0
  329. sudo -s ulimit -n 65535
  330. sudo sysctl net.ipv4.tcp_tw_reuse=1
  331. sudo sysctl net.ipv4.tcp_tw_recycle=1
  332. sudo sysctl -w kernel.shmmax=2147483648
  333. sudo sysctl -w kernel.shmall=2097152
  334. sudo sysctl -w kernel.sem="250 32000 256 512"
  335. """)
  336. # TODO - print kernel configuration to file
  337. # echo "Printing kernel configuration:" && sudo sysctl -a
  338. # Explanations:
  339. # net.ipv4.tcp_max_syn_backlog, net.core.somaxconn, kernel.sched_autogroup_enabled: http://tweaked.io/guide/kernel/
  340. # ulimit -n: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/
  341. # net.ipv4.tcp_tw_*: http://www.linuxbrigade.com/reduce-time_wait-socket-connections/
  342. # kernel.shm*: http://seriousbirder.com/blogs/linux-understanding-shmmax-and-shmall-settings/
  343. # 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
  344. ############################################################
  345. # End __setup_database
  346. ############################################################
  347. ############################################################
  348. # Makes any necessary changes to the client machine that
  349. # should be made before running the tests. Is very similar
  350. # to the server setup, but may also include client specific
  351. # changes.
  352. ############################################################
  353. def __setup_client(self):
  354. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  355. p.communicate("""
  356. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  357. sudo sysctl -w net.core.somaxconn=65535
  358. sudo -s ulimit -n 65535
  359. sudo sysctl net.ipv4.tcp_tw_reuse=1
  360. sudo sysctl net.ipv4.tcp_tw_recycle=1
  361. sudo sysctl -w kernel.shmmax=2147483648
  362. sudo sysctl -w kernel.shmall=2097152
  363. """)
  364. ############################################################
  365. # End __setup_client
  366. ############################################################
  367. ############################################################
  368. # __run_tests
  369. #
  370. # 2013-10-02 ASB Calls each test passed in tests to
  371. # __run_test in a separate process. Each
  372. # test is given a set amount of time and if
  373. # kills the child process (and subsequently
  374. # all of its child processes). Uses
  375. # multiprocessing module.
  376. ############################################################
  377. def __run_tests(self, tests):
  378. if len(tests) == 0:
  379. return 0
  380. logging.debug("Start __run_tests.")
  381. logging.debug("__name__ = %s",__name__)
  382. error_happened = False
  383. if self.os.lower() == 'windows':
  384. logging.debug("Executing __run_tests on Windows")
  385. for test in tests:
  386. with open(self.current_benchmark, 'w') as benchmark_resume_file:
  387. benchmark_resume_file.write(test.name)
  388. if self.__run_test(test) != 0:
  389. error_happened = True
  390. else:
  391. logging.debug("Executing __run_tests on Linux")
  392. # Setup a nice progressbar and ETA indicator
  393. widgets = [self.mode, ': ', progressbar.Percentage(),
  394. ' ', progressbar.Bar(),
  395. ' Rough ', progressbar.ETA()]
  396. pbar = progressbar.ProgressBar(widgets=widgets, maxval=len(tests)).start()
  397. pbar_test = 0
  398. # These features do not work on Windows
  399. for test in tests:
  400. pbar.update(pbar_test)
  401. pbar_test = pbar_test + 1
  402. if __name__ == 'benchmark.benchmarker':
  403. print header("Running Test: %s" % test.name)
  404. with open(self.current_benchmark, 'w') as benchmark_resume_file:
  405. benchmark_resume_file.write(test.name)
  406. test_process = Process(target=self.__run_test, name="Test Runner (%s)" % test.name, args=(test,))
  407. test_process.start()
  408. test_process.join(self.run_test_timeout_seconds)
  409. self.__load_results() # Load intermediate result from child process
  410. if(test_process.is_alive()):
  411. logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
  412. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  413. test_process.terminate()
  414. test_process.join()
  415. if test_process.exitcode != 0:
  416. error_happened = True
  417. pbar.finish()
  418. if os.path.isfile(self.current_benchmark):
  419. os.remove(self.current_benchmark)
  420. logging.debug("End __run_tests.")
  421. if error_happened:
  422. return 1
  423. return 0
  424. ############################################################
  425. # End __run_tests
  426. ############################################################
  427. ############################################################
  428. # __run_test
  429. # 2013-10-02 ASB Previously __run_tests. This code now only
  430. # processes a single test.
  431. #
  432. # Ensures that the system has all necessary software to run
  433. # the tests. This does not include that software for the individual
  434. # test, but covers software such as curl and weighttp that
  435. # are needed.
  436. ############################################################
  437. def __run_test(self, test):
  438. # Used to capture return values
  439. def exit_with_code(code):
  440. if self.os.lower() == 'windows':
  441. return code
  442. else:
  443. sys.exit(code)
  444. logDir = os.path.join(self.full_results_directory(), self.logs_directory, test.name.lower())
  445. try:
  446. os.makedirs(logDir)
  447. except Exception:
  448. pass
  449. with open(os.path.join(logDir, 'out.txt'), 'w') as out:
  450. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  451. out.write("OS or Database OS specified in benchmark_config.json does not match the current environment. Skipping.\n")
  452. return exit_with_code(0)
  453. # If the test is in the excludes list, we skip it
  454. if self.exclude != None and test.name in self.exclude:
  455. out.write("Test {name} has been added to the excludes list. Skipping.\n".format(name=test.name))
  456. return exit_with_code(0)
  457. out.write("test.os.lower() = {os} test.database_os.lower() = {dbos}\n".format(os=test.os.lower(),dbos=test.database_os.lower()))
  458. out.write("self.results['frameworks'] != None: {val}\n".format(val=str(self.results['frameworks'] != None)))
  459. out.write("test.name: {name}\n".format(name=str(test.name)))
  460. out.write("self.results['completed']: {completed}\n".format(completed=str(self.results['completed'])))
  461. if self.results['frameworks'] != None and test.name in self.results['completed']:
  462. out.write('Framework {name} found in latest saved data. Skipping.\n'.format(name=str(test.name)))
  463. print 'WARNING: Test {test} exists in the results directory; this must be removed before running a new test.\n'.format(test=str(test.name))
  464. return exit_with_code(1)
  465. out.flush()
  466. out.write(header("Beginning %s" % test.name, top='='))
  467. out.flush()
  468. ##########################
  469. # Start this test
  470. ##########################
  471. out.write(header("Starting %s" % test.name))
  472. out.flush()
  473. try:
  474. if test.requires_database():
  475. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=out, shell=True)
  476. p.communicate("""
  477. sudo restart mysql
  478. sudo restart mongod
  479. sudo service postgresql restart
  480. sudo service cassandra restart
  481. /opt/elasticsearch/elasticsearch restart
  482. """)
  483. time.sleep(10)
  484. st = verify_database_connections([
  485. ("mysql", self.database_host, 3306),
  486. ("mongodb", self.database_host, 27017),
  487. ("postgresql", self.database_host, 5432),
  488. ("cassandra", self.database_host, 9160),
  489. ("elasticsearch", self.database_host, 9200)
  490. ])
  491. print "database connection test results:\n" + "\n".join(st[1])
  492. self.__cleanup_leftover_processes_before_test();
  493. if self.__is_port_bound(test.port):
  494. # We gave it our all
  495. self.__write_intermediate_results(test.name, "port " + str(test.port) + " is not available before start")
  496. out.write(header("Error: Port %s is not available, cannot start %s" % (test.port, test.name)))
  497. out.flush()
  498. print "Error: Unable to recover port, cannot start test"
  499. return exit_with_code(1)
  500. result, process = test.start(out)
  501. if result != 0:
  502. self.__stop_test(out, process)
  503. time.sleep(5)
  504. out.write( "ERROR: Problem starting {name}\n".format(name=test.name) )
  505. out.flush()
  506. self.__write_intermediate_results(test.name,"<setup.py>#start() returned non-zero")
  507. return exit_with_code(1)
  508. logging.info("Sleeping %s seconds to ensure framework is ready" % self.sleep)
  509. time.sleep(self.sleep)
  510. ##########################
  511. # Verify URLs
  512. ##########################
  513. logging.info("Verifying framework URLs")
  514. passed_verify = test.verify_urls(logDir)
  515. ##########################
  516. # Nuke /tmp
  517. ##########################
  518. try:
  519. subprocess.check_call('sudo rm -rf /tmp/*', shell=True, stderr=out, stdout=out)
  520. except Exception:
  521. out.write(header("Error: Could not empty /tmp"))
  522. ##########################
  523. # Benchmark this test
  524. ##########################
  525. if self.mode == "benchmark":
  526. logging.info("Benchmarking")
  527. out.write(header("Benchmarking %s" % test.name))
  528. out.flush()
  529. test.benchmark(logDir)
  530. ##########################
  531. # Stop this test
  532. ##########################
  533. out.write(header("Stopping %s" % test.name))
  534. out.flush()
  535. self.__stop_test(out, process)
  536. out.flush()
  537. time.sleep(5)
  538. if self.__is_port_bound(test.port):
  539. # This can happen sometimes - let's try again
  540. self.__stop_test(out, process)
  541. out.flush()
  542. time.sleep(5)
  543. if self.__is_port_bound(test.port):
  544. # We gave it our all
  545. self.__write_intermediate_results(test.name, "port " + str(test.port) + " was not released by stop")
  546. out.write(header("Error: Port %s was not released by stop %s" % (test.port, test.name)))
  547. out.flush()
  548. return exit_with_code(1)
  549. out.write(header("Stopped %s" % test.name))
  550. out.flush()
  551. ##########################################################
  552. # Remove contents of /tmp folder
  553. ##########################################################
  554. if self.clear_tmp:
  555. try:
  556. filelist = [ f for f in os.listdir("/tmp") ]
  557. for f in filelist:
  558. try:
  559. os.remove("/tmp/" + f)
  560. except OSError as err:
  561. print "Failed to remove " + str(f) + " from /tmp directory: " + str(err)
  562. except OSError:
  563. print "Failed to remove contents of /tmp directory."
  564. ##########################################################
  565. # Save results thus far into the latest results directory
  566. ##########################################################
  567. out.write(header("Saving results through %s" % test.name))
  568. out.flush()
  569. self.__write_intermediate_results(test.name,time.strftime("%Y%m%d%H%M%S", time.localtime()))
  570. if self.mode == "verify" and not passed_verify:
  571. print "Failed verify!"
  572. return exit_with_code(1)
  573. except (OSError, IOError, subprocess.CalledProcessError) as e:
  574. self.__write_intermediate_results(test.name,"<setup.py> raised an exception")
  575. out.write(header("Subprocess Error %s" % test.name))
  576. traceback.print_exc(file=out)
  577. out.flush()
  578. try:
  579. self.__stop_test(out, process)
  580. except (subprocess.CalledProcessError) as e:
  581. self.__write_intermediate_results(test.name,"<setup.py>#stop() raised an error")
  582. out.write(header("Subprocess Error: Test .stop() raised exception %s" % test.name))
  583. traceback.print_exc(file=out)
  584. out.flush()
  585. out.close()
  586. return exit_with_code(1)
  587. # TODO - subprocess should not catch this exception!
  588. # Parent process should catch it and cleanup/exit
  589. except (KeyboardInterrupt) as e:
  590. self.__stop_test(out, process)
  591. out.write(header("Cleaning up..."))
  592. out.flush()
  593. self.__finish()
  594. sys.exit(1)
  595. out.close()
  596. return exit_with_code(0)
  597. ############################################################
  598. # End __run_tests
  599. ############################################################
  600. ############################################################
  601. # __stop_test(benchmarker)
  602. # Stops all running tests
  603. ############################################################
  604. def __stop_test(self, out, process):
  605. if process is not None and process.poll() is None:
  606. # Stop
  607. pids = self.__find_child_processes(process.pid)
  608. if pids is not None:
  609. stop = ['kill', '-STOP'] + pids
  610. subprocess.call(stop, stderr=out, stdout=out)
  611. pids = self.__find_child_processes(process.pid)
  612. if pids is not None:
  613. term = ['kill', '-TERM'] + pids
  614. subprocess.call(term, stderr=out, stdout=out)
  615. # Okay, if there are any more PIDs, kill them harder
  616. pids = self.__find_child_processes(process.pid)
  617. if pids is not None:
  618. kill = ['kill', '-KILL'] + pids
  619. subprocess.call(kill, stderr=out, stdout=out)
  620. process.terminate()
  621. ############################################################
  622. # End __stop_test
  623. ############################################################
  624. ############################################################
  625. # __find_child_processes
  626. # Recursively finds all child processes for the given PID.
  627. ############################################################
  628. def __find_child_processes(self, pid):
  629. toRet = []
  630. try:
  631. pids = subprocess.check_output(['pgrep','-P',str(pid)]).split()
  632. toRet.extend(pids)
  633. for aPid in pids:
  634. toRet.extend(self.__find_child_processes(aPid))
  635. except:
  636. # pgrep will return a non-zero status code if there are no
  637. # processes who have a PPID of PID.
  638. pass
  639. return toRet
  640. ############################################################
  641. # End __find_child_processes
  642. ############################################################
  643. def is_port_bound(self, port):
  644. return self.__is_port_bound(port)
  645. ############################################################
  646. # __is_port_bound
  647. # Check if the requested port is available. If it
  648. # isn't available, then a previous test probably didn't
  649. # shutdown properly.
  650. ############################################################
  651. def __is_port_bound(self, port):
  652. port = int(port)
  653. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  654. try:
  655. # Try to bind to all IP addresses, this port
  656. s.bind(("", port))
  657. # If we get here, we were able to bind successfully,
  658. # which means the port is free.
  659. except socket.error:
  660. # If we get an exception, it might be because the port is still bound
  661. # which would be bad, or maybe it is a privileged port (<1024) and we
  662. # are not running as root, or maybe the server is gone, but sockets are
  663. # still in TIME_WAIT (SO_REUSEADDR). To determine which scenario, try to
  664. # connect.
  665. try:
  666. s.connect(("127.0.0.1", port))
  667. # If we get here, we were able to connect to something, which means
  668. # that the port is still bound.
  669. return True
  670. except socket.error:
  671. # An exception means that we couldn't connect, so a server probably
  672. # isn't still running on the port.
  673. pass
  674. finally:
  675. s.close()
  676. return False
  677. ############################################################
  678. # End __is_port_bound
  679. ############################################################
  680. ############################################################
  681. # __parse_results
  682. # Ensures that the system has all necessary software to run
  683. # the tests. This does not include that software for the individual
  684. # test, but covers software such as curl and weighttp that
  685. # are needed.
  686. ############################################################
  687. def __parse_results(self, tests):
  688. # Run the method to get the commmit count of each framework.
  689. self.__count_commits()
  690. # Call the method which counts the sloc for each framework
  691. self.__count_sloc()
  692. # Time to create parsed files
  693. # Aggregate JSON file
  694. with open(os.path.join(self.full_results_directory(), "results.json"), "w") as f:
  695. f.write(json.dumps(self.results, indent=2))
  696. ############################################################
  697. # End __parse_results
  698. ############################################################
  699. #############################################################
  700. # __count_sloc
  701. #############################################################
  702. def __count_sloc(self):
  703. frameworks = gather_frameworks(include=self.test,
  704. exclude=self.exclude, benchmarker=self)
  705. jsonResult = {}
  706. for framework, testlist in frameworks.iteritems():
  707. if not os.path.exists(os.path.join(testlist[0].directory, "source_code")):
  708. logging.warn("Cannot count lines of code for %s - no 'source_code' file", framework)
  709. continue
  710. # Unfortunately the source_code files use lines like
  711. # ./cpoll_cppsp/www/fortune_old instead of
  712. # ./www/fortune_old
  713. # so we have to back our working dir up one level
  714. wd = os.path.dirname(testlist[0].directory)
  715. try:
  716. command = "cloc --list-file=%s/source_code --yaml" % testlist[0].directory
  717. if os.path.exists(os.path.join(testlist[0].directory, "cloc_defs.txt")):
  718. command += " --read-lang-def %s" % os.path.join(testlist[0].directory, "cloc_defs.txt")
  719. logging.info("Using custom cloc definitions for %s", framework)
  720. # Find the last instance of the word 'code' in the yaml output. This should
  721. # be the line count for the sum of all listed files or just the line count
  722. # for the last file in the case where there's only one file listed.
  723. command = command + "| grep code | tail -1 | cut -d: -f 2"
  724. logging.debug("Running \"%s\" (cwd=%s)", command, wd)
  725. lineCount = subprocess.check_output(command, cwd=wd, shell=True)
  726. jsonResult[framework] = int(lineCount)
  727. except subprocess.CalledProcessError:
  728. continue
  729. except ValueError as ve:
  730. logging.warn("Unable to get linecount for %s due to error '%s'", framework, ve)
  731. self.results['rawData']['slocCounts'] = jsonResult
  732. ############################################################
  733. # End __count_sloc
  734. ############################################################
  735. ############################################################
  736. # __count_commits
  737. #
  738. ############################################################
  739. def __count_commits(self):
  740. frameworks = gather_frameworks(include=self.test,
  741. exclude=self.exclude, benchmarker=self)
  742. def count_commit(directory, jsonResult):
  743. command = "git rev-list HEAD -- " + directory + " | sort -u | wc -l"
  744. try:
  745. commitCount = subprocess.check_output(command, shell=True)
  746. jsonResult[framework] = int(commitCount)
  747. except subprocess.CalledProcessError:
  748. pass
  749. # Because git can be slow when run in large batches, this
  750. # calls git up to 4 times in parallel. Normal improvement is ~3-4x
  751. # in my trials, or ~100 seconds down to ~25
  752. # This is safe to parallelize as long as each thread only
  753. # accesses one key in the dictionary
  754. threads = []
  755. jsonResult = {}
  756. t1 = datetime.now()
  757. for framework, testlist in frameworks.iteritems():
  758. directory = testlist[0].directory
  759. t = threading.Thread(target=count_commit, args=(directory,jsonResult))
  760. t.start()
  761. threads.append(t)
  762. # Git has internal locks, full parallel will just cause contention
  763. # and slowness, so we rate-limit a bit
  764. if len(threads) >= 4:
  765. threads[0].join()
  766. threads.remove(threads[0])
  767. # Wait for remaining threads
  768. for t in threads:
  769. t.join()
  770. t2 = datetime.now()
  771. # print "Took %s seconds " % (t2 - t1).seconds
  772. self.results['rawData']['commitCounts'] = jsonResult
  773. self.commits = jsonResult
  774. ############################################################
  775. # End __count_commits
  776. ############################################################
  777. ############################################################
  778. # __write_intermediate_results
  779. ############################################################
  780. def __write_intermediate_results(self,test_name,status_message):
  781. try:
  782. self.results["completed"][test_name] = status_message
  783. with open(os.path.join(self.full_results_directory(), 'results.json'), 'w') as f:
  784. f.write(json.dumps(self.results, indent=2))
  785. except (IOError):
  786. logging.error("Error writing results.json")
  787. ############################################################
  788. # End __write_intermediate_results
  789. ############################################################
  790. def __load_results(self):
  791. try:
  792. with open(os.path.join(self.full_results_directory(), 'results.json')) as f:
  793. self.results = json.load(f)
  794. except (ValueError, IOError):
  795. pass
  796. ############################################################
  797. # __finish
  798. ############################################################
  799. def __finish(self):
  800. if not self.list_tests and not self.list_test_metadata and not self.parse:
  801. tests = self.__gather_tests
  802. # Normally you don't have to use Fore.BLUE before each line, but
  803. # Travis-CI seems to reset color codes on newline (see travis-ci/travis-ci#2692)
  804. # or stream flush, so we have to ensure that the color code is printed repeatedly
  805. prefix = Fore.CYAN
  806. for line in header("Verification Summary", top='=', bottom='').split('\n'):
  807. print prefix + line
  808. for test in tests:
  809. print prefix + "| Test: %s" % test.name
  810. if test.name in self.results['verify'].keys():
  811. for test_type, result in self.results['verify'][test.name].iteritems():
  812. if result.upper() == "PASS":
  813. color = Fore.GREEN
  814. elif result.upper() == "WARN":
  815. color = Fore.YELLOW
  816. else:
  817. color = Fore.RED
  818. print prefix + "| " + test_type.ljust(11) + ' : ' + color + result.upper()
  819. else:
  820. print prefix + "| " + Fore.RED + "NO RESULTS (Did framework launch?)"
  821. print prefix + header('', top='', bottom='=') + Style.RESET_ALL
  822. print "Time to complete: " + str(int(time.time() - self.start_time)) + " seconds"
  823. print "Results are saved in " + os.path.join(self.result_directory, self.timestamp)
  824. ############################################################
  825. # End __finish
  826. ############################################################
  827. ##########################################################################################
  828. # Constructor
  829. ##########################################################################################
  830. ############################################################
  831. # Initialize the benchmarker. The args are the arguments
  832. # parsed via argparser.
  833. ############################################################
  834. def __init__(self, args):
  835. # Map type strings to their objects
  836. types = dict()
  837. types['json'] = JsonTestType()
  838. types['db'] = DBTestType()
  839. types['query'] = QueryTestType()
  840. types['fortune'] = FortuneTestType()
  841. types['update'] = UpdateTestType()
  842. types['plaintext'] = PlaintextTestType()
  843. # Turn type into a map instead of a string
  844. if args['type'] == 'all':
  845. args['types'] = types
  846. else:
  847. args['types'] = { args['type'] : types[args['type']] }
  848. del args['type']
  849. args['max_threads'] = args['threads']
  850. args['max_concurrency'] = max(args['concurrency_levels'])
  851. self.__dict__.update(args)
  852. # pprint(self.__dict__)
  853. self.start_time = time.time()
  854. self.run_test_timeout_seconds = 7200
  855. # setup logging
  856. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  857. # setup some additional variables
  858. if self.database_user == None: self.database_user = self.client_user
  859. if self.database_host == None: self.database_host = self.client_host
  860. if self.database_identity_file == None: self.database_identity_file = self.client_identity_file
  861. # Remember root directory
  862. self.fwroot = setup_util.get_fwroot()
  863. # setup current_benchmark.txt location
  864. self.current_benchmark = "/tmp/current_benchmark.txt"
  865. # setup results and latest_results directories
  866. self.result_directory = os.path.join(self.fwroot, "results")
  867. self.logs_directory = os.path.join(self.fwroot, "logs")
  868. if (args['clean'] or args['clean_all']) and os.path.exists(os.path.join(self.fwroot, "results")):
  869. shutil.rmtree(os.path.join(self.fwroot, "results"))
  870. # remove installs directories if --clean-all provided
  871. self.install_root = "%s/%s" % (self.fwroot, "installs")
  872. if args['clean_all']:
  873. os.system("sudo rm -rf " + self.install_root)
  874. os.mkdir(self.install_root)
  875. if hasattr(self, 'parse') and self.parse != None:
  876. self.timestamp = self.parse
  877. else:
  878. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  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. ############################################################