framework_test.py 44 KB

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