benchmarker.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. from setup.linux.installer import Installer
  2. from setup.linux import setup_util
  3. from benchmark import framework_test
  4. from benchmark.test_types import *
  5. from utils import header
  6. from utils import gather_tests
  7. from utils import gather_frameworks
  8. from utils import verify_database_connections
  9. import os
  10. import shutil
  11. import stat
  12. import json
  13. import subprocess
  14. import traceback
  15. import time
  16. import pprint
  17. import csv
  18. import sys
  19. import logging
  20. import socket
  21. import threading
  22. import textwrap
  23. from pprint import pprint
  24. from multiprocessing import Process
  25. from datetime import datetime
  26. # Cross-platform colored text
  27. from colorama import Fore, Back, Style
  28. # Text-based progress indicators
  29. import progressbar
  30. class Benchmarker:
  31. ##########################################################################################
  32. # Public methods
  33. ##########################################################################################
  34. ############################################################
  35. # Prints all the available tests
  36. ############################################################
  37. def run_list_tests(self):
  38. all_tests = self.__gather_tests
  39. for test in all_tests:
  40. print test.name
  41. self.__finish()
  42. ############################################################
  43. # End run_list_tests
  44. ############################################################
  45. ############################################################
  46. # Prints the metadata for all the available tests
  47. ############################################################
  48. def run_list_test_metadata(self, run_finish=True):
  49. all_tests = self.__gather_tests
  50. all_tests_json = json.dumps(map(lambda test: {
  51. "name": test.name,
  52. "approach": test.approach,
  53. "classification": test.classification,
  54. "database": test.database,
  55. "framework": test.framework,
  56. "language": test.language,
  57. "orm": test.orm,
  58. "platform": test.platform,
  59. "webserver": test.webserver,
  60. "os": test.os,
  61. "database_os": test.database_os,
  62. "display_name": test.display_name,
  63. "notes": test.notes,
  64. "versus": test.versus
  65. }, all_tests))
  66. with open(os.path.join(self.full_results_directory(), "test_metadata.json"), "w") as f:
  67. f.write(all_tests_json)
  68. if run_finish:
  69. self.__finish()
  70. ############################################################
  71. # End run_list_test_metadata
  72. ############################################################
  73. ############################################################
  74. # parse_timestamp
  75. # Re-parses the raw data for a given timestamp
  76. ############################################################
  77. def parse_timestamp(self):
  78. all_tests = self.__gather_tests
  79. for test in all_tests:
  80. test.parse_all()
  81. self.__parse_results(all_tests)
  82. self.__finish()
  83. ############################################################
  84. # End parse_timestamp
  85. ############################################################
  86. ############################################################
  87. # Run the tests:
  88. # This process involves setting up the client/server machines
  89. # with any necessary change. Then going through each test,
  90. # running their setup script, verifying the URLs, and
  91. # running benchmarks against them.
  92. ############################################################
  93. def run(self):
  94. ##########################
  95. # Generate metadata
  96. ##########################
  97. self.run_list_test_metadata(False)
  98. ##########################
  99. # Get a list of all known
  100. # tests that we can run.
  101. ##########################
  102. all_tests = self.__gather_tests
  103. ##########################
  104. # Setup client/server
  105. ##########################
  106. print header("Preparing Server, Database, and Client ...", top='=', bottom='=')
  107. self.__setup_server()
  108. self.__setup_database()
  109. self.__setup_client()
  110. ## Check if wrk (and wrk-pipeline) is installed and executable, if not, raise an exception
  111. #if not (os.access("/usr/local/bin/wrk", os.X_OK) and os.access("/usr/local/bin/wrk-pipeline", os.X_OK)):
  112. # raise Exception("wrk and/or wrk-pipeline are not properly installed. Not running tests.")
  113. ##########################
  114. # Run tests
  115. ##########################
  116. print header("Running Tests...", top='=', bottom='=')
  117. result = self.__run_tests(all_tests)
  118. ##########################
  119. # Parse results
  120. ##########################
  121. if self.mode == "benchmark":
  122. print header("Parsing Results ...", top='=', bottom='=')
  123. self.__parse_results(all_tests)
  124. self.__finish()
  125. return result
  126. ############################################################
  127. # End run
  128. ############################################################
  129. ############################################################
  130. # database_sftp_string(batch_file)
  131. # generates a fully qualified URL for sftp to database
  132. ############################################################
  133. def database_sftp_string(self, batch_file):
  134. sftp_string = "sftp -oStrictHostKeyChecking=no "
  135. if batch_file != None: sftp_string += " -b " + batch_file + " "
  136. if self.database_identity_file != None:
  137. sftp_string += " -i " + self.database_identity_file + " "
  138. return sftp_string + self.database_user + "@" + self.database_host
  139. ############################################################
  140. # End database_sftp_string
  141. ############################################################
  142. ############################################################
  143. # client_sftp_string(batch_file)
  144. # generates a fully qualified URL for sftp to client
  145. ############################################################
  146. def client_sftp_string(self, batch_file):
  147. sftp_string = "sftp -oStrictHostKeyChecking=no "
  148. if batch_file != None: sftp_string += " -b " + batch_file + " "
  149. if self.client_identity_file != None:
  150. sftp_string += " -i " + self.client_identity_file + " "
  151. return sftp_string + self.client_user + "@" + self.client_host
  152. ############################################################
  153. # End client_sftp_string
  154. ############################################################
  155. ############################################################
  156. # generate_url(url, port)
  157. # generates a fully qualified URL for accessing a test url
  158. ############################################################
  159. def generate_url(self, url, port):
  160. return self.server_host + ":" + str(port) + url
  161. ############################################################
  162. # End generate_url
  163. ############################################################
  164. ############################################################
  165. # get_output_file(test_name, test_type)
  166. # returns the output file name for this test_name and
  167. # test_type timestamp/test_type/test_name/raw
  168. ############################################################
  169. def get_output_file(self, test_name, test_type):
  170. return os.path.join(self.result_directory, self.timestamp, self.logs_directory, test_name, test_type, "raw")
  171. ############################################################
  172. # End get_output_file
  173. ############################################################
  174. ############################################################
  175. # output_file(test_name, test_type)
  176. # returns the output file for this test_name and test_type
  177. # timestamp/test_type/test_name/raw
  178. ############################################################
  179. def output_file(self, test_name, test_type):
  180. path = self.get_output_file(test_name, test_type)
  181. try:
  182. os.makedirs(os.path.dirname(path))
  183. except OSError:
  184. pass
  185. return path
  186. ############################################################
  187. # End output_file
  188. ############################################################
  189. ############################################################
  190. # get_stats_file(test_name, test_type)
  191. # returns the stats file name for this test_name and
  192. # test_type timestamp/test_type/test_name/raw
  193. ############################################################
  194. def get_stats_file(self, test_name, test_type):
  195. return os.path.join(self.result_directory, self.timestamp, self.logs_directory, test_name, test_type, "stats")
  196. ############################################################
  197. # End get_stats_file
  198. ############################################################
  199. ############################################################
  200. # stats_file(test_name, test_type)
  201. # returns the stats file for this test_name and test_type
  202. # timestamp/test_type/test_name/raw
  203. ############################################################
  204. def stats_file(self, test_name, test_type):
  205. path = self.get_stats_file(test_name, test_type)
  206. try:
  207. os.makedirs(os.path.dirname(path))
  208. except OSError:
  209. pass
  210. return path
  211. ############################################################
  212. # End stats_file
  213. ############################################################
  214. ############################################################
  215. # full_results_directory
  216. ############################################################
  217. def full_results_directory(self):
  218. path = os.path.join(self.result_directory, self.timestamp)
  219. try:
  220. os.makedirs(path)
  221. except OSError:
  222. pass
  223. return path
  224. ############################################################
  225. # End full_results_directory
  226. ############################################################
  227. ############################################################
  228. # report_verify_results
  229. # Used by FrameworkTest to add verification details to our results
  230. #
  231. # TODO: Technically this is an IPC violation - we are accessing
  232. # the parent process' memory from the child process
  233. ############################################################
  234. def report_verify_results(self, framework, test, result):
  235. if framework.name not in self.results['verify'].keys():
  236. self.results['verify'][framework.name] = dict()
  237. self.results['verify'][framework.name][test] = result
  238. ############################################################
  239. # report_benchmark_results
  240. # Used by FrameworkTest to add benchmark data to this
  241. #
  242. # TODO: Technically this is an IPC violation - we are accessing
  243. # the parent process' memory from the child process
  244. ############################################################
  245. def report_benchmark_results(self, framework, test, results):
  246. if test not in self.results['rawData'].keys():
  247. self.results['rawData'][test] = dict()
  248. # If results has a size from the parse, then it succeeded.
  249. if results:
  250. self.results['rawData'][test][framework.name] = results
  251. # This may already be set for single-tests
  252. if framework.name not in self.results['succeeded'][test]:
  253. self.results['succeeded'][test].append(framework.name)
  254. else:
  255. # This may already be set for single-tests
  256. if framework.name not in self.results['failed'][test]:
  257. self.results['failed'][test].append(framework.name)
  258. ############################################################
  259. # End report_results
  260. ############################################################
  261. ##########################################################################################
  262. # Private methods
  263. ##########################################################################################
  264. ############################################################
  265. # Gathers all the tests
  266. ############################################################
  267. @property
  268. def __gather_tests(self):
  269. tests = gather_tests(include=self.test,
  270. exclude=self.exclude,
  271. benchmarker=self)
  272. # If the tests have been interrupted somehow, then we want to resume them where we left
  273. # off, rather than starting from the beginning
  274. if os.path.isfile('current_benchmark.txt'):
  275. with open('current_benchmark.txt', 'r') as interrupted_benchmark:
  276. interrupt_bench = interrupted_benchmark.read().strip()
  277. for index, atest in enumerate(tests):
  278. if atest.name == interrupt_bench:
  279. tests = tests[index:]
  280. break
  281. return tests
  282. ############################################################
  283. # End __gather_tests
  284. ############################################################
  285. ############################################################
  286. # Makes any necessary changes to the server that should be
  287. # made before running the tests. This involves setting kernal
  288. # settings to allow for more connections, or more file
  289. # descriptiors
  290. #
  291. # http://redmine.lighttpd.net/projects/weighttp/wiki#Troubleshooting
  292. ############################################################
  293. def __setup_server(self):
  294. try:
  295. if os.name == 'nt':
  296. return True
  297. #subprocess.check_call(["sudo","bash","-c","cd /sys/devices/system/cpu; ls -d cpu[0-9]*|while read x; do echo performance > $x/cpufreq/scaling_governor; done"])
  298. subprocess.check_call("sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535".rsplit(" "))
  299. subprocess.check_call("sudo sysctl -w net.core.somaxconn=65535".rsplit(" "))
  300. subprocess.check_call("sudo -s ulimit -n 65535".rsplit(" "))
  301. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_reuse=1".rsplit(" "))
  302. subprocess.check_call("sudo sysctl net.ipv4.tcp_tw_recycle=1".rsplit(" "))
  303. subprocess.check_call("sudo sysctl -w kernel.shmmax=134217728".rsplit(" "))
  304. subprocess.check_call("sudo sysctl -w kernel.shmall=2097152".rsplit(" "))
  305. except subprocess.CalledProcessError:
  306. return False
  307. ############################################################
  308. # End __setup_server
  309. ############################################################
  310. ############################################################
  311. # Clean up any processes that run with root privileges
  312. ############################################################
  313. def __cleanup_leftover_processes_before_test(self):
  314. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  315. p.communicate("""
  316. sudo /etc/init.d/apache2 stop
  317. """)
  318. ############################################################
  319. # Makes any necessary changes to the database machine that
  320. # should be made before running the tests. Is very similar
  321. # to the server setup, but may also include database specific
  322. # changes.
  323. ############################################################
  324. def __setup_database(self):
  325. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, shell=True)
  326. p.communicate("""
  327. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  328. sudo sysctl -w net.core.somaxconn=65535
  329. sudo sysctl -w kernel.sched_autogroup_enabled=0
  330. sudo -s ulimit -n 65535
  331. sudo sysctl net.ipv4.tcp_tw_reuse=1
  332. sudo sysctl net.ipv4.tcp_tw_recycle=1
  333. sudo sysctl -w kernel.shmmax=2147483648
  334. sudo sysctl -w kernel.shmall=2097152
  335. sudo sysctl -w kernel.sem="250 32000 256 512"
  336. """)
  337. # TODO - print kernel configuration to file
  338. # echo "Printing kernel configuration:" && sudo sysctl -a
  339. # Explanations:
  340. # net.ipv4.tcp_max_syn_backlog, net.core.somaxconn, kernel.sched_autogroup_enabled: http://tweaked.io/guide/kernel/
  341. # ulimit -n: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/
  342. # net.ipv4.tcp_tw_*: http://www.linuxbrigade.com/reduce-time_wait-socket-connections/
  343. # kernel.shm*: http://seriousbirder.com/blogs/linux-understanding-shmmax-and-shmall-settings/
  344. # For kernel.sem: https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/Tuning_and_Optimizing_Red_Hat_Enterprise_Linux_for_Oracle_9i_and_10g_Databases/chap-Oracle_9i_and_10g_Tuning_Guide-Setting_Semaphores.html
  345. ############################################################
  346. # End __setup_database
  347. ############################################################
  348. ############################################################
  349. # Makes any necessary changes to the client machine that
  350. # should be made before running the tests. Is very similar
  351. # to the server setup, but may also include client specific
  352. # changes.
  353. ############################################################
  354. def __setup_client(self):
  355. p = subprocess.Popen(self.client_ssh_string, stdin=subprocess.PIPE, shell=True)
  356. p.communicate("""
  357. sudo sysctl -w net.ipv4.tcp_max_syn_backlog=65535
  358. sudo sysctl -w net.core.somaxconn=65535
  359. sudo -s ulimit -n 65535
  360. sudo sysctl net.ipv4.tcp_tw_reuse=1
  361. sudo sysctl net.ipv4.tcp_tw_recycle=1
  362. sudo sysctl -w kernel.shmmax=2147483648
  363. sudo sysctl -w kernel.shmall=2097152
  364. """)
  365. ############################################################
  366. # End __setup_client
  367. ############################################################
  368. ############################################################
  369. # __run_tests
  370. #
  371. # 2013-10-02 ASB Calls each test passed in tests to
  372. # __run_test in a separate process. Each
  373. # test is given a set amount of time and if
  374. # kills the child process (and subsequently
  375. # all of its child processes). Uses
  376. # multiprocessing module.
  377. ############################################################
  378. def __run_tests(self, tests):
  379. if len(tests) == 0:
  380. return 0
  381. logging.debug("Start __run_tests.")
  382. logging.debug("__name__ = %s",__name__)
  383. error_happened = False
  384. if self.os.lower() == 'windows':
  385. logging.debug("Executing __run_tests on Windows")
  386. for test in tests:
  387. with open('current_benchmark.txt', 'w') as benchmark_resume_file:
  388. benchmark_resume_file.write(test.name)
  389. if self.__run_test(test) != 0:
  390. error_happened = True
  391. else:
  392. logging.debug("Executing __run_tests on Linux")
  393. # Setup a nice progressbar and ETA indicator
  394. widgets = [self.mode, ': ', progressbar.Percentage(),
  395. ' ', progressbar.Bar(),
  396. ' Rough ', progressbar.ETA()]
  397. pbar = progressbar.ProgressBar(widgets=widgets, maxval=len(tests)).start()
  398. pbar_test = 0
  399. # These features do not work on Windows
  400. for test in tests:
  401. pbar.update(pbar_test)
  402. pbar_test = pbar_test + 1
  403. if __name__ == 'benchmark.benchmarker':
  404. print header("Running Test: %s" % test.name)
  405. with open('current_benchmark.txt', 'w') as benchmark_resume_file:
  406. benchmark_resume_file.write(test.name)
  407. test_process = Process(target=self.__run_test, name="Test Runner (%s)" % test.name, args=(test,))
  408. test_process.start()
  409. test_process.join(self.run_test_timeout_seconds)
  410. self.__load_results() # Load intermediate result from child process
  411. if(test_process.is_alive()):
  412. logging.debug("Child process for {name} is still alive. Terminating.".format(name=test.name))
  413. self.__write_intermediate_results(test.name,"__run_test timeout (="+ str(self.run_test_timeout_seconds) + " seconds)")
  414. test_process.terminate()
  415. test_process.join()
  416. if test_process.exitcode != 0:
  417. error_happened = True
  418. pbar.finish()
  419. if os.path.isfile('current_benchmark.txt'):
  420. os.remove('current_benchmark.txt')
  421. logging.debug("End __run_tests.")
  422. if error_happened:
  423. return 1
  424. return 0
  425. ############################################################
  426. # End __run_tests
  427. ############################################################
  428. ############################################################
  429. # __run_test
  430. # 2013-10-02 ASB Previously __run_tests. This code now only
  431. # processes a single test.
  432. #
  433. # Ensures that the system has all necessary software to run
  434. # the tests. This does not include that software for the individual
  435. # test, but covers software such as curl and weighttp that
  436. # are needed.
  437. ############################################################
  438. def __run_test(self, test):
  439. # Used to capture return values
  440. def exit_with_code(code):
  441. if self.os.lower() == 'windows':
  442. return code
  443. else:
  444. sys.exit(code)
  445. logDir = os.path.join(self.full_results_directory(), self.logs_directory, test.name.lower())
  446. try:
  447. os.makedirs(logDir)
  448. except Exception:
  449. pass
  450. with open(os.path.join(logDir, 'out.txt'), 'w') as out:
  451. if test.os.lower() != self.os.lower() or test.database_os.lower() != self.database_os.lower():
  452. out.write("OS or Database OS specified in benchmark_config.json does not match the current environment. Skipping.\n")
  453. return exit_with_code(0)
  454. # If the test is in the excludes list, we skip it
  455. if self.exclude != None and test.name in self.exclude:
  456. out.write("Test {name} has been added to the excludes list. Skipping.\n".format(name=test.name))
  457. return exit_with_code(0)
  458. out.write("test.os.lower() = {os} test.database_os.lower() = {dbos}\n".format(os=test.os.lower(),dbos=test.database_os.lower()))
  459. out.write("self.results['frameworks'] != None: {val}\n".format(val=str(self.results['frameworks'] != None)))
  460. out.write("test.name: {name}\n".format(name=str(test.name)))
  461. out.write("self.results['completed']: {completed}\n".format(completed=str(self.results['completed'])))
  462. if self.results['frameworks'] != None and test.name in self.results['completed']:
  463. out.write('Framework {name} found in latest saved data. Skipping.\n'.format(name=str(test.name)))
  464. print 'WARNING: Test {test} exists in the results directory; this must be removed before running a new test.\n'.format(test=str(test.name))
  465. return exit_with_code(1)
  466. out.flush()
  467. out.write(header("Beginning %s" % test.name, top='='))
  468. out.flush()
  469. ##########################
  470. # Start this test
  471. ##########################
  472. out.write(header("Starting %s" % test.name))
  473. out.flush()
  474. try:
  475. if test.requires_database():
  476. p = subprocess.Popen(self.database_ssh_string, stdin=subprocess.PIPE, stdout=out, stderr=out, shell=True)
  477. p.communicate("""
  478. sudo restart mysql
  479. sudo restart mongod
  480. sudo service 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 results and latest_results directories
  865. self.result_directory = os.path.join("results")
  866. self.logs_directory = os.path.join("logs")
  867. if (args['clean'] or args['clean_all']) and os.path.exists(os.path.join(self.fwroot, "results")):
  868. shutil.rmtree(os.path.join(self.fwroot, "results"))
  869. # remove installs directories if --clean-all provided
  870. self.install_root = "%s/%s" % (self.fwroot, "installs")
  871. if args['clean_all']:
  872. os.system("sudo rm -rf " + self.install_root)
  873. os.mkdir(self.install_root)
  874. if hasattr(self, 'parse') and self.parse != None:
  875. self.timestamp = self.parse
  876. else:
  877. self.timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
  878. self.results = None
  879. try:
  880. with open(os.path.join(self.full_results_directory(), 'results.json'), 'r') as f:
  881. #Load json file into results object
  882. self.results = json.load(f)
  883. except IOError:
  884. logging.warn("results.json for test not found.")
  885. if self.results == None:
  886. self.results = dict()
  887. self.results['concurrencyLevels'] = self.concurrency_levels
  888. self.results['queryIntervals'] = self.query_levels
  889. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  890. self.results['duration'] = self.duration
  891. self.results['rawData'] = dict()
  892. self.results['rawData']['json'] = dict()
  893. self.results['rawData']['db'] = dict()
  894. self.results['rawData']['query'] = dict()
  895. self.results['rawData']['fortune'] = dict()
  896. self.results['rawData']['update'] = dict()
  897. self.results['rawData']['plaintext'] = dict()
  898. self.results['completed'] = dict()
  899. self.results['succeeded'] = dict()
  900. self.results['succeeded']['json'] = []
  901. self.results['succeeded']['db'] = []
  902. self.results['succeeded']['query'] = []
  903. self.results['succeeded']['fortune'] = []
  904. self.results['succeeded']['update'] = []
  905. self.results['succeeded']['plaintext'] = []
  906. self.results['failed'] = dict()
  907. self.results['failed']['json'] = []
  908. self.results['failed']['db'] = []
  909. self.results['failed']['query'] = []
  910. self.results['failed']['fortune'] = []
  911. self.results['failed']['update'] = []
  912. self.results['failed']['plaintext'] = []
  913. self.results['verify'] = dict()
  914. else:
  915. #for x in self.__gather_tests():
  916. # if x.name not in self.results['frameworks']:
  917. # self.results['frameworks'] = self.results['frameworks'] + [x.name]
  918. # Always overwrite framework list
  919. self.results['frameworks'] = [t.name for t in self.__gather_tests]
  920. # Setup the ssh command string
  921. self.database_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.database_user + "@" + self.database_host
  922. self.client_ssh_string = "ssh -T -o StrictHostKeyChecking=no " + self.client_user + "@" + self.client_host
  923. if self.database_identity_file != None:
  924. self.database_ssh_string = self.database_ssh_string + " -i " + self.database_identity_file
  925. if self.client_identity_file != None:
  926. self.client_ssh_string = self.client_ssh_string + " -i " + self.client_identity_file
  927. if self.install is not None:
  928. install = Installer(self, self.install_strategy)
  929. install.install_software()
  930. ############################################################
  931. # End __init__
  932. ############################################################