benchmarker.py 41 KB

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