framework_test.py 47 KB

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