framework_test.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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 threading import Thread
  18. from threading import Event
  19. from utils import header
  20. class FrameworkTest:
  21. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  22. # Used for test types that do not require a database -
  23. # These tests are run at multiple concurrency levels
  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 {interval}
  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}\" -s ~/pipeline.lua -- {pipeline}"
  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} -s ~/pipeline.lua -- {pipeline}
  57. echo "STARTTIME $STARTTIME"
  58. echo "ENDTIME $(date +"%s")"
  59. sleep 2
  60. done
  61. """
  62. # Used for test types that require a database -
  63. # These tests run at a static concurrency level and vary the size of
  64. # the query sent with each request
  65. query_template = """
  66. echo ""
  67. echo "---------------------------------------------------------"
  68. echo " Running Primer {name}"
  69. echo " wrk {headers} -d 5 -c 8 --timeout 8 -t 8 \"http://{server_host}:{port}{url}2\""
  70. echo "---------------------------------------------------------"
  71. echo ""
  72. wrk {headers} -d 5 -c 8 --timeout 8 -t 8 "http://{server_host}:{port}{url}2"
  73. sleep 5
  74. echo ""
  75. echo "---------------------------------------------------------"
  76. echo " Running Warmup {name}"
  77. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  78. echo "---------------------------------------------------------"
  79. echo ""
  80. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  81. sleep 5
  82. echo ""
  83. echo "---------------------------------------------------------"
  84. echo " Synchronizing time"
  85. echo "---------------------------------------------------------"
  86. echo ""
  87. ntpdate -s pool.ntp.org
  88. for c in {interval}
  89. do
  90. echo ""
  91. echo "---------------------------------------------------------"
  92. echo " Queries: $c for {name}"
  93. echo " wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  94. echo "---------------------------------------------------------"
  95. echo ""
  96. STARTTIME=$(date +"%s")
  97. wrk {headers} -d {duration} -c {max_concurrency} --timeout {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  98. echo "STARTTIME $STARTTIME"
  99. echo "ENDTIME $(date +"%s")"
  100. sleep 2
  101. done
  102. """
  103. ############################################################
  104. # start(benchmarker)
  105. # Start the test using it's setup file
  106. ############################################################
  107. def start(self, out, err):
  108. # Load profile for this installation
  109. profile="%s/bash_profile.sh" % self.directory
  110. if not os.path.exists(profile):
  111. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  112. profile="$FWROOT/config/benchmark_profile"
  113. # Setup variables for TROOT and IROOT
  114. setup_util.replace_environ(config=profile,
  115. command='export TROOT=%s && export IROOT=%s' %
  116. (self.directory, self.install_root))
  117. # Because start can take so long, we print a dot to let the user know
  118. # we are working
  119. class ProgressPrinterThread(Thread):
  120. def __init__(self, event):
  121. Thread.__init__(self)
  122. self.stopped = event
  123. def run(self):
  124. while not self.stopped.wait(20):
  125. sys.stderr.write("Waiting for start to return...\n")
  126. stopFlag = Event()
  127. thread = ProgressPrinterThread(stopFlag)
  128. thread.start()
  129. # Run the module start (inside parent of TROOT)
  130. # - we use the parent as a historical accident - a lot of tests
  131. # use subprocess's cwd argument already
  132. previousDir = os.getcwd()
  133. os.chdir(os.path.dirname(self.troot))
  134. logging.info("Running setup module start (cwd=%s)", os.path.dirname(self.troot))
  135. try:
  136. retcode = self.setup_module.start(self, out, err)
  137. if retcode == None:
  138. retcode = 0
  139. except Exception:
  140. retcode = 1
  141. st = traceback.format_exc()
  142. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  143. st = "Start exception:\n%s" % st
  144. logging.info(st)
  145. err.write(st + '\n')
  146. os.chdir(previousDir)
  147. # Stop the progress printer
  148. stopFlag.set()
  149. logging.info("Called setup.py start")
  150. return retcode
  151. ############################################################
  152. # End start
  153. ############################################################
  154. ############################################################
  155. # stop(benchmarker)
  156. # Stops the test using it's setup file
  157. ############################################################
  158. def stop(self, out, err):
  159. # Load profile for this installation
  160. profile="%s/bash_profile.sh" % self.directory
  161. if not os.path.exists(profile):
  162. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  163. profile="$FWROOT/config/benchmark_profile"
  164. setup_util.replace_environ(config=profile,
  165. command='export TROOT=%s && export IROOT=%s' %
  166. (self.directory, self.install_root))
  167. # Run the module stop (inside parent of TROOT)
  168. # - we use the parent as a historical accident - a lot of tests
  169. # use subprocess's cwd argument already
  170. previousDir = os.getcwd()
  171. os.chdir(os.path.dirname(self.troot))
  172. logging.info("Running setup module stop (cwd=%s)", os.path.dirname(self.troot))
  173. try:
  174. retcode = self.setup_module.stop(out, err)
  175. if retcode == None:
  176. retcode = 0
  177. except Exception:
  178. retcode = 1
  179. st = traceback.format_exc()
  180. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  181. st = "Stop exception:\n%s\n" % st
  182. logging.info(st)
  183. err.write(st + '\n')
  184. os.chdir(previousDir)
  185. # Give processes sent a SIGTERM a moment to shut down gracefully
  186. time.sleep(5)
  187. return retcode
  188. ############################################################
  189. # End stop
  190. ############################################################
  191. ############################################################
  192. # verify_urls
  193. # Verifys each of the URLs for this test. THis will sinply
  194. # curl the URL and check for it's return status.
  195. # For each url, a flag will be set on this object for whether
  196. # or not it passed
  197. # Returns True if all verifications succeeded
  198. ############################################################
  199. def verify_urls(self, out, err):
  200. result = True
  201. def verify_type(test_type):
  202. test = self.runTests[test_type]
  203. test.setup_out_err(out, err)
  204. out.write(header("VERIFYING %s" % test_type.upper()))
  205. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  206. try:
  207. results = test.verify(base_url)
  208. except Exception as e:
  209. results = [('fail',"""Caused Exception in TFB
  210. This almost certainly means your return value is incorrect,
  211. but also that you have found a bug. Please submit an issue
  212. including this message: %s\n%s""" % (e, traceback.format_exc()),
  213. base_url)]
  214. logging.warning("Verifying test %s for %s caused an exception: %s", test_type, self.name, e)
  215. traceback.format_exc()
  216. test.failed = any(result is 'fail' for (result, reason, url) in results)
  217. test.warned = any(result is 'warn' for (result, reason, url) in results)
  218. test.passed = all(result is 'pass' for (result, reason, url) in results)
  219. def output_result(result, reason, url):
  220. out.write(" %s for %s\n" % (result.upper(), url))
  221. print " %s for %s" % (result.upper(), url)
  222. if reason is not None and len(reason) != 0:
  223. for line in reason.splitlines():
  224. out.write(" " + line + '\n')
  225. print " " + line
  226. [output_result(r1,r2,url) for (r1, r2, url) in results]
  227. if test.failed:
  228. self.benchmarker.report_verify_results(self, test_type, 'fail')
  229. elif test.warned:
  230. self.benchmarker.report_verify_results(self, test_type, 'warn')
  231. elif test.passed:
  232. self.benchmarker.report_verify_results(self, test_type, 'pass')
  233. else:
  234. raise Exception("What the hell")
  235. result = True
  236. for test_type in self.runTests:
  237. verify_type(test_type)
  238. if self.runTests[test_type].failed:
  239. result = False
  240. return result
  241. ############################################################
  242. # End verify_urls
  243. ############################################################
  244. ############################################################
  245. # benchmark
  246. # Runs the benchmark for each type of test that it implements
  247. # JSON/DB/Query.
  248. ############################################################
  249. def benchmark(self, out, err):
  250. def benchmark_type(test_type):
  251. out.write("BENCHMARKING %s ... " % test_type.upper())
  252. test = self.runTests[test_type]
  253. test.setup_out_err(out, err)
  254. output_file = self.benchmarker.output_file(self.name, test_type)
  255. if not os.path.exists(output_file):
  256. # Open to create the empty file
  257. with open(output_file, 'w'):
  258. pass
  259. if test.passed:
  260. if test.requires_db:
  261. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  262. else:
  263. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  264. # Begin resource usage metrics collection
  265. self.__begin_logging(test_type)
  266. # Run the benchmark
  267. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=output_file, stderr=err)
  268. p.communicate(remote_script)
  269. err.flush()
  270. # End resource usage metrics collection
  271. self.__end_logging()
  272. results = self.__parse_test(test_type)
  273. print "Benchmark results:"
  274. pprint(results)
  275. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  276. out.write( "Complete\n" )
  277. out.flush()
  278. for test_type in self.runTests:
  279. benchmark_type(test_type)
  280. ############################################################
  281. # End benchmark
  282. ############################################################
  283. ############################################################
  284. # parse_all
  285. # Method meant to be run for a given timestamp
  286. ############################################################
  287. def parse_all(self):
  288. for test_type in self.runTests:
  289. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  290. results = self.__parse_test(test_type)
  291. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  292. ############################################################
  293. # __parse_test(test_type)
  294. ############################################################
  295. def __parse_test(self, test_type):
  296. try:
  297. results = dict()
  298. results['results'] = []
  299. stats = []
  300. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  301. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  302. is_warmup = True
  303. rawData = None
  304. for line in raw_data:
  305. if "Queries:" in line or "Concurrency:" in line:
  306. is_warmup = False
  307. rawData = None
  308. continue
  309. if "Warmup" in line or "Primer" in line:
  310. is_warmup = True
  311. continue
  312. if not is_warmup:
  313. if rawData == None:
  314. rawData = dict()
  315. results['results'].append(rawData)
  316. #if "Requests/sec:" in line:
  317. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  318. # rawData['reportedResults'] = m.group(1)
  319. # search for weighttp data such as succeeded and failed.
  320. if "Latency" in line:
  321. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  322. if len(m) == 4:
  323. rawData['latencyAvg'] = m[0]
  324. rawData['latencyStdev'] = m[1]
  325. rawData['latencyMax'] = m[2]
  326. # rawData['latencyStdevPercent'] = m[3]
  327. #if "Req/Sec" in line:
  328. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  329. # if len(m) == 4:
  330. # rawData['requestsAvg'] = m[0]
  331. # rawData['requestsStdev'] = m[1]
  332. # rawData['requestsMax'] = m[2]
  333. # rawData['requestsStdevPercent'] = m[3]
  334. #if "requests in" in line:
  335. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  336. # if m != None:
  337. # # parse out the raw time, which may be in minutes or seconds
  338. # raw_time = m.group(1)
  339. # if "ms" in raw_time:
  340. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  341. # elif "s" in raw_time:
  342. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  343. # elif "m" in raw_time:
  344. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  345. # elif "h" in raw_time:
  346. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  347. if "requests in" in line:
  348. m = re.search("([0-9]+) requests in", line)
  349. if m != None:
  350. rawData['totalRequests'] = int(m.group(1))
  351. if "Socket errors" in line:
  352. if "connect" in line:
  353. m = re.search("connect ([0-9]+)", line)
  354. rawData['connect'] = int(m.group(1))
  355. if "read" in line:
  356. m = re.search("read ([0-9]+)", line)
  357. rawData['read'] = int(m.group(1))
  358. if "write" in line:
  359. m = re.search("write ([0-9]+)", line)
  360. rawData['write'] = int(m.group(1))
  361. if "timeout" in line:
  362. m = re.search("timeout ([0-9]+)", line)
  363. rawData['timeout'] = int(m.group(1))
  364. if "Non-2xx" in line:
  365. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  366. if m != None:
  367. rawData['5xx'] = int(m.group(1))
  368. if "STARTTIME" in line:
  369. m = re.search("[0-9]+", line)
  370. rawData["startTime"] = int(m.group(0))
  371. if "ENDTIME" in line:
  372. m = re.search("[0-9]+", line)
  373. rawData["endTime"] = int(m.group(0))
  374. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  375. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  376. stats.append(test_stats)
  377. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  378. json.dump(stats, stats_file)
  379. return results
  380. except IOError:
  381. return None
  382. ############################################################
  383. # End benchmark
  384. ############################################################
  385. ##########################################################################################
  386. # Private Methods
  387. ##########################################################################################
  388. ############################################################
  389. # __generate_concurrency_script(url, port)
  390. # Generates the string containing the bash script that will
  391. # be run on the client to benchmark a single test. This
  392. # specifically works for the variable concurrency tests (JSON
  393. # and DB)
  394. ############################################################
  395. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  396. if len(intervals) == 0:
  397. intervals = self.benchmarker.concurrency_levels
  398. headers = self.headers_template.format(accept=accept_header)
  399. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  400. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  401. interval=" ".join("{}".format(item) for item in intervals),
  402. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  403. pipeline=pipeline)
  404. ############################################################
  405. # __generate_query_script(url, port)
  406. # Generates the string containing the bash script that will
  407. # be run on the client to benchmark a single test. This
  408. # specifically works for the variable query tests (Query)
  409. ############################################################
  410. def __generate_query_script(self, url, port, accept_header):
  411. headers = self.headers_template.format(accept=accept_header)
  412. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  413. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  414. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  415. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  416. ############################################################
  417. # Returns True if any test type this this framework test will use a DB
  418. ############################################################
  419. def requires_database(self):
  420. '''Returns True/False if this test requires a database'''
  421. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  422. ############################################################
  423. # __begin_logging
  424. # Starts a thread to monitor the resource usage, to be synced with the client's time
  425. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  426. ############################################################
  427. def __begin_logging(self, test_type):
  428. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_type))
  429. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  430. --raw --socket --tcp --udp --unix --vm --disk-util \
  431. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  432. cmd = shlex.split(dstat_string)
  433. dev_null = open(os.devnull, "w")
  434. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  435. ##############################################################
  436. # Begin __end_logging
  437. # Stops the logger thread and blocks until shutdown is complete.
  438. ##############################################################
  439. def __end_logging(self):
  440. self.subprocess_handle.terminate()
  441. self.subprocess_handle.communicate()
  442. ##############################################################
  443. # Begin __parse_stats
  444. # For each test type, process all the statistics, and return a multi-layered dictionary
  445. # that has a structure as follows:
  446. # (timestamp)
  447. # | (main header) - group that the stat is in
  448. # | | (sub header) - title of the stat
  449. # | | | (stat) - the stat itself, usually a floating point number
  450. ##############################################################
  451. def __parse_stats(self, test_type, start_time, end_time, interval):
  452. stats_dict = dict()
  453. stats_file = self.benchmarker.stats_file(self.name, test_type)
  454. with open(stats_file) as stats:
  455. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  456. pass
  457. stats_reader = csv.reader(stats)
  458. main_header = stats_reader.next()
  459. sub_header = stats_reader.next()
  460. time_row = sub_header.index("epoch")
  461. int_counter = 0
  462. for row in stats_reader:
  463. time = float(row[time_row])
  464. int_counter+=1
  465. if time < start_time:
  466. continue
  467. elif time > end_time:
  468. return stats_dict
  469. if int_counter % interval != 0:
  470. continue
  471. row_dict = dict()
  472. for nextheader in main_header:
  473. if nextheader != "":
  474. row_dict[nextheader] = dict()
  475. header = ""
  476. for item_num, column in enumerate(row):
  477. if(len(main_header[item_num]) != 0):
  478. header = main_header[item_num]
  479. 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
  480. stats_dict[time] = row_dict
  481. return stats_dict
  482. ##############################################################
  483. # End __parse_stats
  484. ##############################################################
  485. def __getattr__(self, name):
  486. """For backwards compatibility, we used to pass benchmarker
  487. as the argument to the setup.py files"""
  488. try:
  489. x = getattr(self.benchmarker, name)
  490. except AttributeError:
  491. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  492. print "This is probably a bug"
  493. raise
  494. return x
  495. ##############################################################
  496. # Begin __calculate_average_stats
  497. # We have a large amount of raw data for the statistics that
  498. # may be useful for the stats nerds, but most people care about
  499. # a couple of numbers. For now, we're only going to supply:
  500. # * Average CPU
  501. # * Average Memory
  502. # * Total network use
  503. # * Total disk use
  504. # More may be added in the future. If they are, please update
  505. # the above list.
  506. # Note: raw_stats is directly from the __parse_stats method.
  507. # Recall that this consists of a dictionary of timestamps,
  508. # each of which contain a dictionary of stat categories which
  509. # contain a dictionary of stats
  510. ##############################################################
  511. def __calculate_average_stats(self, raw_stats):
  512. raw_stat_collection = dict()
  513. for timestamp, time_dict in raw_stats.items():
  514. for main_header, sub_headers in time_dict.items():
  515. item_to_append = None
  516. if 'cpu' in main_header:
  517. # We want to take the idl stat and subtract it from 100
  518. # to get the time that the CPU is NOT idle.
  519. item_to_append = sub_headers['idl'] - 100.0
  520. elif main_header == 'memory usage':
  521. item_to_append = sub_headers['used']
  522. elif 'net' in main_header:
  523. # Network stats have two parts - recieve and send. We'll use a tuple of
  524. # style (recieve, send)
  525. item_to_append = (sub_headers['recv'], sub_headers['send'])
  526. elif 'dsk' or 'io' in main_header:
  527. # Similar for network, except our tuple looks like (read, write)
  528. item_to_append = (sub_headers['read'], sub_headers['writ'])
  529. if item_to_append is not None:
  530. if main_header not in raw_stat_collection:
  531. raw_stat_collection[main_header] = list()
  532. raw_stat_collection[main_header].append(item_to_append)
  533. # Simple function to determine human readable size
  534. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  535. def sizeof_fmt(num):
  536. # We'll assume that any number we get is convertable to a float, just in case
  537. num = float(num)
  538. for x in ['bytes','KB','MB','GB']:
  539. if num < 1024.0 and num > -1024.0:
  540. return "%3.1f%s" % (num, x)
  541. num /= 1024.0
  542. return "%3.1f%s" % (num, 'TB')
  543. # Now we have our raw stats in a readable format - we need to format it for display
  544. # We need a floating point sum, so the built in sum doesn't cut it
  545. display_stat_collection = dict()
  546. for header, values in raw_stat_collection.items():
  547. display_stat = None
  548. if 'cpu' in header:
  549. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  550. elif main_header == 'memory usage':
  551. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  552. elif 'net' in main_header:
  553. receive, send = zip(*values) # unzip
  554. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  555. else: # if 'dsk' or 'io' in header:
  556. read, write = zip(*values) # unzip
  557. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  558. display_stat_collection[header] = display_stat
  559. return display_stat
  560. ###########################################################################################
  561. # End __calculate_average_stats
  562. #########################################################################################
  563. ##########################################################################################
  564. # Constructor
  565. ##########################################################################################
  566. def __init__(self, name, directory, benchmarker, runTests, args):
  567. self.name = name
  568. self.directory = directory
  569. self.benchmarker = benchmarker
  570. self.runTests = runTests
  571. self.fwroot = benchmarker.fwroot
  572. # setup logging
  573. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  574. self.install_root="%s/%s" % (self.fwroot, "installs")
  575. if benchmarker.install_strategy is 'pertest':
  576. self.install_root="%s/pertest/%s" % (self.install_root, name)
  577. # Used in setup.py scripts for consistency with
  578. # the bash environment variables
  579. self.troot = self.directory
  580. self.iroot = self.install_root
  581. self.__dict__.update(args)
  582. # ensure directory has __init__.py file so that we can use it as a Python package
  583. if not os.path.exists(os.path.join(directory, "__init__.py")):
  584. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  585. open(os.path.join(directory, "__init__.py"), 'w').close()
  586. # Import the module (TODO - consider using sys.meta_path)
  587. # Note: You can see the log output if you really want to, but it's a *ton*
  588. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  589. if dir_rel_to_fwroot != ".":
  590. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  591. logging.log(0, "Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  592. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  593. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  594. else:
  595. logging.log(0, "Importing %s.%s", directory, self.setup_file)
  596. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  597. ############################################################
  598. # End __init__
  599. ############################################################
  600. ############################################################
  601. # End FrameworkTest
  602. ############################################################
  603. ##########################################################################################
  604. # Static methods
  605. ##########################################################################################
  606. ##############################################################
  607. # parse_config(config, directory, benchmarker)
  608. # parses a config file and returns a list of FrameworkTest
  609. # objects based on that config file.
  610. ##############################################################
  611. def parse_config(config, directory, benchmarker):
  612. tests = []
  613. # The config object can specify multiple tests
  614. # Loop over them and parse each into a FrameworkTest
  615. for test in config['tests']:
  616. for test_name, test_keys in test.iteritems():
  617. # Prefix all test names with framework except 'default' test
  618. if test_name == 'default':
  619. test_name = config['framework']
  620. else:
  621. test_name = "%s-%s" % (config['framework'], test_name)
  622. # Ensure FrameworkTest.framework is available
  623. if not test_keys['framework']:
  624. test_keys['framework'] = config['framework']
  625. #if test_keys['framework'].lower() != config['framework'].lower():
  626. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  627. # (test_name, test_keys['framework'], config['framework']))
  628. # Confirm required keys are present
  629. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  630. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  631. if not all (key in test_keys for key in required):
  632. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  633. # Map test type to a parsed FrameworkTestType object
  634. runTests = dict()
  635. for type_name, type_obj in benchmarker.types.iteritems():
  636. try:
  637. runTests[type_name] = type_obj.copy().parse(test_keys)
  638. except AttributeError as ae:
  639. # This is quite common - most tests don't support all types
  640. # Quitely log it and move on
  641. logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  642. pass
  643. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  644. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, test_keys))
  645. return tests
  646. ##############################################################
  647. # End parse_config
  648. ##############################################################