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