benchmarker.py 40 KB

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