framework_test.py 43 KB

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