benchmarker.py 41 KB

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