framework_test.py 45 KB

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