framework_test.py 35 KB

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