framework_test.py 44 KB

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