benchmarker.py 42 KB

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