framework_test.py 44 KB

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