framework_test.py 43 KB

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