framework_test.py 39 KB

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