framework_test.py 57 KB

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