framework_test.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. from benchmark.fortune_html_parser import FortuneHTMLParser
  2. from setup.linux import setup_util
  3. from benchmark.test_types import *
  4. import importlib
  5. import os
  6. import subprocess
  7. import time
  8. import re
  9. from pprint import pprint
  10. import sys
  11. import traceback
  12. import json
  13. import logging
  14. import csv
  15. import shlex
  16. import math
  17. from collections import OrderedDict
  18. from threading import Thread
  19. from threading import Event
  20. from utils import header
  21. # Cross-platform colored text
  22. from colorama import Fore, Back, Style
  23. from datetime import datetime
  24. from datetime import timedelta
  25. class FrameworkTest:
  26. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  27. # Used for test types that require no pipelining or query string params.
  28. concurrency_template = """
  29. echo ""
  30. echo "---------------------------------------------------------"
  31. echo " Running Primer {name}"
  32. echo " {wrk} {headers} --latency -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}\""
  33. echo "---------------------------------------------------------"
  34. echo ""
  35. {wrk} {headers} --latency -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}"
  36. sleep 5
  37. echo ""
  38. echo "---------------------------------------------------------"
  39. echo " Running Warmup {name}"
  40. echo " {wrk} {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  41. echo "---------------------------------------------------------"
  42. echo ""
  43. {wrk} {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  44. sleep 5
  45. echo ""
  46. echo "---------------------------------------------------------"
  47. echo " Synchronizing time"
  48. echo "---------------------------------------------------------"
  49. echo ""
  50. ntpdate -s pool.ntp.org
  51. for c in {levels}
  52. do
  53. echo ""
  54. echo "---------------------------------------------------------"
  55. echo " Concurrency: $c for {name}"
  56. echo " {wrk} {headers} --latency -d {duration} -c $c --timeout $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  57. echo "---------------------------------------------------------"
  58. echo ""
  59. STARTTIME=$(date +"%s")
  60. {wrk} {headers} --latency -d {duration} -c $c --timeout $c -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  61. echo "STARTTIME $STARTTIME"
  62. echo "ENDTIME $(date +"%s")"
  63. sleep 2
  64. done
  65. """
  66. # Used for test types that require pipelining.
  67. pipeline_template = """
  68. echo ""
  69. echo "---------------------------------------------------------"
  70. echo " Running Primer {name}"
  71. echo " {wrk} {headers} --latency -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}\""
  72. echo "---------------------------------------------------------"
  73. echo ""
  74. {wrk} {headers} --latency -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}"
  75. sleep 5
  76. echo ""
  77. echo "---------------------------------------------------------"
  78. echo " Running Warmup {name}"
  79. echo " {wrk} {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  80. echo "---------------------------------------------------------"
  81. echo ""
  82. {wrk} {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  83. sleep 5
  84. echo ""
  85. echo "---------------------------------------------------------"
  86. echo " Synchronizing time"
  87. echo "---------------------------------------------------------"
  88. echo ""
  89. ntpdate -s pool.ntp.org
  90. for c in {levels}
  91. do
  92. echo ""
  93. echo "---------------------------------------------------------"
  94. echo " Concurrency: $c for {name}"
  95. echo " {wrk} {headers} --latency -d {duration} -c $c --timeout $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\" -s ~/pipeline.lua -- {pipeline}"
  96. echo "---------------------------------------------------------"
  97. echo ""
  98. STARTTIME=$(date +"%s")
  99. {wrk} {headers} --latency -d {duration} -c $c --timeout $c -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url} -s ~/pipeline.lua -- {pipeline}
  100. echo "STARTTIME $STARTTIME"
  101. echo "ENDTIME $(date +"%s")"
  102. sleep 2
  103. done
  104. """
  105. # Used for test types that require a database -
  106. # These tests run at a static concurrency level and vary the size of
  107. # the query sent with each request
  108. query_template = """
  109. echo ""
  110. echo "---------------------------------------------------------"
  111. echo " Running Primer {name}"
  112. echo " wrk {headers} --latency -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}2\""
  113. echo "---------------------------------------------------------"
  114. echo ""
  115. wrk {headers} --latency -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}2"
  116. sleep 5
  117. echo ""
  118. echo "---------------------------------------------------------"
  119. echo " Running Warmup {name}"
  120. echo " wrk {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  121. echo "---------------------------------------------------------"
  122. echo ""
  123. wrk {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  124. sleep 5
  125. echo ""
  126. echo "---------------------------------------------------------"
  127. echo " Synchronizing time"
  128. echo "---------------------------------------------------------"
  129. echo ""
  130. ntpdate -s pool.ntp.org
  131. for c in {levels}
  132. do
  133. echo ""
  134. echo "---------------------------------------------------------"
  135. echo " Queries: $c for {name}"
  136. echo " wrk {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  137. echo "---------------------------------------------------------"
  138. echo ""
  139. STARTTIME=$(date +"%s")
  140. wrk {headers} --latency -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  141. echo "STARTTIME $STARTTIME"
  142. echo "ENDTIME $(date +"%s")"
  143. sleep 2
  144. done
  145. """
  146. ############################################################
  147. # start(benchmarker)
  148. # Start the test using it's setup file
  149. ############################################################
  150. def start(self, out, err):
  151. # Setup environment variables
  152. logDir = os.path.join(self.fwroot, self.benchmarker.latest_results_directory, 'logs', self.name.lower())
  153. bash_functions_path= os.path.join(self.fwroot, 'toolset/setup/linux/bash_functions.sh')
  154. setup_util.replace_environ(config='$FWROOT/config/benchmark_profile',
  155. command='''\
  156. export TROOT=%s && \
  157. export IROOT=%s && \
  158. export DBHOST=%s && \
  159. export LOGDIR=%s && \
  160. export MAX_THREADS=%s \
  161. ''' % (
  162. self.directory,
  163. self.install_root,
  164. self.database_host,
  165. logDir,
  166. self.benchmarker.threads))
  167. # Always ensure that IROOT belongs to the runner_user
  168. chown = "sudo chown -R %s:%s %s" % (self.benchmarker.runner_user,
  169. self.benchmarker.runner_user, os.path.join(self.fwroot, self.install_root))
  170. subprocess.check_call(chown, shell=True, cwd=cwd, executable='/bin/bash')
  171. # Run the module start inside parent of TROOT
  172. # - we use the parent as a historical accident, a number of tests
  173. # refer to their TROOT maually still
  174. previousDir = os.getcwd()
  175. os.chdir(os.path.dirname(self.troot))
  176. logging.info("Running setup module start (cwd=%s)", self.directory)
  177. # Run the start script for the test as the "testrunner" user
  178. #
  179. # `sudo` - Switching user requires superuser privs
  180. # -u [username] The username
  181. # -E Preserves the current environment variables
  182. # -H Forces the home var (~) to be reset to the user specified
  183. # `stdbuf` - Disable buffering, send output to python ASAP
  184. # -o0 zero-sized buffer for stdout
  185. # -e0 zero-sized buffer for stderr
  186. # `bash` - Run the setup.sh script using bash
  187. # -e Force bash to exit on first error
  188. # -x Turn on bash tracing e.g. print commands before running
  189. #
  190. # Most servers do not output to stdout/stderr while serving
  191. # requests so there is no performance hit from disabling
  192. # output buffering. This disabling is necessary to
  193. # a) allow TFB to show output in real time and b) avoid loosing
  194. # output in the buffer when the testrunner processes are forcibly
  195. # killed
  196. #
  197. # See http://www.pixelbeat.org/programming/stdio_buffering/
  198. # See https://blogs.gnome.org/markmc/2013/06/04/async-io-and-python/
  199. # See http://eyalarubas.com/python-subproc-nonblock.html
  200. command = 'sudo -u %s -E -H stdbuf -o0 -e0 bash -exc "source %s && source %s.sh"' % (
  201. self.benchmarker.runner_user,
  202. bash_functions_path,
  203. os.path.join(self.troot, self.setup_file))
  204. debug_command = '''\
  205. export FWROOT=%s && \\
  206. export TROOT=%s && \\
  207. export IROOT=%s && \\
  208. export DBHOST=%s && \\
  209. export LOGDIR=%s && \\
  210. export MAX_THREADS=%s && \\
  211. cd %s && \\
  212. %s''' % (self.fwroot,
  213. self.directory,
  214. self.install_root,
  215. self.database_host,
  216. logDir,
  217. self.benchmarker.threads,
  218. self.directory,
  219. command)
  220. logging.info("To run %s manually, copy/paste this:\n%s", self.name, debug_command)
  221. def tee_output(prefix, line):
  222. # Needs to be one atomic write
  223. # Explicitly use UTF-8 as it's the most common framework output
  224. # TODO improve encoding handling
  225. line = prefix.encode('utf-8') + line
  226. # Log to current terminal
  227. sys.stdout.write(line)
  228. sys.stdout.flush()
  229. # logging.error("".join([prefix, line]))
  230. out.write(line)
  231. out.flush()
  232. # Start the setup.sh command
  233. p = subprocess.Popen(command, cwd=self.directory,
  234. shell=True, stdout=subprocess.PIPE,
  235. stderr=subprocess.STDOUT)
  236. nbsr = setup_util.NonBlockingStreamReader(p.stdout,
  237. "%s: %s.sh and framework processes have terminated" % (self.name, self.setup_file))
  238. # Set a limit on total execution time of setup.sh
  239. timeout = datetime.now() + timedelta(minutes = 30)
  240. time_remaining = timeout - datetime.now()
  241. # Need to print to stdout once every 10 minutes or Travis-CI will abort
  242. travis_timeout = datetime.now() + timedelta(minutes = 5)
  243. # Flush output until setup.sh work is finished. This is
  244. # either a) when setup.sh exits b) when the port is bound
  245. # c) when we run out of time. Note that 'finished' doesn't
  246. # guarantee setup.sh process is dead - the OS may choose to make
  247. # setup.sh a zombie process if it still has living children
  248. #
  249. # Note: child processes forked (using &) will remain alive
  250. # after setup.sh has exited. The will have inherited the
  251. # stdout/stderr descriptors and will be directing their
  252. # output to the pipes.
  253. #
  254. prefix = "Setup %s: " % self.name
  255. while not (p.poll()
  256. or self.benchmarker.is_port_bound(self.port)
  257. or time_remaining.total_seconds() < 0):
  258. # The conditions above are slow to check, so
  259. # we will delay output substantially if we only
  260. # print one line per condition check.
  261. # Adding a tight loop here mitigates the effect,
  262. # ensuring that most of the output directly from
  263. # setup.sh is sent to tee_output before the outer
  264. # loop exits and prints things like "setup.sh exited"
  265. #
  266. for i in xrange(10):
  267. try:
  268. line = nbsr.readline(0.05)
  269. if line:
  270. tee_output(prefix, line)
  271. # Reset Travis-CI timer
  272. travis_timeout = datetime.now() + timedelta(minutes = 5)
  273. except setup_util.EndOfStream:
  274. tee_output(prefix, "Setup has terminated\n")
  275. break
  276. time_remaining = timeout - datetime.now()
  277. if (travis_timeout - datetime.now()).total_seconds() < 0:
  278. sys.stdout.write(prefix + 'Printing so Travis-CI does not time out\n')
  279. sys.stdout.flush()
  280. travis_timeout = datetime.now() + timedelta(minutes = 5)
  281. # Did we time out?
  282. if time_remaining.total_seconds() < 0:
  283. tee_output(prefix, "%s.sh timed out!! Aborting...\n" % self.setup_file)
  284. p.kill()
  285. return 1
  286. # What's our return code?
  287. # If setup.sh has terminated, use that code
  288. # Otherwise, detect if the port was bound
  289. retcode = (p.poll() or 0 if self.benchmarker.is_port_bound(self.port) else 1)
  290. if p.poll():
  291. tee_output(prefix, "%s.sh process exited naturally with %s\n" % (self.setup_file, p.poll()))
  292. elif self.benchmarker.is_port_bound(self.port):
  293. tee_output(prefix, "Bound port detected on %s\n" % self.port)
  294. # Before we return control to the benchmarker, spin up a
  295. # thread to keep an eye on the pipes in case the running
  296. # framework uses stdout/stderr. Once all processes accessing
  297. # the subprocess.PIPEs are dead, this thread will terminate.
  298. # Use a different prefix to indicate this is the framework
  299. # speaking
  300. prefix = "Server %s: " % self.name
  301. def watch_child_pipes(nbsr, prefix):
  302. while True:
  303. try:
  304. line = nbsr.readline(60)
  305. if line:
  306. tee_output(prefix, line)
  307. except setup_util.EndOfStream:
  308. tee_output(prefix, "Framework processes have terminated\n")
  309. return
  310. watch_thread = Thread(target = watch_child_pipes,
  311. args = (nbsr, prefix))
  312. watch_thread.daemon = True
  313. watch_thread.start()
  314. logging.info("Executed %s.sh, returning %s", self.setup_file, retcode)
  315. os.chdir(previousDir)
  316. return retcode
  317. ############################################################
  318. # End start
  319. ############################################################
  320. ############################################################
  321. # verify_urls
  322. # Verifys each of the URLs for this test. THis will sinply
  323. # curl the URL and check for it's return status.
  324. # For each url, a flag will be set on this object for whether
  325. # or not it passed
  326. # Returns True if all verifications succeeded
  327. ############################################################
  328. def verify_urls(self, out, err):
  329. result = True
  330. def verify_type(test_type):
  331. test = self.runTests[test_type]
  332. test.setup_out_err(out, err)
  333. out.write(header("VERIFYING %s" % test_type.upper()))
  334. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  335. try:
  336. results = test.verify(base_url)
  337. except Exception as e:
  338. results = [('fail',"""Caused Exception in TFB
  339. This almost certainly means your return value is incorrect,
  340. but also that you have found a bug. Please submit an issue
  341. including this message: %s\n%s""" % (e, traceback.format_exc()),
  342. base_url)]
  343. logging.warning("Verifying test %s for %s caused an exception: %s", test_type, self.name, e)
  344. traceback.format_exc()
  345. test.failed = any(result is 'fail' for (result, reason, url) in results)
  346. test.warned = any(result is 'warn' for (result, reason, url) in results)
  347. test.passed = all(result is 'pass' for (result, reason, url) in results)
  348. def output_result(result, reason, url):
  349. specific_rules_url = "http://frameworkbenchmarks.readthedocs.org/en/latest/Project-Information/Framework-Tests/#specific-test-requirements"
  350. color = Fore.GREEN
  351. if result.upper() == "WARN":
  352. color = Fore.YELLOW
  353. elif result.upper() == "FAIL":
  354. color = Fore.RED
  355. out.write((" " + color + "%s" + Style.RESET_ALL + " for %s\n") % (result.upper(), url))
  356. print (" " + color + "%s" + Style.RESET_ALL + " for %s\n") % (result.upper(), url)
  357. if reason is not None and len(reason) != 0:
  358. for line in reason.splitlines():
  359. out.write(" " + line + '\n')
  360. print " " + line
  361. if not test.passed:
  362. out.write(" See %s\n" % specific_rules_url)
  363. print " See %s\n" % specific_rules_url
  364. [output_result(r1,r2,url) for (r1, r2, url) in results]
  365. if test.failed:
  366. self.benchmarker.report_verify_results(self, test_type, 'fail')
  367. elif test.warned:
  368. self.benchmarker.report_verify_results(self, test_type, 'warn')
  369. elif test.passed:
  370. self.benchmarker.report_verify_results(self, test_type, 'pass')
  371. else:
  372. raise Exception("Unknown error - test did not pass,warn,or fail")
  373. result = True
  374. for test_type in self.runTests:
  375. verify_type(test_type)
  376. if self.runTests[test_type].failed:
  377. result = False
  378. return result
  379. ############################################################
  380. # End verify_urls
  381. ############################################################
  382. ############################################################
  383. # benchmark
  384. # Runs the benchmark for each type of test that it implements
  385. # JSON/DB/Query.
  386. ############################################################
  387. def benchmark(self, out, err):
  388. def benchmark_type(test_type):
  389. out.write("BENCHMARKING %s ... " % test_type.upper())
  390. test = self.runTests[test_type]
  391. test.setup_out_err(out, err)
  392. output_file = self.benchmarker.output_file(self.name, test_type)
  393. if not os.path.exists(output_file):
  394. # Open to create the empty file
  395. with open(output_file, 'w'):
  396. pass
  397. if not test.failed:
  398. if test_type == 'plaintext': # One special case
  399. remote_script = self.__generate_pipeline_script(test.get_url(), self.port, test.accept_header)
  400. elif test_type == 'query' or test_type == 'update':
  401. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  402. else:
  403. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  404. # Begin resource usage metrics collection
  405. self.__begin_logging(test_type)
  406. # Run the benchmark
  407. with open(output_file, 'w') as raw_file:
  408. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  409. p.communicate(remote_script)
  410. err.flush()
  411. # End resource usage metrics collection
  412. self.__end_logging()
  413. results = self.__parse_test(test_type)
  414. print "Benchmark results:"
  415. pprint(results)
  416. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  417. out.write( "Complete\n" )
  418. out.flush()
  419. for test_type in self.runTests:
  420. benchmark_type(test_type)
  421. ############################################################
  422. # End benchmark
  423. ############################################################
  424. ############################################################
  425. # parse_all
  426. # Method meant to be run for a given timestamp
  427. ############################################################
  428. def parse_all(self):
  429. for test_type in self.runTests:
  430. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  431. results = self.__parse_test(test_type)
  432. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  433. ##########################################################################################
  434. # Private Methods
  435. ##########################################################################################
  436. ############################################################
  437. # __parse_test(test_type)
  438. ############################################################
  439. def __parse_test(self, test_type):
  440. try:
  441. results = dict()
  442. results['results'] = []
  443. stats = []
  444. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  445. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  446. is_warmup = True
  447. rawData = None
  448. for line in raw_data:
  449. if "Queries:" in line or "Concurrency:" in line:
  450. is_warmup = False
  451. rawData = None
  452. continue
  453. if "Warmup" in line or "Primer" in line:
  454. is_warmup = True
  455. continue
  456. if not is_warmup:
  457. if rawData == None:
  458. rawData = dict()
  459. results['results'].append(rawData)
  460. #if "Requests/sec:" in line:
  461. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  462. # rawData['reportedResults'] = m.group(1)
  463. # search for weighttp data such as succeeded and failed.
  464. if "Latency" in line:
  465. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  466. if len(m) == 4:
  467. rawData['latencyAvg'] = m[0]
  468. rawData['latencyStdev'] = m[1]
  469. rawData['latencyMax'] = m[2]
  470. # rawData['latencyStdevPercent'] = m[3]
  471. #if "Req/Sec" in line:
  472. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  473. # if len(m) == 4:
  474. # rawData['requestsAvg'] = m[0]
  475. # rawData['requestsStdev'] = m[1]
  476. # rawData['requestsMax'] = m[2]
  477. # rawData['requestsStdevPercent'] = m[3]
  478. #if "requests in" in line:
  479. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  480. # if m != None:
  481. # # parse out the raw time, which may be in minutes or seconds
  482. # raw_time = m.group(1)
  483. # if "ms" in raw_time:
  484. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  485. # elif "s" in raw_time:
  486. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  487. # elif "m" in raw_time:
  488. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  489. # elif "h" in raw_time:
  490. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  491. if "requests in" in line:
  492. m = re.search("([0-9]+) requests in", line)
  493. if m != None:
  494. rawData['totalRequests'] = int(m.group(1))
  495. if "Socket errors" in line:
  496. if "connect" in line:
  497. m = re.search("connect ([0-9]+)", line)
  498. rawData['connect'] = int(m.group(1))
  499. if "read" in line:
  500. m = re.search("read ([0-9]+)", line)
  501. rawData['read'] = int(m.group(1))
  502. if "write" in line:
  503. m = re.search("write ([0-9]+)", line)
  504. rawData['write'] = int(m.group(1))
  505. if "timeout" in line:
  506. m = re.search("timeout ([0-9]+)", line)
  507. rawData['timeout'] = int(m.group(1))
  508. if "Non-2xx" in line:
  509. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  510. if m != None:
  511. rawData['5xx'] = int(m.group(1))
  512. if "STARTTIME" in line:
  513. m = re.search("[0-9]+", line)
  514. rawData["startTime"] = int(m.group(0))
  515. if "ENDTIME" in line:
  516. m = re.search("[0-9]+", line)
  517. rawData["endTime"] = int(m.group(0))
  518. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  519. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  520. stats.append(test_stats)
  521. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  522. json.dump(stats, stats_file, indent=2)
  523. return results
  524. except IOError:
  525. return None
  526. ############################################################
  527. # End benchmark
  528. ############################################################
  529. ############################################################
  530. # __generate_concurrency_script(url, port)
  531. # Generates the string containing the bash script that will
  532. # be run on the client to benchmark a single test. This
  533. # specifically works for the variable concurrency tests (JSON
  534. # and DB)
  535. ############################################################
  536. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk"):
  537. headers = self.headers_template.format(accept=accept_header)
  538. return self.concurrency_template.format(max_concurrency=max(self.benchmarker.concurrency_levels),
  539. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  540. levels=" ".join("{}".format(item) for item in self.benchmarker.concurrency_levels),
  541. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command)
  542. ############################################################
  543. # __generate_pipeline_script(url, port)
  544. # Generates the string containing the bash script that will
  545. # be run on the client to benchmark a single pipeline test.
  546. ############################################################
  547. def __generate_pipeline_script(self, url, port, accept_header, wrk_command="wrk"):
  548. headers = self.headers_template.format(accept=accept_header)
  549. return self.pipeline_template.format(max_concurrency=16384,
  550. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  551. levels=" ".join("{}".format(item) for item in [256,1024,4096,16384]),
  552. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  553. pipeline=16)
  554. ############################################################
  555. # __generate_query_script(url, port)
  556. # Generates the string containing the bash script that will
  557. # be run on the client to benchmark a single test. This
  558. # specifically works for the variable query tests (Query)
  559. ############################################################
  560. def __generate_query_script(self, url, port, accept_header):
  561. headers = self.headers_template.format(accept=accept_header)
  562. return self.query_template.format(max_concurrency=max(self.benchmarker.concurrency_levels),
  563. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  564. levels=" ".join("{}".format(item) for item in self.benchmarker.query_levels),
  565. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  566. ############################################################
  567. # Returns True if any test type this this framework test will use a DB
  568. ############################################################
  569. def requires_database(self):
  570. '''Returns True/False if this test requires a database'''
  571. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  572. ############################################################
  573. # __begin_logging
  574. # Starts a thread to monitor the resource usage, to be synced with the client's time
  575. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  576. ############################################################
  577. def __begin_logging(self, test_type):
  578. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_type))
  579. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  580. --raw --socket --tcp --udp --unix --vm --disk-util \
  581. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  582. cmd = shlex.split(dstat_string)
  583. dev_null = open(os.devnull, "w")
  584. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  585. ##############################################################
  586. # Begin __end_logging
  587. # Stops the logger thread and blocks until shutdown is complete.
  588. ##############################################################
  589. def __end_logging(self):
  590. self.subprocess_handle.terminate()
  591. self.subprocess_handle.communicate()
  592. ##############################################################
  593. # Begin __parse_stats
  594. # For each test type, process all the statistics, and return a multi-layered dictionary
  595. # that has a structure as follows:
  596. # (timestamp)
  597. # | (main header) - group that the stat is in
  598. # | | (sub header) - title of the stat
  599. # | | | (stat) - the stat itself, usually a floating point number
  600. ##############################################################
  601. def __parse_stats(self, test_type, start_time, end_time, interval):
  602. stats_dict = dict()
  603. stats_file = self.benchmarker.stats_file(self.name, test_type)
  604. with open(stats_file) as stats:
  605. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  606. pass
  607. stats_reader = csv.reader(stats)
  608. main_header = stats_reader.next()
  609. sub_header = stats_reader.next()
  610. time_row = sub_header.index("epoch")
  611. int_counter = 0
  612. for row in stats_reader:
  613. time = float(row[time_row])
  614. int_counter+=1
  615. if time < start_time:
  616. continue
  617. elif time > end_time:
  618. return stats_dict
  619. if int_counter % interval != 0:
  620. continue
  621. row_dict = dict()
  622. for nextheader in main_header:
  623. if nextheader != "":
  624. row_dict[nextheader] = dict()
  625. header = ""
  626. for item_num, column in enumerate(row):
  627. if(len(main_header[item_num]) != 0):
  628. header = main_header[item_num]
  629. row_dict[header][sub_header[item_num]] = float(column) # all the stats are numbers, so we want to make sure that they stay that way in json
  630. stats_dict[time] = row_dict
  631. return stats_dict
  632. ##############################################################
  633. # End __parse_stats
  634. ##############################################################
  635. def __getattr__(self, name):
  636. """For backwards compatibility, we used to pass benchmarker
  637. as the argument to the setup.sh files"""
  638. try:
  639. x = getattr(self.benchmarker, name)
  640. except AttributeError:
  641. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  642. print "This is probably a bug"
  643. raise
  644. return x
  645. ##############################################################
  646. # Begin __calculate_average_stats
  647. # We have a large amount of raw data for the statistics that
  648. # may be useful for the stats nerds, but most people care about
  649. # a couple of numbers. For now, we're only going to supply:
  650. # * Average CPU
  651. # * Average Memory
  652. # * Total network use
  653. # * Total disk use
  654. # More may be added in the future. If they are, please update
  655. # the above list.
  656. # Note: raw_stats is directly from the __parse_stats method.
  657. # Recall that this consists of a dictionary of timestamps,
  658. # each of which contain a dictionary of stat categories which
  659. # contain a dictionary of stats
  660. ##############################################################
  661. def __calculate_average_stats(self, raw_stats):
  662. raw_stat_collection = dict()
  663. for timestamp, time_dict in raw_stats.items():
  664. for main_header, sub_headers in time_dict.items():
  665. item_to_append = None
  666. if 'cpu' in main_header:
  667. # We want to take the idl stat and subtract it from 100
  668. # to get the time that the CPU is NOT idle.
  669. item_to_append = sub_headers['idl'] - 100.0
  670. elif main_header == 'memory usage':
  671. item_to_append = sub_headers['used']
  672. elif 'net' in main_header:
  673. # Network stats have two parts - recieve and send. We'll use a tuple of
  674. # style (recieve, send)
  675. item_to_append = (sub_headers['recv'], sub_headers['send'])
  676. elif 'dsk' or 'io' in main_header:
  677. # Similar for network, except our tuple looks like (read, write)
  678. item_to_append = (sub_headers['read'], sub_headers['writ'])
  679. if item_to_append is not None:
  680. if main_header not in raw_stat_collection:
  681. raw_stat_collection[main_header] = list()
  682. raw_stat_collection[main_header].append(item_to_append)
  683. # Simple function to determine human readable size
  684. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  685. def sizeof_fmt(num):
  686. # We'll assume that any number we get is convertable to a float, just in case
  687. num = float(num)
  688. for x in ['bytes','KB','MB','GB']:
  689. if num < 1024.0 and num > -1024.0:
  690. return "%3.1f%s" % (num, x)
  691. num /= 1024.0
  692. return "%3.1f%s" % (num, 'TB')
  693. # Now we have our raw stats in a readable format - we need to format it for display
  694. # We need a floating point sum, so the built in sum doesn't cut it
  695. display_stat_collection = dict()
  696. for header, values in raw_stat_collection.items():
  697. display_stat = None
  698. if 'cpu' in header:
  699. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  700. elif main_header == 'memory usage':
  701. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  702. elif 'net' in main_header:
  703. receive, send = zip(*values) # unzip
  704. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  705. else: # if 'dsk' or 'io' in header:
  706. read, write = zip(*values) # unzip
  707. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  708. display_stat_collection[header] = display_stat
  709. return display_stat
  710. ###########################################################################################
  711. # End __calculate_average_stats
  712. #########################################################################################
  713. ##########################################################################################
  714. # Constructor
  715. ##########################################################################################
  716. def __init__(self, name, directory, benchmarker, runTests, args):
  717. self.name = name
  718. self.directory = directory
  719. self.benchmarker = benchmarker
  720. self.runTests = runTests
  721. self.fwroot = benchmarker.fwroot
  722. self.approach = ""
  723. self.classification = ""
  724. self.database = ""
  725. self.framework = ""
  726. self.language = ""
  727. self.orm = ""
  728. self.platform = ""
  729. self.webserver = ""
  730. self.os = ""
  731. self.database_os = ""
  732. self.display_name = ""
  733. self.notes = ""
  734. self.versus = ""
  735. # setup logging
  736. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  737. self.install_root="%s/%s" % (self.fwroot, "installs")
  738. if benchmarker.install_strategy is 'pertest':
  739. self.install_root="%s/pertest/%s" % (self.install_root, name)
  740. # Used in setup.sh scripts for consistency with
  741. # the bash environment variables
  742. self.troot = self.directory
  743. self.iroot = self.install_root
  744. self.__dict__.update(args)
  745. ############################################################
  746. # End __init__
  747. ############################################################
  748. ############################################################
  749. # End FrameworkTest
  750. ############################################################
  751. ##########################################################################################
  752. # Static methods
  753. ##########################################################################################
  754. ##############################################################
  755. # parse_config(config, directory, benchmarker)
  756. # parses a config file and returns a list of FrameworkTest
  757. # objects based on that config file.
  758. ##############################################################
  759. def parse_config(config, directory, benchmarker):
  760. tests = []
  761. # This sort ordering is set up specifically to return the length
  762. # of the test name. There were SO many problems involved with
  763. # 'plaintext' being run first (rather, just not last) that we
  764. # needed to ensure that it was run last for every framework.
  765. def testOrder(type_name):
  766. return len(type_name)
  767. # The config object can specify multiple tests
  768. # Loop over them and parse each into a FrameworkTest
  769. for test in config['tests']:
  770. names = [name for (name,keys) in test.iteritems()]
  771. if "default" not in names:
  772. logging.warn("Framework %s does not define a default test in benchmark_config.json", config['framework'])
  773. for test_name, test_keys in test.iteritems():
  774. # Prefix all test names with framework except 'default' test
  775. if test_name == 'default':
  776. test_name = config['framework']
  777. else:
  778. test_name = "%s-%s" % (config['framework'], test_name)
  779. # Ensure FrameworkTest.framework is available
  780. if not test_keys['framework']:
  781. test_keys['framework'] = config['framework']
  782. #if test_keys['framework'].lower() != config['framework'].lower():
  783. # print Exception("benchmark_config.json for test %s is invalid - test framework '%s' must match benchmark_config.json framework '%s'" %
  784. # (test_name, test_keys['framework'], config['framework']))
  785. # Confirm required keys are present
  786. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  787. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  788. if not all (key in test_keys for key in required):
  789. raise Exception("benchmark_config.json for test %s is invalid - missing required keys" % test_name)
  790. # Map test type to a parsed FrameworkTestType object
  791. runTests = dict()
  792. for type_name, type_obj in benchmarker.types.iteritems():
  793. try:
  794. runTests[type_name] = type_obj.copy().parse(test_keys)
  795. except AttributeError as ae:
  796. # This is quite common - most tests don't support all types
  797. # Quitely log it and move on (debug logging is on in travis and this causes
  798. # ~1500 lines of debug, so I'm totally ignoring it for now
  799. # logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  800. pass
  801. # We need to sort by test_type to run
  802. sortedTestKeys = sorted(runTests.keys(), key=testOrder)
  803. sortedRunTests = OrderedDict()
  804. for sortedTestKey in sortedTestKeys:
  805. sortedRunTests[sortedTestKey] = runTests[sortedTestKey]
  806. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  807. tests.append(FrameworkTest(test_name, directory, benchmarker, sortedRunTests, test_keys))
  808. return tests
  809. ##############################################################
  810. # End parse_config
  811. ##############################################################