framework_test.py 43 KB

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