framework_test.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  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. # contains_type(type)
  655. # true if this test contains an implementation of the given
  656. # test type (json, db, etc.)
  657. ############################################################
  658. def contains_type(self, type):
  659. try:
  660. if type == self.JSON and self.json_url is not None:
  661. return True
  662. if type == self.DB and self.db_url is not None:
  663. return True
  664. if type == self.QUERY and self.query_url is not None:
  665. return True
  666. if type == self.FORTUNE and self.fortune_url is not None:
  667. return True
  668. if type == self.UPDATE and self.update_url is not None:
  669. return True
  670. if type == self.PLAINTEXT and self.plaintext_url is not None:
  671. return True
  672. except AttributeError:
  673. pass
  674. return False
  675. ############################################################
  676. # End stop
  677. ############################################################
  678. ############################################################
  679. # benchmark
  680. # Runs the benchmark for each type of test that it implements
  681. # JSON/DB/Query.
  682. ############################################################
  683. def benchmark(self, out, err):
  684. # JSON
  685. if self.runTests[self.JSON]:
  686. try:
  687. out.write("BENCHMARKING JSON ... ")
  688. out.flush()
  689. results = None
  690. output_file = self.benchmarker.output_file(self.name, self.JSON)
  691. if not os.path.exists(output_file):
  692. with open(output_file, 'w'):
  693. # Simply opening the file in write mode should create the empty file.
  694. pass
  695. if self.json_url_passed:
  696. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  697. self.__begin_logging(self.JSON)
  698. self.__run_benchmark(remote_script, output_file, err)
  699. self.__end_logging()
  700. results = self.__parse_test(self.JSON)
  701. print results
  702. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  703. out.write( "Complete\n" )
  704. out.flush()
  705. except AttributeError:
  706. pass
  707. # DB
  708. if self.runTests[self.DB]:
  709. try:
  710. out.write("BENCHMARKING DB ... ")
  711. out.flush()
  712. results = None
  713. output_file = self.benchmarker.output_file(self.name, self.DB)
  714. if not os.path.exists(output_file):
  715. with open(output_file, 'w'):
  716. # Simply opening the file in write mode should create the empty file.
  717. pass
  718. if self.db_url_passed:
  719. self.benchmarker.report_verify_results(self, self.DB, 'pass')
  720. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  721. self.__begin_logging(self.DB)
  722. self.__run_benchmark(remote_script, output_file, err)
  723. self.__end_logging()
  724. results = self.__parse_test(self.DB)
  725. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  726. out.write( "Complete\n" )
  727. except AttributeError:
  728. pass
  729. # Query
  730. if self.runTests[self.QUERY]:
  731. try:
  732. out.write("BENCHMARKING Query ... ")
  733. out.flush()
  734. results = None
  735. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  736. if not os.path.exists(output_file):
  737. with open(output_file, 'w'):
  738. # Simply opening the file in write mode should create the empty file.
  739. pass
  740. if self.query_url_passed:
  741. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  742. self.__begin_logging(self.QUERY)
  743. self.__run_benchmark(remote_script, output_file, err)
  744. self.__end_logging()
  745. results = self.__parse_test(self.QUERY)
  746. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  747. out.write( "Complete\n" )
  748. out.flush()
  749. except AttributeError:
  750. pass
  751. # fortune
  752. if self.runTests[self.FORTUNE]:
  753. try:
  754. out.write("BENCHMARKING Fortune ... ")
  755. out.flush()
  756. results = None
  757. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  758. if not os.path.exists(output_file):
  759. with open(output_file, 'w'):
  760. # Simply opening the file in write mode should create the empty file.
  761. pass
  762. if self.fortune_url_passed:
  763. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  764. self.__begin_logging(self.FORTUNE)
  765. self.__run_benchmark(remote_script, output_file, err)
  766. self.__end_logging()
  767. results = self.__parse_test(self.FORTUNE)
  768. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  769. out.write( "Complete\n" )
  770. out.flush()
  771. except AttributeError:
  772. pass
  773. # update
  774. if self.runTests[self.UPDATE]:
  775. try:
  776. out.write("BENCHMARKING Update ... ")
  777. out.flush()
  778. results = None
  779. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  780. if not os.path.exists(output_file):
  781. with open(output_file, 'w'):
  782. # Simply opening the file in write mode should create the empty file.
  783. pass
  784. if self.update_url_passed:
  785. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  786. self.__begin_logging(self.UPDATE)
  787. self.__run_benchmark(remote_script, output_file, err)
  788. self.__end_logging()
  789. results = self.__parse_test(self.UPDATE)
  790. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  791. out.write( "Complete\n" )
  792. out.flush()
  793. except AttributeError:
  794. pass
  795. # plaintext
  796. if self.runTests[self.PLAINTEXT]:
  797. try:
  798. out.write("BENCHMARKING Plaintext ... ")
  799. out.flush()
  800. results = None
  801. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  802. if not os.path.exists(output_file):
  803. with open(output_file, 'w'):
  804. # Simply opening the file in write mode should create the empty file.
  805. pass
  806. if self.plaintext_url_passed:
  807. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  808. self.__begin_logging(self.PLAINTEXT)
  809. self.__run_benchmark(remote_script, output_file, err)
  810. self.__end_logging()
  811. results = self.__parse_test(self.PLAINTEXT)
  812. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  813. out.write( "Complete\n" )
  814. out.flush()
  815. except AttributeError:
  816. traceback.print_exc()
  817. pass
  818. ############################################################
  819. # End benchmark
  820. ############################################################
  821. ############################################################
  822. # parse_all
  823. # Method meant to be run for a given timestamp
  824. ############################################################
  825. def parse_all(self):
  826. # JSON
  827. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  828. results = self.__parse_test(self.JSON)
  829. self.benchmarker.report_benchmark_results(framework=self, test=self.JSON, results=results['results'])
  830. # DB
  831. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  832. results = self.__parse_test(self.DB)
  833. self.benchmarker.report_benchmark_results(framework=self, test=self.DB, results=results['results'])
  834. # Query
  835. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  836. results = self.__parse_test(self.QUERY)
  837. self.benchmarker.report_benchmark_results(framework=self, test=self.QUERY, results=results['results'])
  838. # Fortune
  839. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  840. results = self.__parse_test(self.FORTUNE)
  841. self.benchmarker.report_benchmark_results(framework=self, test=self.FORTUNE, results=results['results'])
  842. # Update
  843. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  844. results = self.__parse_test(self.UPDATE)
  845. self.benchmarker.report_benchmark_results(framework=self, test=self.UPDATE, results=results['results'])
  846. # Plaintext
  847. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  848. results = self.__parse_test(self.PLAINTEXT)
  849. self.benchmarker.report_benchmark_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  850. ############################################################
  851. # End parse_all
  852. ############################################################
  853. ############################################################
  854. # __parse_test(test_type)
  855. ############################################################
  856. def __parse_test(self, test_type):
  857. try:
  858. results = dict()
  859. results['results'] = []
  860. stats = []
  861. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  862. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  863. is_warmup = True
  864. rawData = None
  865. for line in raw_data:
  866. if "Queries:" in line or "Concurrency:" in line:
  867. is_warmup = False
  868. rawData = None
  869. continue
  870. if "Warmup" in line or "Primer" in line:
  871. is_warmup = True
  872. continue
  873. if not is_warmup:
  874. if rawData == None:
  875. rawData = dict()
  876. results['results'].append(rawData)
  877. #if "Requests/sec:" in line:
  878. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  879. # rawData['reportedResults'] = m.group(1)
  880. # search for weighttp data such as succeeded and failed.
  881. if "Latency" in line:
  882. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  883. if len(m) == 4:
  884. rawData['latencyAvg'] = m[0]
  885. rawData['latencyStdev'] = m[1]
  886. rawData['latencyMax'] = m[2]
  887. # rawData['latencyStdevPercent'] = m[3]
  888. #if "Req/Sec" in line:
  889. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  890. # if len(m) == 4:
  891. # rawData['requestsAvg'] = m[0]
  892. # rawData['requestsStdev'] = m[1]
  893. # rawData['requestsMax'] = m[2]
  894. # rawData['requestsStdevPercent'] = m[3]
  895. #if "requests in" in line:
  896. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  897. # if m != None:
  898. # # parse out the raw time, which may be in minutes or seconds
  899. # raw_time = m.group(1)
  900. # if "ms" in raw_time:
  901. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  902. # elif "s" in raw_time:
  903. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  904. # elif "m" in raw_time:
  905. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  906. # elif "h" in raw_time:
  907. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  908. if "requests in" in line:
  909. m = re.search("([0-9]+) requests in", line)
  910. if m != None:
  911. rawData['totalRequests'] = int(m.group(1))
  912. if "Socket errors" in line:
  913. if "connect" in line:
  914. m = re.search("connect ([0-9]+)", line)
  915. rawData['connect'] = int(m.group(1))
  916. if "read" in line:
  917. m = re.search("read ([0-9]+)", line)
  918. rawData['read'] = int(m.group(1))
  919. if "write" in line:
  920. m = re.search("write ([0-9]+)", line)
  921. rawData['write'] = int(m.group(1))
  922. if "timeout" in line:
  923. m = re.search("timeout ([0-9]+)", line)
  924. rawData['timeout'] = int(m.group(1))
  925. if "Non-2xx" in line:
  926. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  927. if m != None:
  928. rawData['5xx'] = int(m.group(1))
  929. if "STARTTIME" in line:
  930. m = re.search("[0-9]+", line)
  931. rawData["startTime"] = int(m.group(0))
  932. if "ENDTIME" in line:
  933. m = re.search("[0-9]+", line)
  934. rawData["endTime"] = int(m.group(0))
  935. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  936. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  937. stats.append(test_stats)
  938. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  939. json.dump(stats, stats_file)
  940. return results
  941. except IOError:
  942. return None
  943. ############################################################
  944. # End benchmark
  945. ############################################################
  946. ##########################################################################################
  947. # Private Methods
  948. ##########################################################################################
  949. ############################################################
  950. # __run_benchmark(script, output_file)
  951. # Runs a single benchmark using the script which is a bash
  952. # template that uses weighttp to run the test. All the results
  953. # outputed to the output_file.
  954. ############################################################
  955. def __run_benchmark(self, script, output_file, err):
  956. with open(output_file, 'w') as raw_file:
  957. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  958. p.communicate(script)
  959. err.flush()
  960. ############################################################
  961. # End __run_benchmark
  962. ############################################################
  963. ############################################################
  964. # __generate_concurrency_script(url, port)
  965. # Generates the string containing the bash script that will
  966. # be run on the client to benchmark a single test. This
  967. # specifically works for the variable concurrency tests (JSON
  968. # and DB)
  969. ############################################################
  970. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  971. if len(intervals) == 0:
  972. intervals = self.benchmarker.concurrency_levels
  973. headers = self.__get_request_headers(accept_header)
  974. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  975. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  976. interval=" ".join("{}".format(item) for item in intervals),
  977. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  978. pipeline=pipeline)
  979. ############################################################
  980. # End __generate_concurrency_script
  981. ############################################################
  982. ############################################################
  983. # __generate_query_script(url, port)
  984. # Generates the string containing the bash script that will
  985. # be run on the client to benchmark a single test. This
  986. # specifically works for the variable query tests (Query)
  987. ############################################################
  988. def __generate_query_script(self, url, port, accept_header):
  989. headers = self.__get_request_headers(accept_header)
  990. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  991. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  992. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  993. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  994. ############################################################
  995. # End __generate_query_script
  996. ############################################################
  997. ############################################################
  998. # __get_request_headers(accept_header)
  999. # Generates the complete HTTP header string
  1000. ############################################################
  1001. def __get_request_headers(self, accept_header):
  1002. return self.headers_template.format(accept=accept_header)
  1003. ############################################################
  1004. # End __format_request_headers
  1005. ############################################################
  1006. ############################################################
  1007. # __curl_url
  1008. # Dump HTTP response and headers. Throw exception if there
  1009. # is an HTTP error.
  1010. ############################################################
  1011. def __curl_url(self, url, testType, out, err):
  1012. output = None
  1013. try:
  1014. # Use -m 15 to make curl stop trying after 15sec.
  1015. # Use -i to output response with headers.
  1016. # Don't use -f so that the HTTP response code is ignored.
  1017. # Use --stderr - to redirect stderr to stdout so we get
  1018. # error output for sure in stdout.
  1019. # Use -sS to hide progress bar, but show errors.
  1020. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  1021. # HTTP output may not end in a newline, so add that here.
  1022. out.write( "\n\n" )
  1023. out.flush()
  1024. err.flush()
  1025. # We need to get the respond body from the curl and return it.
  1026. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  1027. output = p.communicate()
  1028. except:
  1029. pass
  1030. if output:
  1031. # We have the response body - return it
  1032. return output[0]
  1033. ##############################################################
  1034. # End __curl_url
  1035. ##############################################################
  1036. def requires_database(self):
  1037. """Returns True/False if this test requires a database"""
  1038. return (self.contains_type(self.FORTUNE) or
  1039. self.contains_type(self.DB) or
  1040. self.contains_type(self.QUERY) or
  1041. self.contains_type(self.UPDATE))
  1042. ############################################################
  1043. # __begin_logging
  1044. # Starts a thread to monitor the resource usage, to be synced with the client's time
  1045. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  1046. ############################################################
  1047. def __begin_logging(self, test_name):
  1048. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_name))
  1049. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  1050. --raw --socket --tcp --udp --unix --vm --disk-util \
  1051. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  1052. cmd = shlex.split(dstat_string)
  1053. dev_null = open(os.devnull, "w")
  1054. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  1055. ##############################################################
  1056. # End __begin_logging
  1057. ##############################################################
  1058. ##############################################################
  1059. # Begin __end_logging
  1060. # Stops the logger thread and blocks until shutdown is complete.
  1061. ##############################################################
  1062. def __end_logging(self):
  1063. self.subprocess_handle.terminate()
  1064. self.subprocess_handle.communicate()
  1065. ##############################################################
  1066. # End __end_logging
  1067. ##############################################################
  1068. ##############################################################
  1069. # Begin __parse_stats
  1070. # For each test type, process all the statistics, and return a multi-layered dictionary
  1071. # that has a structure as follows:
  1072. # (timestamp)
  1073. # | (main header) - group that the stat is in
  1074. # | | (sub header) - title of the stat
  1075. # | | | (stat) - the stat itself, usually a floating point number
  1076. ##############################################################
  1077. def __parse_stats(self, test_type, start_time, end_time, interval):
  1078. stats_dict = dict()
  1079. stats_file = self.benchmarker.stats_file(self.name, test_type)
  1080. with open(stats_file) as stats:
  1081. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  1082. pass
  1083. stats_reader = csv.reader(stats)
  1084. main_header = stats_reader.next()
  1085. sub_header = stats_reader.next()
  1086. time_row = sub_header.index("epoch")
  1087. int_counter = 0
  1088. for row in stats_reader:
  1089. time = float(row[time_row])
  1090. int_counter+=1
  1091. if time < start_time:
  1092. continue
  1093. elif time > end_time:
  1094. return stats_dict
  1095. if int_counter % interval != 0:
  1096. continue
  1097. row_dict = dict()
  1098. for nextheader in main_header:
  1099. if nextheader != "":
  1100. row_dict[nextheader] = dict()
  1101. header = ""
  1102. for item_num, column in enumerate(row):
  1103. if(len(main_header[item_num]) != 0):
  1104. header = main_header[item_num]
  1105. 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
  1106. stats_dict[time] = row_dict
  1107. return stats_dict
  1108. ##############################################################
  1109. # End __parse_stats
  1110. ##############################################################
  1111. def __getattr__(self, name):
  1112. """For backwards compatibility, we used to pass benchmarker
  1113. as the argument to the setup.py files"""
  1114. try:
  1115. x = getattr(self.benchmarker, name)
  1116. except AttributeError:
  1117. print "AttributeError: %s not a member of FrameworkTest or Benchmarker" % name
  1118. print "This is probably a bug"
  1119. raise
  1120. return x
  1121. ##############################################################
  1122. # Begin __calculate_average_stats
  1123. # We have a large amount of raw data for the statistics that
  1124. # may be useful for the stats nerds, but most people care about
  1125. # a couple of numbers. For now, we're only going to supply:
  1126. # * Average CPU
  1127. # * Average Memory
  1128. # * Total network use
  1129. # * Total disk use
  1130. # More may be added in the future. If they are, please update
  1131. # the above list.
  1132. # Note: raw_stats is directly from the __parse_stats method.
  1133. # Recall that this consists of a dictionary of timestamps,
  1134. # each of which contain a dictionary of stat categories which
  1135. # contain a dictionary of stats
  1136. ##############################################################
  1137. def __calculate_average_stats(self, raw_stats):
  1138. raw_stat_collection = dict()
  1139. for timestamp, time_dict in raw_stats.items():
  1140. for main_header, sub_headers in time_dict.items():
  1141. item_to_append = None
  1142. if 'cpu' in main_header:
  1143. # We want to take the idl stat and subtract it from 100
  1144. # to get the time that the CPU is NOT idle.
  1145. item_to_append = sub_headers['idl'] - 100.0
  1146. elif main_header == 'memory usage':
  1147. item_to_append = sub_headers['used']
  1148. elif 'net' in main_header:
  1149. # Network stats have two parts - recieve and send. We'll use a tuple of
  1150. # style (recieve, send)
  1151. item_to_append = (sub_headers['recv'], sub_headers['send'])
  1152. elif 'dsk' or 'io' in main_header:
  1153. # Similar for network, except our tuple looks like (read, write)
  1154. item_to_append = (sub_headers['read'], sub_headers['writ'])
  1155. if item_to_append is not None:
  1156. if main_header not in raw_stat_collection:
  1157. raw_stat_collection[main_header] = list()
  1158. raw_stat_collection[main_header].append(item_to_append)
  1159. # Simple function to determine human readable size
  1160. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  1161. def sizeof_fmt(num):
  1162. # We'll assume that any number we get is convertable to a float, just in case
  1163. num = float(num)
  1164. for x in ['bytes','KB','MB','GB']:
  1165. if num < 1024.0 and num > -1024.0:
  1166. return "%3.1f%s" % (num, x)
  1167. num /= 1024.0
  1168. return "%3.1f%s" % (num, 'TB')
  1169. # Now we have our raw stats in a readable format - we need to format it for display
  1170. # We need a floating point sum, so the built in sum doesn't cut it
  1171. display_stat_collection = dict()
  1172. for header, values in raw_stat_collection.items():
  1173. display_stat = None
  1174. if 'cpu' in header:
  1175. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1176. elif main_header == 'memory usage':
  1177. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1178. elif 'net' in main_header:
  1179. receive, send = zip(*values) # unzip
  1180. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  1181. else: # if 'dsk' or 'io' in header:
  1182. read, write = zip(*values) # unzip
  1183. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  1184. display_stat_collection[header] = display_stat
  1185. return display_stat
  1186. ###########################################################################################
  1187. # End __calculate_average_stats
  1188. #########################################################################################
  1189. ##########################################################################################
  1190. # Constructor
  1191. ##########################################################################################
  1192. def __init__(self, name, directory, benchmarker, runTests, args):
  1193. self.name = name
  1194. self.directory = directory
  1195. self.benchmarker = benchmarker
  1196. self.runTests = runTests
  1197. self.fwroot = benchmarker.fwroot
  1198. # setup logging
  1199. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  1200. self.install_root="%s/%s" % (self.fwroot, "installs")
  1201. if benchmarker.install_strategy is 'pertest':
  1202. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1203. # Used in setup.py scripts for consistency with
  1204. # the bash environment variables
  1205. self.troot = self.directory
  1206. self.iroot = self.install_root
  1207. self.__dict__.update(args)
  1208. # ensure directory has __init__.py file so that we can use it as a Python package
  1209. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1210. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  1211. open(os.path.join(directory, "__init__.py"), 'w').close()
  1212. # Import the module (TODO - consider using sys.meta_path)
  1213. # Note: You can see the log output if you really want to, but it's a *ton*
  1214. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  1215. if dir_rel_to_fwroot != ".":
  1216. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1217. logging.log(0, "Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  1218. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1219. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1220. else:
  1221. logging.log(0, "Importing %s.%s", directory, self.setup_file)
  1222. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1223. ############################################################
  1224. # End __init__
  1225. ############################################################
  1226. ############################################################
  1227. # End FrameworkTest
  1228. ############################################################
  1229. ##########################################################################################
  1230. # Static methods
  1231. ##########################################################################################
  1232. ##############################################################
  1233. # parse_config(config, directory, benchmarker)
  1234. # parses a config file and returns a list of FrameworkTest
  1235. # objects based on that config file.
  1236. ##############################################################
  1237. def parse_config(config, directory, benchmarker):
  1238. tests = []
  1239. # The config object can specify multiple tests
  1240. # Loop over them and parse each into a FrameworkTest
  1241. for test in config['tests']:
  1242. for test_name, test_keys in test.iteritems():
  1243. # Prefix all test names with framework except 'default' test
  1244. if test_name == 'default':
  1245. test_name = config['framework']
  1246. else:
  1247. test_name = "%s-%s" % (config['framework'], test_name)
  1248. # Ensure FrameworkTest.framework is available
  1249. if not test_keys['framework']:
  1250. test_keys['framework'] = config['framework']
  1251. #if test_keys['framework'].lower() != config['framework'].lower():
  1252. # print Exception("benchmark_config for test %s is invalid - test framework '%s' must match benchmark_config framework '%s'" %
  1253. # (test_name, test_keys['framework'], config['framework']))
  1254. # Confirm required keys are present
  1255. # TODO have a TechEmpower person confirm this list - I don't know what the website requires....
  1256. required = ['language','webserver','classification','database','approach','orm','framework','os','database_os']
  1257. if not all (key in test_keys for key in required):
  1258. raise Exception("benchmark_config for test %s is invalid - missing required keys" % test_name)
  1259. # Map test type to a parsed FrameworkTestType object
  1260. runTests = dict()
  1261. for type_name, type_obj in benchmarker.types.iteritems():
  1262. try:
  1263. runTests[type_name] = type_obj.copy().parse(test_keys)
  1264. except AttributeError as ae:
  1265. # This is quite common - most tests don't support all types
  1266. # Quitely log it and move on
  1267. logging.debug("Missing arguments for test type %s for framework test %s", type_name, test_name)
  1268. pass
  1269. # By passing the entire set of keys, each FrameworkTest will have a member for each key
  1270. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, test_keys))
  1271. return tests
  1272. ##############################################################
  1273. # End parse_config
  1274. ##############################################################