benchmarker.py 46 KB

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