framework_test.py 56 KB

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