framework_test.py 39 KB

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