framework_test.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  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. # Test Variables
  105. ############################################################
  106. JSON = "json"
  107. DB = "db"
  108. QUERY = "query"
  109. FORTUNE = "fortune"
  110. UPDATE = "update"
  111. PLAINTEXT = "plaintext"
  112. ##########################################################################################
  113. # Public Methods
  114. ##########################################################################################
  115. ############################################################
  116. # Validates the jsonString is an array with a length of
  117. # 2, that each entry in the array is a JSON object, that
  118. # each object has an "id" and a "randomNumber" key, and that
  119. # both keys map to integers.
  120. ############################################################
  121. def validateQuery(self, jsonString, out, err):
  122. err_str = ""
  123. if jsonString is None or len(jsonString) == 0:
  124. err_str += "Empty Response"
  125. return (False, err_str)
  126. try:
  127. arr = [{k.lower(): v for k,v in d.iteritems()} for d in json.loads(jsonString)]
  128. if len(arr) != 2:
  129. err_str += "Expected array of length 2. Got length {length}. ".format(length=len(arr))
  130. for obj in arr:
  131. id_ret_val = True
  132. random_num_ret_val = True
  133. if "id" not in obj or "randomnumber" not in obj:
  134. err_str += "Expected keys id and randomNumber to be in JSON string. "
  135. break
  136. try:
  137. if not isinstance(float(obj["id"]), float):
  138. id_ret_val=False
  139. except:
  140. id_ret_val=False
  141. if not id_ret_val:
  142. err_str += "Expected id to be type int or float, got '{rand}' ".format(rand=obj["randomnumber"])
  143. try:
  144. if not isinstance(float(obj["randomnumber"]), float):
  145. random_num_ret_val=False
  146. except:
  147. random_num_ret_val=False
  148. if not random_num_ret_val:
  149. err_str += "Expected randomNumber to be type int or float, got '{rand}' ".format(rand=obj["randomnumber"])
  150. except:
  151. err_str += "Got exception when trying to validate the query test: {exception}".format(exception=traceback.format_exc())
  152. return (True, ) if len(err_str) == 0 else (False, err_str)
  153. ############################################################
  154. # Validates the jsonString is an array with a length of
  155. # 1, that each entry in the array is a JSON object, that
  156. # each object has an "id" and a "randomNumber" key, and that
  157. # both keys map to integers.
  158. ############################################################
  159. def validateQueryOneOrLess(self, jsonString, out, err):
  160. err_str = ""
  161. if jsonString is None or len(jsonString) == 0:
  162. err_str += "Empty Response"
  163. else:
  164. try:
  165. json_load = json.loads(jsonString)
  166. if not isinstance(json_load, list):
  167. err_str += "Expected JSON array, got {typeObj}. ".format(typeObj=type(json_load))
  168. if len(json_load) != 1:
  169. err_str += "Expected array of length 1. Got length {length}. ".format(length=len(json_load))
  170. obj = {k.lower(): v for k,v in json_load[0].iteritems()}
  171. id_ret_val = True
  172. random_num_ret_val = True
  173. if "id" not in obj or "randomnumber" not in obj:
  174. err_str += "Expected keys id and randomNumber to be in JSON string. "
  175. try:
  176. if not isinstance(float(obj["id"]), float):
  177. id_ret_val=False
  178. except:
  179. id_ret_val=False
  180. if not id_ret_val:
  181. err_str += "Expected id to be type int or float, got '{rand}'. ".format(rand=obj["randomnumber"])
  182. try:
  183. if not isinstance(float(obj["randomnumber"]), float):
  184. random_num_ret_val=False
  185. except:
  186. random_num_ret_val=False
  187. if not random_num_ret_val:
  188. err_str += "Expected randomNumber to be type int or float, got '{rand}'. ".format(rand=obj["randomnumber"])
  189. except:
  190. err_str += "Got exception when trying to validate the query test: {exception} ".format(exception=traceback.format_exc())
  191. return (True, ) if len(err_str) == 0 else (False, err_str)
  192. ############################################################
  193. # Validates the jsonString is an array with a length of
  194. # 500, that each entry in the array is a JSON object, that
  195. # each object has an "id" and a "randomNumber" key, and that
  196. # both keys map to integers.
  197. ############################################################
  198. def validateQueryFiveHundredOrMore(self, jsonString, out, err):
  199. err_str = ""
  200. if jsonString is None or len(jsonString) == 0:
  201. err_str += "Empty Response"
  202. return (False, err_str)
  203. try:
  204. arr = [{k.lower(): v for k,v in d.iteritems()} for d in json.loads(jsonString)]
  205. if len(arr) != 500:
  206. err_str += "Expected array of length 500. Got length {length}. ".format(length=len(arr))
  207. return (False, err_str)
  208. for obj in arr:
  209. id_ret_val = True
  210. random_num_ret_val = True
  211. if "id" not in obj or "randomnumber" not in obj:
  212. err_str += "Expected keys id and randomNumber to be in JSON string. "
  213. break
  214. try:
  215. if not isinstance(float(obj["id"]), float):
  216. id_ret_val=False
  217. except:
  218. id_ret_val=False
  219. if not id_ret_val:
  220. err_str += "Expected id to be type int or float, got '{rand}'. ".format(rand=obj["randomnumber"])
  221. try:
  222. if not isinstance(float(obj["randomnumber"]), float):
  223. random_num_ret_val=False
  224. except:
  225. random_num_ret_val=False
  226. if not random_num_ret_val:
  227. err_str += "Expected randomNumber to be type int or float, got '{rand}'. ".format(rand=obj["randomnumber"])
  228. except:
  229. err_str += "Got exception when trying to validate the query test: {exception} ".format(exception=traceback.format_exc())
  230. return (True, ) if len(err_str) == 0 else (False, err_str)
  231. ############################################################
  232. # Parses the given HTML string and asks a FortuneHTMLParser
  233. # whether the parsed string is a valid fortune return.
  234. ############################################################
  235. def validateFortune(self, htmlString, out, err):
  236. err_str = ""
  237. if htmlString is None or len(htmlString) == 0:
  238. err_str += "Empty Response"
  239. return (False, err_str)
  240. try:
  241. parser = FortuneHTMLParser()
  242. parser.feed(htmlString)
  243. valid = parser.isValidFortune(out)
  244. return (valid, '' if valid else 'Did not pass validation')
  245. except:
  246. print "Got exception when trying to validate the fortune test: {exception} ".format(exception=traceback.format_exc())
  247. return (False, err_str)
  248. ############################################################
  249. # Validates the jsonString is an array with a length of
  250. # 2, that each entry in the array is a JSON object, that
  251. # each object has an "id" and a "randomNumber" key, and that
  252. # both keys map to integers.
  253. ############################################################
  254. def validateUpdate(self, jsonString, out, err):
  255. err_str = ""
  256. if jsonString is None or len(jsonString) == 0:
  257. err_str += "Empty Response"
  258. return (False, err_str)
  259. try:
  260. arr = [{k.lower(): v for k,v in d.iteritems()} for d in json.loads(jsonString)]
  261. if len(arr) != 2:
  262. err_str += "Expected array of length 2. Got length {length}.\n".format(length=len(arr))
  263. for obj in arr:
  264. id_ret_val = True
  265. random_num_ret_val = True
  266. if "id" not in obj or "randomnumber" not in obj:
  267. err_str += "Expected keys id and randomNumber to be in JSON string.\n"
  268. return (False, err_str)
  269. try:
  270. if not isinstance(float(obj["id"]), float):
  271. id_ret_val=False
  272. except:
  273. id_ret_val=False
  274. if not id_ret_val:
  275. err_str += "Expected id to be type int or float, got '{rand}'.\n".format(rand=obj["randomnumber"])
  276. try:
  277. if not isinstance(float(obj["randomnumber"]), float):
  278. random_num_ret_val=False
  279. except:
  280. random_num_ret_val=False
  281. if not random_num_ret_val:
  282. err_str += "Expected randomNumber to be type int or float, got '{rand}'.\n".format(rand=obj["randomnumber"])
  283. except:
  284. err_str += "Got exception when trying to validate the update test: {exception}\n".format(exception=traceback.format_exc())
  285. return (True, ) if len(err_str) == 0 else (False, err_str)
  286. ############################################################
  287. # start(benchmarker)
  288. # Start the test using it's setup file
  289. ############################################################
  290. def start(self, out, err):
  291. # Load profile for this installation
  292. profile="%s/bash_profile.sh" % self.directory
  293. if not os.path.exists(profile):
  294. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  295. profile="$FWROOT/config/benchmark_profile"
  296. # Setup variables for TROOT and IROOT
  297. setup_util.replace_environ(config=profile,
  298. command='export TROOT=%s && export IROOT=%s' %
  299. (self.directory, self.install_root))
  300. # Because start can take so long, we print a dot to let the user know
  301. # we are working
  302. class ProgressPrinterThread(Thread):
  303. def __init__(self, event):
  304. Thread.__init__(self)
  305. self.stopped = event
  306. def run(self):
  307. while not self.stopped.wait(20):
  308. sys.stderr.write("Waiting for start to return...\n")
  309. stopFlag = Event()
  310. thread = ProgressPrinterThread(stopFlag)
  311. thread.start()
  312. # Run the module start (inside parent of TROOT)
  313. # - we use the parent as a historical accident - a lot of tests
  314. # use subprocess's cwd argument already
  315. previousDir = os.getcwd()
  316. os.chdir(os.path.dirname(self.troot))
  317. logging.info("Running setup module start (cwd=%s)", os.path.dirname(self.troot))
  318. try:
  319. retcode = self.setup_module.start(self, out, err)
  320. if retcode == None:
  321. retcode = 0
  322. except Exception:
  323. retcode = 1
  324. st = traceback.format_exc()
  325. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  326. st = "Start exception:\n%s" % st
  327. logging.info(st)
  328. err.write(st + '\n')
  329. os.chdir(previousDir)
  330. # Stop the progress printer
  331. stopFlag.set()
  332. logging.info("Start completed, running %s", self.benchmarker.mode)
  333. return retcode
  334. ############################################################
  335. # End start
  336. ############################################################
  337. ############################################################
  338. # stop(benchmarker)
  339. # Stops the test using it's setup file
  340. ############################################################
  341. def stop(self, out, err):
  342. # Load profile for this installation
  343. profile="%s/bash_profile.sh" % self.directory
  344. if not os.path.exists(profile):
  345. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  346. profile="$FWROOT/config/benchmark_profile"
  347. setup_util.replace_environ(config=profile,
  348. command='export TROOT=%s && export IROOT=%s' %
  349. (self.directory, self.install_root))
  350. # Run the module stop (inside parent of TROOT)
  351. # - we use the parent as a historical accident - a lot of tests
  352. # use subprocess's cwd argument already
  353. previousDir = os.getcwd()
  354. os.chdir(os.path.dirname(self.troot))
  355. logging.info("Running setup module stop (cwd=%s)", os.path.dirname(self.troot))
  356. try:
  357. retcode = self.setup_module.stop(out, err)
  358. if retcode == None:
  359. retcode = 0
  360. except Exception:
  361. retcode = 1
  362. st = traceback.format_exc()
  363. st = '\n'.join((4 * ' ') + x for x in st.splitlines())
  364. st = "Stop exception:\n%s\n" % st
  365. logging.info(st)
  366. err.write(st + '\n')
  367. os.chdir(previousDir)
  368. # Give processes sent a SIGTERM a moment to shut down gracefully
  369. time.sleep(5)
  370. return retcode
  371. ############################################################
  372. # End stop
  373. ############################################################
  374. ############################################################
  375. # verify_urls
  376. # Verifys each of the URLs for this test. THis will sinply
  377. # curl the URL and check for it's return status.
  378. # For each url, a flag will be set on this object for whether
  379. # or not it passed
  380. # Returns True if all verifications succeeded
  381. ############################################################
  382. def verify_urls(self, out, err):
  383. result = True
  384. def verify_type(test_type):
  385. test = self.runTests[test_type]
  386. out.write(header("VERIFYING %s" % test_type.upper()))
  387. base_url = "http://%s:%s" % (self.benchmarker.server_host, self.port)
  388. results = test.verify(base_url)
  389. test.failed = any(result is 'fail' for (result, reason, url) in results)
  390. test.warned = any(result is 'warn' for (result, reason, url) in results)
  391. test.passed = all(result is 'pass' for (result, reason, url) in results)
  392. def output_result(result, reason, url):
  393. out.write(" %s for %s\n" % (result.upper(), url))
  394. print " %s for %s" % (result.upper(), url)
  395. if reason is not None and len(reason) != 0:
  396. for line in reason.splitlines():
  397. out.write(" " + line + '\n')
  398. print " " + line
  399. [output_result(r1,r2,url) for (r1, r2, url) in results]
  400. if test.failed:
  401. self.benchmarker.report_verify_results(self, test_type, 'fail')
  402. elif test.warned:
  403. self.benchmarker.report_verify_results(self, test_type, 'warn')
  404. elif test.passed:
  405. self.benchmarker.report_verify_results(self, test_type, 'pass')
  406. else:
  407. raise Exception("What the hell")
  408. # JSON
  409. if self.runTests[self.JSON]:
  410. out.write(header("VERIFYING JSON (%s)" % self.json_url))
  411. out.flush()
  412. url = self.benchmarker.generate_url(self.json_url, self.port)
  413. output = self.__curl_url(url, self.JSON, out, err)
  414. out.write("VALIDATING JSON ... ")
  415. ret_tuple = self.validateJson(output, out, err)
  416. if ret_tuple[0]:
  417. self.json_url_passed = True
  418. out.write("PASS\n\n")
  419. self.benchmarker.report_verify_results(self, self.JSON, 'pass')
  420. else:
  421. self.json_url_passed = False
  422. out.write("\nFAIL" + ret_tuple[1] + "\n\n")
  423. self.benchmarker.report_verify_results(self, self.JSON, 'fail')
  424. result = False
  425. out.flush()
  426. # DB
  427. if self.runTests[self.DB]:
  428. out.write(header("VERIFYING DB (%s)" % self.db_url))
  429. out.flush()
  430. url = self.benchmarker.generate_url(self.db_url, self.port)
  431. output = self.__curl_url(url, self.DB, out, err)
  432. validate_ret_tuple = self.validateDb(output, out, err)
  433. validate_strict_ret_tuple = self.validateDbStrict(output, out, err)
  434. if validate_ret_tuple[0]:
  435. self.db_url_passed = True
  436. else:
  437. self.db_url_passed = False
  438. if validate_strict_ret_tuple:
  439. self.db_url_warn = False
  440. else:
  441. self.db_url_warn = True
  442. out.write("VALIDATING DB ... ")
  443. if self.db_url_passed:
  444. out.write("PASS")
  445. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  446. if self.db_url_warn:
  447. out.write(" (with warnings) " + validate_strict_ret_tuple[1])
  448. self.benchmarker.report_verify_results(self, self.DB, 'warn')
  449. out.write("\n\n")
  450. else:
  451. self.benchmarker.report_verify_results(self, self.DB, 'fail')
  452. out.write("\nFAIL" + validate_ret_tuple[1])
  453. result = False
  454. out.flush()
  455. # Query
  456. if self.runTests[self.QUERY]:
  457. out.write(header("VERIFYING QUERY (%s)" % self.query_url+"2"))
  458. out.flush()
  459. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  460. output = self.__curl_url(url, self.QUERY, out, err)
  461. ret_tuple = self.validateQuery(output, out, err)
  462. if ret_tuple[0]:
  463. self.query_url_passed = True
  464. out.write(self.query_url + "2 - PASS\n\n")
  465. else:
  466. self.query_url_passed = False
  467. out.write(self.query_url + "2 - FAIL " + ret_tuple[1] + "\n\n")
  468. out.write("-----------------------------------------------------\n\n")
  469. out.flush()
  470. self.query_url_warn = False
  471. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  472. output2 = self.__curl_url(url2, self.QUERY, out, err)
  473. ret_tuple = self.validateQueryOneOrLess(output2, out, err)
  474. if not ret_tuple[0]:
  475. self.query_url_warn = True
  476. out.write(self.query_url + "0 - WARNING " + ret_tuple[1] + "\n\n")
  477. else:
  478. out.write(self.query_url + "0 - PASS\n\n")
  479. out.write("-----------------------------------------------------\n\n")
  480. out.flush()
  481. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  482. output3 = self.__curl_url(url3, self.QUERY, out, err)
  483. ret_tuple = self.validateQueryOneOrLess(output3, out, err)
  484. if not ret_tuple[0]:
  485. self.query_url_warn = True
  486. out.write(self.query_url + "foo - WARNING " + ret_tuple[1] + "\n\n")
  487. else:
  488. out.write(self.query_url + "foo - PASS\n\n")
  489. out.write("-----------------------------------------------------\n\n")
  490. out.flush()
  491. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  492. output4 = self.__curl_url(url4, self.QUERY, out, err)
  493. ret_tuple = self.validateQueryFiveHundredOrMore(output4, out, err)
  494. if not ret_tuple[0]:
  495. self.query_url_warn = True
  496. out.write(self.query_url + "501 - WARNING " + ret_tuple[1] + "\n\n")
  497. else:
  498. out.write(self.query_url + "501 - PASS\n\n")
  499. out.write("-----------------------------------------------------\n\n\n")
  500. out.flush()
  501. out.write("VALIDATING QUERY ... ")
  502. if self.query_url_passed:
  503. out.write("PASS")
  504. self.benchmarker.report_verify_results(self, self.QUERY, 'pass')
  505. if self.query_url_warn:
  506. out.write(" (with warnings)")
  507. self.benchmarker.report_verify_results(self, self.QUERY, 'warn')
  508. out.write("\n\n")
  509. else:
  510. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  511. self.benchmarker.report_verify_results(self, self.QUERY, 'fail')
  512. result = False
  513. out.flush()
  514. # Fortune
  515. if self.runTests[self.FORTUNE]:
  516. out.write(header("VERIFYING FORTUNE (%s)" % self.fortune_url))
  517. out.flush()
  518. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  519. output = self.__curl_url(url, self.FORTUNE, out, err)
  520. out.write("VALIDATING FORTUNE ... ")
  521. ret_tuple = self.validateFortune(output, out, err)
  522. if ret_tuple[0]:
  523. self.fortune_url_passed = True
  524. out.write("PASS\n\n")
  525. self.benchmarker.report_verify_results(self, self.FORTUNE, 'pass')
  526. else:
  527. self.fortune_url_passed = False
  528. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  529. self.benchmarker.report_verify_results(self, self.FORTUNE, 'fail')
  530. result = False
  531. out.flush()
  532. # Update
  533. if self.runTests[self.UPDATE]:
  534. out.write(header("VERIFYING UPDATE (%s)" % self.update_url))
  535. out.flush()
  536. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  537. output = self.__curl_url(url, self.UPDATE, out, err)
  538. out.write("VALIDATING UPDATE ... ")
  539. ret_tuple = self.validateUpdate(output, out, err)
  540. if ret_tuple[0]:
  541. self.update_url_passed = True
  542. out.write("PASS\n\n")
  543. self.benchmarker.report_verify_results(self, self.UPDATE, 'pass')
  544. else:
  545. self.update_url_passed = False
  546. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  547. self.benchmarker.report_verify_results(self, self.UPDATE, 'fail')
  548. result = False
  549. out.flush()
  550. # plaintext
  551. if self.runTests[self.PLAINTEXT]:
  552. out.write(header("VERIFYING PLAINTEXT (%s)" % self.plaintext_url))
  553. out.flush()
  554. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  555. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  556. out.write("VALIDATING PLAINTEXT ... ")
  557. ret_tuple = self.validatePlaintext(output, out, err)
  558. if ret_tuple[0]:
  559. self.plaintext_url_passed = True
  560. out.write("PASS\n\n")
  561. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'pass')
  562. else:
  563. self.plaintext_url_passed = False
  564. out.write("\nFAIL\n\n" + ret_tuple[1] + "\n\n")
  565. self.benchmarker.report_verify_results(self, self.PLAINTEXT, 'fail')
  566. result = False
  567. out.flush()
  568. return result
  569. ############################################################
  570. # End verify_urls
  571. ############################################################
  572. ############################################################
  573. # benchmark
  574. # Runs the benchmark for each type of test that it implements
  575. # JSON/DB/Query.
  576. ############################################################
  577. def benchmark(self, out, err):
  578. def benchmark_type(test_type):
  579. out.write("BENCHMARKING %s ... " % test_type.upper())
  580. test = self.runTests[test_type]
  581. output_file = self.benchmarker.output_file(self.name, test_type)
  582. if not os.path.exists(output_file):
  583. # Open to create the empty file
  584. with open(output_file, 'w'):
  585. pass
  586. if test.passed:
  587. if test.requires_db:
  588. remote_script = self.__generate_query_script(test.get_url(), self.port, test.accept_header)
  589. else:
  590. remote_script = self.__generate_concurrency_script(test.get_url(), self.port, test.accept_header)
  591. self.__begin_logging(test_type)
  592. self.__run_benchmark(remote_script, output_file, err)
  593. self.__end_logging()
  594. results = self.__parse_test(test_type)
  595. print "Benchmark results:"
  596. pprint(results)
  597. self.benchmarker.report_benchmark_results(framework=self, test=test_type, results=results['results'])
  598. out.write( "Complete\n" )
  599. out.flush()
  600. # JSON
  601. if self.runTests[self.JSON]:
  602. try:
  603. out.write("BENCHMARKING JSON ... ")
  604. out.flush()
  605. results = None
  606. output_file = self.benchmarker.output_file(self.name, self.JSON)
  607. if not os.path.exists(output_file):
  608. with open(output_file, 'w'):
  609. # Simply opening the file in write mode should create the empty file.
  610. pass
  611. if self.json_url_passed:
  612. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  613. self.__begin_logging(self.JSON)
  614. self.__run_benchmark(remote_script, output_file, err)
  615. self.__end_logging()
  616. results = self.__parse_test(self.JSON)
  617. print results
  618. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  619. out.write( "Complete\n" )
  620. out.flush()
  621. except AttributeError:
  622. pass
  623. # DB
  624. if self.runTests[self.DB]:
  625. try:
  626. out.write("BENCHMARKING DB ... ")
  627. out.flush()
  628. results = None
  629. output_file = self.benchmarker.output_file(self.name, self.DB)
  630. if not os.path.exists(output_file):
  631. with open(output_file, 'w'):
  632. # Simply opening the file in write mode should create the empty file.
  633. pass
  634. if self.db_url_passed:
  635. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  636. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  637. self.__begin_logging(self.DB)
  638. self.__run_benchmark(remote_script, output_file, err)
  639. self.__end_logging()
  640. results = self.__parse_test(self.DB)
  641. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  642. out.write( "Complete\n" )
  643. except AttributeError:
  644. pass
  645. # Query
  646. if self.runTests[self.QUERY]:
  647. try:
  648. out.write("BENCHMARKING Query ... ")
  649. out.flush()
  650. results = None
  651. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  652. if not os.path.exists(output_file):
  653. with open(output_file, 'w'):
  654. # Simply opening the file in write mode should create the empty file.
  655. pass
  656. if self.query_url_passed:
  657. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  658. self.__begin_logging(self.QUERY)
  659. self.__run_benchmark(remote_script, output_file, err)
  660. self.__end_logging()
  661. results = self.__parse_test(self.QUERY)
  662. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  663. out.write( "Complete\n" )
  664. out.flush()
  665. except AttributeError:
  666. pass
  667. # fortune
  668. if self.runTests[self.FORTUNE]:
  669. try:
  670. out.write("BENCHMARKING Fortune ... ")
  671. out.flush()
  672. results = None
  673. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  674. if not os.path.exists(output_file):
  675. with open(output_file, 'w'):
  676. # Simply opening the file in write mode should create the empty file.
  677. pass
  678. if self.fortune_url_passed:
  679. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  680. self.__begin_logging(self.FORTUNE)
  681. self.__run_benchmark(remote_script, output_file, err)
  682. self.__end_logging()
  683. results = self.__parse_test(self.FORTUNE)
  684. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  685. out.write( "Complete\n" )
  686. out.flush()
  687. except AttributeError:
  688. pass
  689. # update
  690. if self.runTests[self.UPDATE]:
  691. try:
  692. out.write("BENCHMARKING Update ... ")
  693. out.flush()
  694. results = None
  695. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  696. if not os.path.exists(output_file):
  697. with open(output_file, 'w'):
  698. # Simply opening the file in write mode should create the empty file.
  699. pass
  700. if self.update_url_passed:
  701. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  702. self.__begin_logging(self.UPDATE)
  703. self.__run_benchmark(remote_script, output_file, err)
  704. self.__end_logging()
  705. results = self.__parse_test(self.UPDATE)
  706. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  707. out.write( "Complete\n" )
  708. out.flush()
  709. except AttributeError:
  710. pass
  711. # plaintext
  712. if self.runTests[self.PLAINTEXT]:
  713. try:
  714. out.write("BENCHMARKING Plaintext ... ")
  715. out.flush()
  716. results = None
  717. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  718. if not os.path.exists(output_file):
  719. with open(output_file, 'w'):
  720. # Simply opening the file in write mode should create the empty file.
  721. pass
  722. if self.plaintext_url_passed:
  723. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  724. self.__begin_logging(self.PLAINTEXT)
  725. self.__run_benchmark(remote_script, output_file, err)
  726. self.__end_logging()
  727. results = self.__parse_test(self.PLAINTEXT)
  728. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  729. out.write( "Complete\n" )
  730. out.flush()
  731. except AttributeError:
  732. traceback.print_exc()
  733. pass
  734. ############################################################
  735. # End benchmark
  736. ############################################################
  737. ############################################################
  738. # parse_all
  739. # Method meant to be run for a given timestamp
  740. ############################################################
  741. def parse_all(self):
  742. # JSON
  743. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  744. results = self.__parse_test(self.JSON)
  745. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  746. # DB
  747. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  748. results = self.__parse_test(self.DB)
  749. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  750. # Query
  751. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  752. results = self.__parse_test(self.QUERY)
  753. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  754. # Fortune
  755. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  756. results = self.__parse_test(self.FORTUNE)
  757. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  758. # Update
  759. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  760. results = self.__parse_test(self.UPDATE)
  761. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  762. # Plaintext
  763. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  764. results = self.__parse_test(self.PLAINTEXT)
  765. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  766. ############################################################
  767. # End parse_all
  768. ############################################################
  769. ############################################################
  770. # __parse_test(test_type)
  771. ############################################################
  772. def __parse_test(self, test_type):
  773. try:
  774. results = dict()
  775. results['results'] = []
  776. stats = []
  777. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  778. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  779. is_warmup = True
  780. rawData = None
  781. for line in raw_data:
  782. if "Queries:" in line or "Concurrency:" in line:
  783. is_warmup = False
  784. rawData = None
  785. continue
  786. if "Warmup" in line or "Primer" in line:
  787. is_warmup = True
  788. continue
  789. if not is_warmup:
  790. if rawData == None:
  791. rawData = dict()
  792. results['results'].append(rawData)
  793. #if "Requests/sec:" in line:
  794. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  795. # rawData['reportedResults'] = m.group(1)
  796. # search for weighttp data such as succeeded and failed.
  797. if "Latency" in line:
  798. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  799. if len(m) == 4:
  800. rawData['latencyAvg'] = m[0]
  801. rawData['latencyStdev'] = m[1]
  802. rawData['latencyMax'] = m[2]
  803. # rawData['latencyStdevPercent'] = m[3]
  804. #if "Req/Sec" in line:
  805. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  806. # if len(m) == 4:
  807. # rawData['requestsAvg'] = m[0]
  808. # rawData['requestsStdev'] = m[1]
  809. # rawData['requestsMax'] = m[2]
  810. # rawData['requestsStdevPercent'] = m[3]
  811. #if "requests in" in line:
  812. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  813. # if m != None:
  814. # # parse out the raw time, which may be in minutes or seconds
  815. # raw_time = m.group(1)
  816. # if "ms" in raw_time:
  817. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  818. # elif "s" in raw_time:
  819. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  820. # elif "m" in raw_time:
  821. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  822. # elif "h" in raw_time:
  823. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  824. if "requests in" in line:
  825. m = re.search("([0-9]+) requests in", line)
  826. if m != None:
  827. rawData['totalRequests'] = int(m.group(1))
  828. if "Socket errors" in line:
  829. if "connect" in line:
  830. m = re.search("connect ([0-9]+)", line)
  831. rawData['connect'] = int(m.group(1))
  832. if "read" in line:
  833. m = re.search("read ([0-9]+)", line)
  834. rawData['read'] = int(m.group(1))
  835. if "write" in line:
  836. m = re.search("write ([0-9]+)", line)
  837. rawData['write'] = int(m.group(1))
  838. if "timeout" in line:
  839. m = re.search("timeout ([0-9]+)", line)
  840. rawData['timeout'] = int(m.group(1))
  841. if "Non-2xx" in line:
  842. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  843. if m != None:
  844. rawData['5xx'] = int(m.group(1))
  845. if "STARTTIME" in line:
  846. m = re.search("[0-9]+", line)
  847. rawData["startTime"] = int(m.group(0))
  848. if "ENDTIME" in line:
  849. m = re.search("[0-9]+", line)
  850. rawData["endTime"] = int(m.group(0))
  851. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  852. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  853. stats.append(test_stats)
  854. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  855. json.dump(stats, stats_file)
  856. return results
  857. except IOError:
  858. return None
  859. ############################################################
  860. # End benchmark
  861. ############################################################
  862. ##########################################################################################
  863. # Private Methods
  864. ##########################################################################################
  865. ############################################################
  866. # __run_benchmark(script, output_file)
  867. # Runs a single benchmark using the script which is a bash
  868. # template that uses weighttp to run the test. All the results
  869. # outputed to the output_file.
  870. ############################################################
  871. def __run_benchmark(self, script, output_file, err):
  872. with open(output_file, 'w') as raw_file:
  873. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  874. p.communicate(script)
  875. err.flush()
  876. ############################################################
  877. # End __run_benchmark
  878. ############################################################
  879. ############################################################
  880. # __generate_concurrency_script(url, port)
  881. # Generates the string containing the bash script that will
  882. # be run on the client to benchmark a single test. This
  883. # specifically works for the variable concurrency tests (JSON
  884. # and DB)
  885. ############################################################
  886. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  887. if len(intervals) == 0:
  888. intervals = self.benchmarker.concurrency_levels
  889. headers = self.__get_request_headers(accept_header)
  890. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  891. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  892. interval=" ".join("{}".format(item) for item in intervals),
  893. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  894. pipeline=pipeline)
  895. ############################################################
  896. # End __generate_concurrency_script
  897. ############################################################
  898. ############################################################
  899. # __generate_query_script(url, port)
  900. # Generates the string containing the bash script that will
  901. # be run on the client to benchmark a single test. This
  902. # specifically works for the variable query tests (Query)
  903. ############################################################
  904. def __generate_query_script(self, url, port, accept_header):
  905. headers = self.__get_request_headers(accept_header)
  906. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  907. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  908. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  909. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  910. ############################################################
  911. # End __generate_query_script
  912. ############################################################
  913. ############################################################
  914. # __get_request_headers(accept_header)
  915. # Generates the complete HTTP header string
  916. ############################################################
  917. def __get_request_headers(self, accept_header):
  918. return self.headers_template.format(accept=accept_header)
  919. ############################################################
  920. # End __format_request_headers
  921. ############################################################
  922. ############################################################
  923. # __curl_url
  924. # Dump HTTP response and headers. Throw exception if there
  925. # is an HTTP error.
  926. ############################################################
  927. def __curl_url(self, url, testType, out, err):
  928. output = None
  929. try:
  930. # Use -m 15 to make curl stop trying after 15sec.
  931. # Use -i to output response with headers.
  932. # Don't use -f so that the HTTP response code is ignored.
  933. # Use --stderr - to redirect stderr to stdout so we get
  934. # error output for sure in stdout.
  935. # Use -sS to hide progress bar, but show errors.
  936. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  937. # HTTP output may not end in a newline, so add that here.
  938. out.write( "\n\n" )
  939. out.flush()
  940. err.flush()
  941. # We need to get the respond body from the curl and return it.
  942. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  943. output = p.communicate()
  944. except:
  945. pass
  946. if output:
  947. # We have the response body - return it
  948. return output[0]
  949. ##############################################################
  950. # End __curl_url
  951. ##############################################################
  952. def requires_database(self):
  953. '''Returns True/False if this test requires a database'''
  954. return any(tobj.requires_db for (ttype,tobj) in self.runTests.iteritems())
  955. ############################################################
  956. # __begin_logging
  957. # Starts a thread to monitor the resource usage, to be synced with the client's time
  958. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  959. ############################################################
  960. def __begin_logging(self, test_name):
  961. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_name))
  962. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  963. --raw --socket --tcp --udp --unix --vm --disk-util \
  964. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  965. cmd = shlex.split(dstat_string)
  966. dev_null = open(os.devnull, "w")
  967. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  968. ##############################################################
  969. # End __begin_logging
  970. ##############################################################
  971. ##############################################################
  972. # Begin __end_logging
  973. # Stops the logger thread and blocks until shutdown is complete.
  974. ##############################################################
  975. def __end_logging(self):
  976. self.subprocess_handle.terminate()
  977. self.subprocess_handle.communicate()
  978. ##############################################################
  979. # End __end_logging
  980. ##############################################################
  981. ##############################################################
  982. # Begin __parse_stats
  983. # For each test type, process all the statistics, and return a multi-layered dictionary
  984. # that has a structure as follows:
  985. # (timestamp)
  986. # | (main header) - group that the stat is in
  987. # | | (sub header) - title of the stat
  988. # | | | (stat) - the stat itself, usually a floating point number
  989. ##############################################################
  990. def __parse_stats(self, test_type, start_time, end_time, interval):
  991. stats_dict = dict()
  992. stats_file = self.benchmarker.stats_file(self.name, test_type)
  993. with open(stats_file) as stats:
  994. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  995. pass
  996. stats_reader = csv.reader(stats)
  997. main_header = stats_reader.next()
  998. sub_header = stats_reader.next()
  999. time_row = sub_header.index("epoch")
  1000. int_counter = 0
  1001. for row in stats_reader:
  1002. time = float(row[time_row])
  1003. int_counter+=1
  1004. if time < start_time:
  1005. continue
  1006. elif time > end_time:
  1007. return stats_dict
  1008. if int_counter % interval != 0:
  1009. continue
  1010. row_dict = dict()
  1011. for nextheader in main_header:
  1012. if nextheader != "":
  1013. row_dict[nextheader] = dict()
  1014. header = ""
  1015. for item_num, column in enumerate(row):
  1016. if(len(main_header[item_num]) != 0):
  1017. header = main_header[item_num]
  1018. 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
  1019. stats_dict[time] = row_dict
  1020. return stats_dict
  1021. ##############################################################
  1022. # End __parse_stats
  1023. ##############################################################
  1024. def __getattr__(self, name):
  1025. """For backwards compatibility, we used to pass benchmarker
  1026. as the argument to the setup.py files"""
  1027. try:
  1028. x = getattr(self.benchmarker, name)
  1029. except AttributeError:
  1030. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  1031. print "This is probably a bug"
  1032. raise
  1033. return x
  1034. ##############################################################
  1035. # Begin __calculate_average_stats
  1036. # We have a large amount of raw data for the statistics that
  1037. # may be useful for the stats nerds, but most people care about
  1038. # a couple of numbers. For now, we're only going to supply:
  1039. # * Average CPU
  1040. # * Average Memory
  1041. # * Total network use
  1042. # * Total disk use
  1043. # More may be added in the future. If they are, please update
  1044. # the above list.
  1045. # Note: raw_stats is directly from the __parse_stats method.
  1046. # Recall that this consists of a dictionary of timestamps,
  1047. # each of which contain a dictionary of stat categories which
  1048. # contain a dictionary of stats
  1049. ##############################################################
  1050. def __calculate_average_stats(self, raw_stats):
  1051. raw_stat_collection = dict()
  1052. for timestamp, time_dict in raw_stats.items():
  1053. for main_header, sub_headers in time_dict.items():
  1054. item_to_append = None
  1055. if 'cpu' in main_header:
  1056. # We want to take the idl stat and subtract it from 100
  1057. # to get the time that the CPU is NOT idle.
  1058. item_to_append = sub_headers['idl'] - 100.0
  1059. elif main_header == 'memory usage':
  1060. item_to_append = sub_headers['used']
  1061. elif 'net' in main_header:
  1062. # Network stats have two parts - recieve and send. We'll use a tuple of
  1063. # style (recieve, send)
  1064. item_to_append = (sub_headers['recv'], sub_headers['send'])
  1065. elif 'dsk' or 'io' in main_header:
  1066. # Similar for network, except our tuple looks like (read, write)
  1067. item_to_append = (sub_headers['read'], sub_headers['writ'])
  1068. if item_to_append is not None:
  1069. if main_header not in raw_stat_collection:
  1070. raw_stat_collection[main_header] = list()
  1071. raw_stat_collection[main_header].append(item_to_append)
  1072. # Simple function to determine human readable size
  1073. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  1074. def sizeof_fmt(num):
  1075. # We'll assume that any number we get is convertable to a float, just in case
  1076. num = float(num)
  1077. for x in ['bytes','KB','MB','GB']:
  1078. if num < 1024.0 and num > -1024.0:
  1079. return "%3.1f%s" % (num, x)
  1080. num /= 1024.0
  1081. return "%3.1f%s" % (num, 'TB')
  1082. # Now we have our raw stats in a readable format - we need to format it for display
  1083. # We need a floating point sum, so the built in sum doesn't cut it
  1084. display_stat_collection = dict()
  1085. for header, values in raw_stat_collection.items():
  1086. display_stat = None
  1087. if 'cpu' in header:
  1088. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1089. elif main_header == 'memory usage':
  1090. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1091. elif 'net' in main_header:
  1092. receive, send = zip(*values) # unzip
  1093. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  1094. else: # if 'dsk' or 'io' in header:
  1095. read, write = zip(*values) # unzip
  1096. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  1097. display_stat_collection[header] = display_stat
  1098. return display_stat
  1099. ###########################################################################################
  1100. # End __calculate_average_stats
  1101. #########################################################################################
  1102. ##########################################################################################
  1103. # Constructor
  1104. ##########################################################################################
  1105. def __init__(self, name, directory, benchmarker, runTests, args):
  1106. self.name = name
  1107. self.directory = directory
  1108. self.benchmarker = benchmarker
  1109. self.runTests = runTests
  1110. self.fwroot = benchmarker.fwroot
  1111. # setup logging
  1112. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  1113. self.install_root="%s/%s" % (self.fwroot, "installs")
  1114. if benchmarker.install_strategy is 'pertest':
  1115. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1116. # Used in setup.py scripts for consistency with
  1117. # the bash environment variables
  1118. self.troot = self.directory
  1119. self.iroot = self.install_root
  1120. self.__dict__.update(args)
  1121. # ensure directory has __init__.py file so that we can use it as a Python package
  1122. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1123. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  1124. open(os.path.join(directory, "__init__.py"), 'w').close()
  1125. # Import the module (TODO - consider using sys.meta_path)
  1126. # Note: You can see the log output if you really want to, but it's a *ton*
  1127. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  1128. if dir_rel_to_fwroot != ".":
  1129. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1130. logging.log(0, "Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  1131. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1132. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1133. else:
  1134. logging.log(0, "Importing %s.%s", directory, self.setup_file)
  1135. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1136. ############################################################
  1137. # End __init__
  1138. ############################################################
  1139. ############################################################
  1140. # End FrameworkTest
  1141. ############################################################
  1142. ##########################################################################################
  1143. # Static methods
  1144. ##########################################################################################
  1145. ##############################################################
  1146. # parse_config(config, directory, benchmarker)
  1147. # parses a config file and returns a list of FrameworkTest
  1148. # objects based on that config file.
  1149. ##############################################################
  1150. def parse_config(config, directory, benchmarker):
  1151. tests = []
  1152. # The config object can specify multiple tests
  1153. # Loop over them and parse each into a FrameworkTest
  1154. for test in config['tests']:
  1155. for test_name, test_keys in test.iteritems():
  1156. # Prefix all test names with framework except 'default' test
  1157. if test_name == 'default':
  1158. test_name = config['framework']
  1159. else:
  1160. test_name = "%s-%s" % (config['framework'], test_name)
  1161. # Ensure FrameworkTest.framework is available
  1162. if not test_keys['framework']:
  1163. test_keys['framework'] = config['framework']
  1164. #if test_keys['framework'].lower() != config['framework'].lower():
  1165. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  1166. # (test_name, test_keys['framework'], config['framework']))
  1167. # Confirm required keys are present
  1168. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  1169. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  1170. if not all (key in test_keys for key in required):
  1171. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  1172. # Map test type to a parsed FrameworkTestType object
  1173. runTests = dict()
  1174. for type_name, type_obj in benchmarker.types.iteritems():
  1175. try:
  1176. runTests[type_name] = type_obj.copy().parse(test_keys)
  1177. except AttributeError as ae:
  1178. # This is quite common - most tests don't support all types
  1179. # Quitely log it and move on
  1180. logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  1181. pass
  1182. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  1183. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, test_keys))
  1184. return tests
  1185. ##############################################################
  1186. # End parse_config
  1187. ##############################################################