framework_test.py 43 KB

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