framework_test.py 58 KB

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