framework_test.py 43 KB

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