framework_test.py 55 KB

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