framework_test.py 58 KB

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