framework_test.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. from benchmark.fortune_html_parser import FortuneHTMLParser
  2. from setup.linux import setup_util
  3. from benchmark.test_types import *
  4. import importlib
  5. import os
  6. import subprocess
  7. import time
  8. import re
  9. from pprint import pprint
  10. import sys
  11. import traceback
  12. import json
  13. import logging
  14. import csv
  15. import shlex
  16. import math
  17. from collections import OrderedDict
  18. from threading import Thread
  19. from threading import Event
  20. from utils import header
  21. class FrameworkTest:
  22. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  23. # Used for test types that require no pipelining or query string params.
  24. concurrency_template = """
  25. echo ""
  26. echo "---------------------------------------------------------"
  27. echo " Running Primer {name}"
  28. echo " {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}\""
  29. echo "---------------------------------------------------------"
  30. echo ""
  31. {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}"
  32. sleep 5
  33. echo ""
  34. echo "---------------------------------------------------------"
  35. echo " Running Warmup {name}"
  36. echo " {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  37. echo "---------------------------------------------------------"
  38. echo ""
  39. {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  40. sleep 5
  41. echo ""
  42. echo "---------------------------------------------------------"
  43. echo " Synchronizing time"
  44. echo "---------------------------------------------------------"
  45. echo ""
  46. ntpdate -s pool.ntp.org
  47. for c in {levels}
  48. do
  49. echo ""
  50. echo "---------------------------------------------------------"
  51. echo " Concurrency: $c for {name}"
  52. echo " {wrk} {headers} -d {duration} -c $c --timeout $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  53. echo "---------------------------------------------------------"
  54. echo ""
  55. STARTTIME=$(date +"%s")
  56. {wrk} {headers} -d {duration} -c $c --timeout $c -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  57. echo "STARTTIME $STARTTIME"
  58. echo "ENDTIME $(date +"%s")"
  59. sleep 2
  60. done
  61. """
  62. # Used for test types that require pipelining.
  63. pipeline_template = """
  64. echo ""
  65. echo "---------------------------------------------------------"
  66. echo " Running Primer {name}"
  67. echo " {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}\""
  68. echo "---------------------------------------------------------"
  69. echo ""
  70. {wrk} {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}"
  71. sleep 5
  72. echo ""
  73. echo "---------------------------------------------------------"
  74. echo " Running Warmup {name}"
  75. echo " {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  76. echo "---------------------------------------------------------"
  77. echo ""
  78. {wrk} {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  79. sleep 5
  80. echo ""
  81. echo "---------------------------------------------------------"
  82. echo " Synchronizing time"
  83. echo "---------------------------------------------------------"
  84. echo ""
  85. ntpdate -s pool.ntp.org
  86. for c in {levels}
  87. do
  88. echo ""
  89. echo "---------------------------------------------------------"
  90. echo " Concurrency: $c for {name}"
  91. echo " {wrk} {headers} -d {duration} -c $c --timeout $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\" -s ~/pipeline.lua -- {pipeline}"
  92. echo "---------------------------------------------------------"
  93. echo ""
  94. STARTTIME=$(date +"%s")
  95. {wrk} {headers} -d {duration} -c $c --timeout $c -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url} -s ~/pipeline.lua -- {pipeline}
  96. echo "STARTTIME $STARTTIME"
  97. echo "ENDTIME $(date +"%s")"
  98. sleep 2
  99. done
  100. """
  101. # Used for test types that require a database -
  102. # These tests run at a static concurrency level and vary the size of
  103. # the query sent with each request
  104. query_template = """
  105. echo ""
  106. echo "---------------------------------------------------------"
  107. echo " Running Primer {name}"
  108. echo " wrk {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}2\""
  109. echo "---------------------------------------------------------"
  110. echo ""
  111. wrk {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}2"
  112. sleep 5
  113. echo ""
  114. echo "---------------------------------------------------------"
  115. echo " Running Warmup {name}"
  116. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  117. echo "---------------------------------------------------------"
  118. echo ""
  119. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  120. sleep 5
  121. echo ""
  122. echo "---------------------------------------------------------"
  123. echo " Synchronizing time"
  124. echo "---------------------------------------------------------"
  125. echo ""
  126. ntpdate -s pool.ntp.org
  127. for c in {levels}
  128. do
  129. echo ""
  130. echo "---------------------------------------------------------"
  131. echo " Queries: $c for {name}"
  132. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  133. echo "---------------------------------------------------------"
  134. echo ""
  135. STARTTIME=$(date +"%s")
  136. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  137. echo "STARTTIME $STARTTIME"
  138. echo "ENDTIME $(date +"%s")"
  139. sleep 2
  140. done
  141. """
  142. ############################################################
  143. # start(benchmarker)
  144. # Start the test using it's setup file
  145. ############################################################
  146. def start(self, out, err):
  147. # Load profile for this installation
  148. profile="$FWROOT/config/benchmark_profile"
  149. # Setup variables for TROOT and IROOT
  150. setup_util.replace_environ(config=profile,
  151. command='export TROOT=%s && export IROOT=%s && export DBHOST=%s && export MAX_THREADS=%s && export OUT=%s && export ERR=%s' %
  152. (self.directory, self.install_root, self.database_host, self.benchmarker.threads, os.path.join(self.fwroot, out.name), os.path.join(self.fwroot, err.name)))
  153. # Run the module start (inside parent of TROOT)
  154. # - we use the parent as a historical accident - a lot of tests
  155. # use subprocess's cwd argument already
  156. previousDir = os.getcwd()
  157. os.chdir(os.path.dirname(self.troot))
  158. logging.info("Running setup module start (cwd=%s)", self.directory)
  159. # Run the start script for the test as the "testrunner" user.
  160. # This requires superuser privs, so `sudo` is necessary.
  161. # -u [username] The username
  162. # -E Preserves the current environment variables
  163. # -H Forces the home var (~) to be reset to the user specified
  164. # -e Force bash to exit on first error
  165. # Note: check_call is a blocking call, so any startup scripts
  166. # run by the framework that need to continue (read: server has
  167. # started and needs to remain that way), then they should be
  168. # executed in the background.
  169. command = 'sudo -u %s -E -H bash -e %s.sh' % (self.benchmarker.runner_user, self.setup_file)
  170. debug_command = '''\
  171. export FWROOT=%s && \\
  172. export TROOT=%s && \\
  173. export IROOT=%s && \\
  174. export DBHOST=%s && \\
  175. export MAX_THREADS=%s && \\
  176. export OUT=%s && \\
  177. export ERR=%s && \\
  178. cd %s && \\
  179. %s''' % (self.fwroot,
  180. self.directory,
  181. self.install_root,
  182. self.database_host,
  183. self.benchmarker.threads,
  184. os.path.join(self.fwroot, out.name),
  185. os.path.join(self.fwroot, err.name),
  186. self.directory,
  187. command)
  188. logging.info("To run framework manually, copy/paste this:\n%s", debug_command)
  189. '''
  190. # Write the stderr to our temp.txt file to be read and fed back
  191. # to the user via logging later.
  192. with open('temp', 'w') as errout:
  193. try:
  194. subprocess.check_call(command, cwd=self.directory,
  195. shell=True, stderr=errout, stdout=out)
  196. retcode = 0
  197. except Exception:
  198. logging.exception("Failure running setup.sh")
  199. retcode = 1
  200. with open('temp', 'r') as errout:
  201. # Read out temp error output in its entirety
  202. body = errout.read()
  203. if len(body) > 0:
  204. # Log it to the user.
  205. logging.error(body)
  206. # Log it to our err.txt file
  207. err.write(body)
  208. # We are done with our temp file - delete it
  209. os.remove('temp')
  210. '''
  211. # Run setup.sh
  212. # Printing output until subprocess terminates
  213. class RunSetup(Thread):
  214. def __init__(self, command, directory, deadProcessFlag, name):
  215. Thread.__init__(self)
  216. self.command = command
  217. self.directory = directory
  218. self.deadProcessFlag = deadProcessFlag
  219. self.prefix = "Setup %s:" % name
  220. def run(self):
  221. # Run in backgroud, using line buffered output
  222. # Thanks: http://www.saltycrane.com/blog/2009/10/how-capture-stdout-in-real-time-python/
  223. p = subprocess.Popen(self.command, cwd=self.directory,
  224. shell=True, stdout=subprocess.PIPE, bufsize=1,
  225. stderr=subprocess.STDOUT)
  226. # Flush output until process dies
  227. # Output is sent to current terminal (via logging)
  228. # Output is sent to file
  229. while p.returncode is None:
  230. line = p.stdout.readline()
  231. if not line:
  232. time.sleep(0.5)
  233. continue
  234. # Log to current terminal
  235. # Needs to be one atomic write, so we join because
  236. # list operations are faster than string concat
  237. sys.stdout.write("".join([self.prefix, line]))
  238. sys.stdout.flush()
  239. # logging.error(body)
  240. # Log it to file
  241. out.write(line)
  242. # Process has died (may have left children, but setup.sh has
  243. # exited), so signal that it's safe to return from start
  244. deadProcessFlag.set()
  245. deadProcessFlag = Event()
  246. setup_thread = RunSetup(command, self.directory, deadProcessFlag, self.name)
  247. setup_thread.start()
  248. # We can return once the port is bound or the process is dead
  249. while not (self.benchmarker.is_port_bound(self.port) or deadProcessFlag.wait(5)):
  250. sys.stderr.write("Waiting for start to return...\n")
  251. logging.info("Executed %s.sh", self.setup_file)
  252. retcode = 0
  253. os.chdir(previousDir)
  254. return retcode
  255. ############################################################
  256. # End start
  257. ############################################################
  258. ############################################################
  259. # verify_urls
  260. # Verifys each of the URLs for this test. THis will sinply
  261. # curl the URL and check for it's return status.
  262. # For each url, a flag will be set on this object for whether
  263. # or not it passed
  264. # Returns True if all verifications succeeded
  265. ############################################################
  266. def verify_urls(self, out, err):
  267. result = True
  268. def verify_type(test_type):
  269. test = self.runTests[test_type]
  270. test.setup_out_err(out, err)
  271. out.write(header("VERIFYING %s" % test_type.upper()))
  272. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  273. try:
  274. results = test.verify(base_url)
  275. except Exception as e:
  276. results = [('fail',"""Caused Exception in TFB
  277. This almost certainly means your return value is incorrect,
  278. but also that you have found a bug. Please submit an issue
  279. including this message: %s\n%s""" % (e, traceback.format_exc()),
  280. base_url)]
  281. logging.warning("Verifying test %s for %s caused an exception: %s", test_type, self.name, e)
  282. traceback.format_exc()
  283. test.failed = any(result is 'fail' for (result, reason, url) in results)
  284. test.warned = any(result is 'warn' for (result, reason, url) in results)
  285. test.passed = all(result is 'pass' for (result, reason, url) in results)
  286. def output_result(result, reason, url):
  287. out.write(" %s for %s\n" % (result.upper(), url))
  288. print " %s for %s" % (result.upper(), url)
  289. if reason is not None and len(reason) != 0:
  290. for line in reason.splitlines():
  291. out.write(" " + line + '\n')
  292. print " " + line
  293. [output_result(r1,r2,url) for (r1, r2, url) in results]
  294. if test.failed:
  295. self.benchmarker.report_verify_results(self, test_type, 'fail')
  296. elif test.warned:
  297. self.benchmarker.report_verify_results(self, test_type, 'warn')
  298. elif test.passed:
  299. self.benchmarker.report_verify_results(self, test_type, 'pass')
  300. else:
  301. raise Exception("Unknown error - test did not pass,warn,or fail")
  302. result = True
  303. for test_type in self.runTests:
  304. verify_type(test_type)
  305. if self.runTests[test_type].failed:
  306. result = False
  307. return result
  308. ############################################################
  309. # End verify_urls
  310. ############################################################
  311. ############################################################
  312. # benchmark
  313. # Runs the benchmark for each type of test that it implements
  314. # JSON/DB/Query.
  315. ############################################################
  316. def benchmark(self, out, err):
  317. def benchmark_type(test_type):
  318. out.write("BENCHMARKING %s ... " % test_type.upper())
  319. test = self.runTests[test_type]
  320. test.setup_out_err(out, err)
  321. output_file = self.benchmarker.output_file(self.name, test_type)
  322. if not os.path.exists(output_file):
  323. # Open to create the empty file
  324. with open(output_file, 'w'):
  325. pass
  326. if not test.failed:
  327. if test_type == 'plaintext': # One special case
  328. remote_script = self.__generate_pipeline_script(test.get_url(), self.port, test.accept_header)
  329. elif test_type == 'query' or test_type == 'update':
  330. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  331. else:
  332. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  333. # Begin resource usage metrics collection
  334. self.__begin_logging(test_type)
  335. # Run the benchmark
  336. with open(output_file, 'w') as raw_file:
  337. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  338. p.communicate(remote_script)
  339. err.flush()
  340. # End resource usage metrics collection
  341. self.__end_logging()
  342. results = self.__parse_test(test_type)
  343. print "Benchmark results:"
  344. pprint(results)
  345. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  346. out.write( "Complete\n" )
  347. out.flush()
  348. for test_type in self.runTests:
  349. benchmark_type(test_type)
  350. ############################################################
  351. # End benchmark
  352. ############################################################
  353. ############################################################
  354. # parse_all
  355. # Method meant to be run for a given timestamp
  356. ############################################################
  357. def parse_all(self):
  358. for test_type in self.runTests:
  359. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  360. results = self.__parse_test(test_type)
  361. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  362. ############################################################
  363. # __parse_test(test_type)
  364. ############################################################
  365. def __parse_test(self, test_type):
  366. try:
  367. results = dict()
  368. results['results'] = []
  369. stats = []
  370. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  371. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  372. is_warmup = True
  373. rawData = None
  374. for line in raw_data:
  375. if "Queries:" in line or "Concurrency:" in line:
  376. is_warmup = False
  377. rawData = None
  378. continue
  379. if "Warmup" in line or "Primer" in line:
  380. is_warmup = True
  381. continue
  382. if not is_warmup:
  383. if rawData == None:
  384. rawData = dict()
  385. results['results'].append(rawData)
  386. #if "Requests/sec:" in line:
  387. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  388. # rawData['reportedResults'] = m.group(1)
  389. # search for weighttp data such as succeeded and failed.
  390. if "Latency" in line:
  391. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  392. if len(m) == 4:
  393. rawData['latencyAvg'] = m[0]
  394. rawData['latencyStdev'] = m[1]
  395. rawData['latencyMax'] = m[2]
  396. # rawData['latencyStdevPercent'] = m[3]
  397. #if "Req/Sec" in line:
  398. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  399. # if len(m) == 4:
  400. # rawData['requestsAvg'] = m[0]
  401. # rawData['requestsStdev'] = m[1]
  402. # rawData['requestsMax'] = m[2]
  403. # rawData['requestsStdevPercent'] = m[3]
  404. #if "requests in" in line:
  405. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  406. # if m != None:
  407. # # parse out the raw time, which may be in minutes or seconds
  408. # raw_time = m.group(1)
  409. # if "ms" in raw_time:
  410. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  411. # elif "s" in raw_time:
  412. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  413. # elif "m" in raw_time:
  414. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  415. # elif "h" in raw_time:
  416. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  417. if "requests in" in line:
  418. m = re.search("([0-9]+) requests in", line)
  419. if m != None:
  420. rawData['totalRequests'] = int(m.group(1))
  421. if "Socket errors" in line:
  422. if "connect" in line:
  423. m = re.search("connect ([0-9]+)", line)
  424. rawData['connect'] = int(m.group(1))
  425. if "read" in line:
  426. m = re.search("read ([0-9]+)", line)
  427. rawData['read'] = int(m.group(1))
  428. if "write" in line:
  429. m = re.search("write ([0-9]+)", line)
  430. rawData['write'] = int(m.group(1))
  431. if "timeout" in line:
  432. m = re.search("timeout ([0-9]+)", line)
  433. rawData['timeout'] = int(m.group(1))
  434. if "Non-2xx" in line:
  435. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  436. if m != None:
  437. rawData['5xx'] = int(m.group(1))
  438. if "STARTTIME" in line:
  439. m = re.search("[0-9]+", line)
  440. rawData["startTime"] = int(m.group(0))
  441. if "ENDTIME" in line:
  442. m = re.search("[0-9]+", line)
  443. rawData["endTime"] = int(m.group(0))
  444. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  445. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  446. stats.append(test_stats)
  447. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  448. json.dump(stats, stats_file, indent=2)
  449. return results
  450. except IOError:
  451. return None
  452. ############################################################
  453. # End benchmark
  454. ############################################################
  455. ##########################################################################################
  456. # Private Methods
  457. ##########################################################################################
  458. ############################################################
  459. # __generate_concurrency_script(url, port)
  460. # Generates the string containing the bash script that will
  461. # be run on the client to benchmark a single test. This
  462. # specifically works for the variable concurrency tests (JSON
  463. # and DB)
  464. ############################################################
  465. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk"):
  466. headers = self.headers_template.format(accept=accept_header)
  467. return self.concurrency_template.format(max_concurrency=max(self.benchmarker.concurrency_levels),
  468. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  469. levels=" ".join("{}".format(item) for item in self.benchmarker.concurrency_levels),
  470. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command)
  471. ############################################################
  472. # __generate_pipeline_script(url, port)
  473. # Generates the string containing the bash script that will
  474. # be run on the client to benchmark a single pipeline test.
  475. ############################################################
  476. def __generate_pipeline_script(self, url, port, accept_header, wrk_command="wrk"):
  477. headers = self.headers_template.format(accept=accept_header)
  478. return self.pipeline_template.format(max_concurrency=16384,
  479. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  480. levels=" ".join("{}".format(item) for item in [256,1024,4096,16384]),
  481. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  482. pipeline=16)
  483. ############################################################
  484. # __generate_query_script(url, port)
  485. # Generates the string containing the bash script that will
  486. # be run on the client to benchmark a single test. This
  487. # specifically works for the variable query tests (Query)
  488. ############################################################
  489. def __generate_query_script(self, url, port, accept_header):
  490. headers = self.headers_template.format(accept=accept_header)
  491. return self.query_template.format(max_concurrency=max(self.benchmarker.concurrency_levels),
  492. max_threads=self.benchmarker.threads, name=self.name, duration=self.benchmarker.duration,
  493. levels=" ".join("{}".format(item) for item in self.benchmarker.query_levels),
  494. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  495. ############################################################
  496. # Returns True if any test type this this framework test will use a DB
  497. ############################################################
  498. def requires_database(self):
  499. '''Returns True/False if this test requires a database'''
  500. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  501. ############################################################
  502. # __begin_logging
  503. # Starts a thread to monitor the resource usage, to be synced with the client's time
  504. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  505. ############################################################
  506. def __begin_logging(self, test_type):
  507. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_type))
  508. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  509. --raw --socket --tcp --udp --unix --vm --disk-util \
  510. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  511. cmd = shlex.split(dstat_string)
  512. dev_null = open(os.devnull, "w")
  513. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  514. ##############################################################
  515. # Begin __end_logging
  516. # Stops the logger thread and blocks until shutdown is complete.
  517. ##############################################################
  518. def __end_logging(self):
  519. self.subprocess_handle.terminate()
  520. self.subprocess_handle.communicate()
  521. ##############################################################
  522. # Begin __parse_stats
  523. # For each test type, process all the statistics, and return a multi-layered dictionary
  524. # that has a structure as follows:
  525. # (timestamp)
  526. # | (main header) - group that the stat is in
  527. # | | (sub header) - title of the stat
  528. # | | | (stat) - the stat itself, usually a floating point number
  529. ##############################################################
  530. def __parse_stats(self, test_type, start_time, end_time, interval):
  531. stats_dict = dict()
  532. stats_file = self.benchmarker.stats_file(self.name, test_type)
  533. with open(stats_file) as stats:
  534. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  535. pass
  536. stats_reader = csv.reader(stats)
  537. main_header = stats_reader.next()
  538. sub_header = stats_reader.next()
  539. time_row = sub_header.index("epoch")
  540. int_counter = 0
  541. for row in stats_reader:
  542. time = float(row[time_row])
  543. int_counter+=1
  544. if time < start_time:
  545. continue
  546. elif time > end_time:
  547. return stats_dict
  548. if int_counter % interval != 0:
  549. continue
  550. row_dict = dict()
  551. for nextheader in main_header:
  552. if nextheader != "":
  553. row_dict[nextheader] = dict()
  554. header = ""
  555. for item_num, column in enumerate(row):
  556. if(len(main_header[item_num]) != 0):
  557. header = main_header[item_num]
  558. 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
  559. stats_dict[time] = row_dict
  560. return stats_dict
  561. ##############################################################
  562. # End __parse_stats
  563. ##############################################################
  564. def __getattr__(self, name):
  565. """For backwards compatibility, we used to pass benchmarker
  566. as the argument to the setup.sh files"""
  567. try:
  568. x = getattr(self.benchmarker, name)
  569. except AttributeError:
  570. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  571. print "This is probably a bug"
  572. raise
  573. return x
  574. ##############################################################
  575. # Begin __calculate_average_stats
  576. # We have a large amount of raw data for the statistics that
  577. # may be useful for the stats nerds, but most people care about
  578. # a couple of numbers. For now, we're only going to supply:
  579. # * Average CPU
  580. # * Average Memory
  581. # * Total network use
  582. # * Total disk use
  583. # More may be added in the future. If they are, please update
  584. # the above list.
  585. # Note: raw_stats is directly from the __parse_stats method.
  586. # Recall that this consists of a dictionary of timestamps,
  587. # each of which contain a dictionary of stat categories which
  588. # contain a dictionary of stats
  589. ##############################################################
  590. def __calculate_average_stats(self, raw_stats):
  591. raw_stat_collection = dict()
  592. for timestamp, time_dict in raw_stats.items():
  593. for main_header, sub_headers in time_dict.items():
  594. item_to_append = None
  595. if 'cpu' in main_header:
  596. # We want to take the idl stat and subtract it from 100
  597. # to get the time that the CPU is NOT idle.
  598. item_to_append = sub_headers['idl'] - 100.0
  599. elif main_header == 'memory usage':
  600. item_to_append = sub_headers['used']
  601. elif 'net' in main_header:
  602. # Network stats have two parts - recieve and send. We'll use a tuple of
  603. # style (recieve, send)
  604. item_to_append = (sub_headers['recv'], sub_headers['send'])
  605. elif 'dsk' or 'io' in main_header:
  606. # Similar for network, except our tuple looks like (read, write)
  607. item_to_append = (sub_headers['read'], sub_headers['writ'])
  608. if item_to_append is not None:
  609. if main_header not in raw_stat_collection:
  610. raw_stat_collection[main_header] = list()
  611. raw_stat_collection[main_header].append(item_to_append)
  612. # Simple function to determine human readable size
  613. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  614. def sizeof_fmt(num):
  615. # We'll assume that any number we get is convertable to a float, just in case
  616. num = float(num)
  617. for x in ['bytes','KB','MB','GB']:
  618. if num < 1024.0 and num > -1024.0:
  619. return "%3.1f%s" % (num, x)
  620. num /= 1024.0
  621. return "%3.1f%s" % (num, 'TB')
  622. # Now we have our raw stats in a readable format - we need to format it for display
  623. # We need a floating point sum, so the built in sum doesn't cut it
  624. display_stat_collection = dict()
  625. for header, values in raw_stat_collection.items():
  626. display_stat = None
  627. if 'cpu' in header:
  628. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  629. elif main_header == 'memory usage':
  630. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  631. elif 'net' in main_header:
  632. receive, send = zip(*values) # unzip
  633. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  634. else: # if 'dsk' or 'io' in header:
  635. read, write = zip(*values) # unzip
  636. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  637. display_stat_collection[header] = display_stat
  638. return display_stat
  639. ###########################################################################################
  640. # End __calculate_average_stats
  641. #########################################################################################
  642. ##########################################################################################
  643. # Constructor
  644. ##########################################################################################
  645. def __init__(self, name, directory, benchmarker, runTests, args):
  646. self.name = name
  647. self.directory = directory
  648. self.benchmarker = benchmarker
  649. self.runTests = runTests
  650. self.fwroot = benchmarker.fwroot
  651. self.approach = ""
  652. self.classification = ""
  653. self.database = ""
  654. self.framework = ""
  655. self.language = ""
  656. self.orm = ""
  657. self.platform = ""
  658. self.webserver = ""
  659. self.os = ""
  660. self.database_os = ""
  661. self.display_name = ""
  662. self.notes = ""
  663. self.versus = ""
  664. # setup logging
  665. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  666. self.install_root="%s/%s" % (self.fwroot, "installs")
  667. if benchmarker.install_strategy is 'pertest':
  668. self.install_root="%s/pertest/%s" % (self.install_root, name)
  669. # Used in setup.sh scripts for consistency with
  670. # the bash environment variables
  671. self.troot = self.directory
  672. self.iroot = self.install_root
  673. self.__dict__.update(args)
  674. ############################################################
  675. # End __init__
  676. ############################################################
  677. ############################################################
  678. # End FrameworkTest
  679. ############################################################
  680. ##########################################################################################
  681. # Static methods
  682. ##########################################################################################
  683. ##############################################################
  684. # parse_config(config, directory, benchmarker)
  685. # parses a config file and returns a list of FrameworkTest
  686. # objects based on that config file.
  687. ##############################################################
  688. def parse_config(config, directory, benchmarker):
  689. tests = []
  690. # This sort ordering is set up specifically to return the length
  691. # of the test name. There were SO many problems involved with
  692. # 'plaintext' being run first (rather, just not last) that we
  693. # needed to ensure that it was run last for every framework.
  694. def testOrder(type_name):
  695. return len(type_name)
  696. # The config object can specify multiple tests
  697. # Loop over them and parse each into a FrameworkTest
  698. for test in config['tests']:
  699. names = [name for (name,keys) in test.iteritems()]
  700. if "default" not in names:
  701. logging.warn("Framework %s does not define a default test in benchmark_config", config['framework'])
  702. for test_name, test_keys in test.iteritems():
  703. # Prefix all test names with framework except 'default' test
  704. if test_name == 'default':
  705. test_name = config['framework']
  706. else:
  707. test_name = "%s-%s" % (config['framework'], test_name)
  708. # Ensure FrameworkTest.framework is available
  709. if not test_keys['framework']:
  710. test_keys['framework'] = config['framework']
  711. #if test_keys['framework'].lower() != config['framework'].lower():
  712. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  713. # (test_name, test_keys['framework'], config['framework']))
  714. # Confirm required keys are present
  715. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  716. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  717. if not all (key in test_keys for key in required):
  718. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  719. # Map test type to a parsed FrameworkTestType object
  720. runTests = dict()
  721. for type_name, type_obj in benchmarker.types.iteritems():
  722. try:
  723. runTests[type_name] = type_obj.copy().parse(test_keys)
  724. except AttributeError as ae:
  725. # This is quite common - most tests don't support all types
  726. # Quitely log it and move on (debug logging is on in travis and this causes
  727. # ~1500 lines of debug, so I'm totally ignoring it for now
  728. # logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  729. pass
  730. # We need to sort by test_type to run
  731. sortedTestKeys = sorted(runTests.keys(), key=testOrder)
  732. sortedRunTests = OrderedDict()
  733. for sortedTestKey in sortedTestKeys:
  734. sortedRunTests[sortedTestKey] = runTests[sortedTestKey]
  735. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  736. tests.append(FrameworkTest(test_name, directory, benchmarker, sortedRunTests, test_keys))
  737. return tests
  738. ##############################################################
  739. # End parse_config
  740. ##############################################################