framework_test.py 44 KB

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