benchmarker.py 39 KB

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