framework_test.py 44 KB

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