framework_test.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  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. self.troot = self.directory
  412. self.iroot = self.install_root
  413. setup_util.replace_environ(config=profile,
  414. command='export TROOT=%s && export IROOT=%s' %
  415. (self.directory, self.install_root))
  416. # Run the module start (inside parent of TROOT)
  417. # - we use the parent as a historical accident - a lot of tests
  418. # use subprocess's cwd argument already
  419. previousDir = os.getcwd()
  420. os.chdir(os.path.dirname(self.troot))
  421. logging.info("Running setup module start (cwd=%s)", os.path.dirname(self.troot))
  422. retcode = self.setup_module.start(self, out, err)
  423. os.chdir(previousDir)
  424. return retcode
  425. ############################################################
  426. # End start
  427. ############################################################
  428. ############################################################
  429. # stop(benchmarker)
  430. # Stops the test using it's setup file
  431. ############################################################
  432. def stop(self, out, err):
  433. # Load profile for this installation
  434. profile="%s/bash_profile.sh" % self.directory
  435. if not os.path.exists(profile):
  436. logging.warning("Directory %s does not have a bash_profile.sh" % self.directory)
  437. profile="$FWROOT/config/benchmark_profile"
  438. setup_util.replace_environ(config=profile,
  439. command='export TROOT=%s && export IROOT=%s' %
  440. (self.directory, self.install_root))
  441. # Run the module stop (inside parent of TROOT)
  442. # - we use the parent as a historical accident - a lot of tests
  443. # use subprocess's cwd argument already
  444. previousDir = os.getcwd()
  445. os.chdir(os.path.dirname(self.troot))
  446. logging.info("Running setup module stop (cwd=%s)", os.path.dirname(self.troot))
  447. retcode = self.setup_module.stop(out, err)
  448. os.chdir(previousDir)
  449. return retcode
  450. ############################################################
  451. # End stop
  452. ############################################################
  453. ############################################################
  454. # verify_urls
  455. # Verifys each of the URLs for this test. THis will sinply
  456. # curl the URL and check for it's return status.
  457. # For each url, a flag will be set on this object for whether
  458. # or not it passed
  459. # Returns True if all verifications succeeded
  460. ############################################################
  461. def verify_urls(self, out, err):
  462. result = True
  463. # JSON
  464. if self.runTests[self.JSON]:
  465. out.write(header("VERIFYING JSON (%s)" % self.json_url))
  466. out.flush()
  467. url = self.benchmarker.generate_url(self.json_url, self.port)
  468. output = self.__curl_url(url, self.JSON, out, err)
  469. out.write("VALIDATING JSON ... ")
  470. ret_tuple = self.validateJson(output, out, err)
  471. if ret_tuple[0]:
  472. self.json_url_passed = True
  473. out.write("PASS\n\n")
  474. else:
  475. self.json_url_passed = False
  476. out.write("\nFAIL" + ret_tuple[1] + "\n\n")
  477. result = False
  478. out.flush()
  479. # DB
  480. if self.runTests[self.DB]:
  481. out.write(header("VERIFYING DB (%s)" % self.db_url))
  482. out.flush()
  483. url = self.benchmarker.generate_url(self.db_url, self.port)
  484. output = self.__curl_url(url, self.DB, out, err)
  485. validate_ret_tuple = self.validateDb(output, out, err)
  486. validate_strict_ret_tuple = self.validateDbStrict(output, out, err)
  487. if validate_ret_tuple[0]:
  488. self.db_url_passed = True
  489. else:
  490. self.db_url_passed = False
  491. if validate_strict_ret_tuple:
  492. self.db_url_warn = False
  493. else:
  494. self.db_url_warn = True
  495. out.write("VALIDATING DB ... ")
  496. if self.db_url_passed:
  497. out.write("PASS")
  498. if self.db_url_warn:
  499. out.write(" (with warnings) " + validate_strict_ret_tuple[1])
  500. out.write("\n\n")
  501. else:
  502. out.write("\nFAIL" + validate_ret_tuple[1])
  503. result = False
  504. out.flush()
  505. # Query
  506. if self.runTests[self.QUERY]:
  507. out.write(header("VERIFYING QUERY (%s)" % self.query_url+"2"))
  508. out.flush()
  509. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  510. output = self.__curl_url(url, self.QUERY, out, err)
  511. ret_tuple = self.validateQuery(output, out, err)
  512. if ret_tuple[0]:
  513. self.query_url_passed = True
  514. out.write(self.query_url + "2 - PASS\n\n")
  515. else:
  516. self.query_url_passed = False
  517. out.write(self.query_url + "2 - FAIL " + ret_tuple[1] + "\n\n")
  518. out.write("-----------------------------------------------------\n\n")
  519. out.flush()
  520. self.query_url_warn = False
  521. url2 = self.benchmarker.generate_url(self.query_url + "0", self.port)
  522. output2 = self.__curl_url(url2, self.QUERY, out, err)
  523. ret_tuple = self.validateQueryOneOrLess(output2, out, err)
  524. if not ret_tuple[0]:
  525. self.query_url_warn = True
  526. out.write(self.query_url + "0 - WARNING " + ret_tuple[1] + "\n\n")
  527. else:
  528. out.write(self.query_url + "0 - PASS\n\n")
  529. out.write("-----------------------------------------------------\n\n")
  530. out.flush()
  531. url3 = self.benchmarker.generate_url(self.query_url + "foo", self.port)
  532. output3 = self.__curl_url(url3, self.QUERY, out, err)
  533. ret_tuple = self.validateQueryOneOrLess(output3, out, err)
  534. if not ret_tuple[0]:
  535. self.query_url_warn = True
  536. out.write(self.query_url + "foo - WARNING " + ret_tuple[1] + "\n\n")
  537. else:
  538. out.write(self.query_url + "foo - PASS\n\n")
  539. out.write("-----------------------------------------------------\n\n")
  540. out.flush()
  541. url4 = self.benchmarker.generate_url(self.query_url + "501", self.port)
  542. output4 = self.__curl_url(url4, self.QUERY, out, err)
  543. ret_tuple = self.validateQueryFiveHundredOrMore(output4, out, err)
  544. if not ret_tuple[0]:
  545. self.query_url_warn = True
  546. out.write(self.query_url + "501 - WARNING " + ret_tuple[1] + "\n\n")
  547. else:
  548. out.write(self.query_url + "501 - PASS\n\n")
  549. out.write("-----------------------------------------------------\n\n\n")
  550. out.flush()
  551. out.write("VALIDATING QUERY ... ")
  552. if self.query_url_passed:
  553. out.write("PASS")
  554. if self.query_url_warn:
  555. out.write(" (with warnings)")
  556. out.write("\n\n")
  557. else:
  558. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  559. result = False
  560. out.flush()
  561. # Fortune
  562. if self.runTests[self.FORTUNE]:
  563. out.write(header("VERIFYING FORTUNE (%s)" % self.fortune_url))
  564. out.flush()
  565. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  566. output = self.__curl_url(url, self.FORTUNE, out, err)
  567. out.write("VALIDATING FORTUNE ... ")
  568. if self.validateFortune(output, out, err):
  569. self.fortune_url_passed = True
  570. out.write("PASS\n\n")
  571. else:
  572. self.fortune_url_passed = False
  573. out.write("\nFAIL\n\n")
  574. result = False
  575. out.flush()
  576. # Update
  577. if self.runTests[self.UPDATE]:
  578. out.write(header("VERIFYING UPDATE (%s)" % self.update_url))
  579. out.flush()
  580. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  581. output = self.__curl_url(url, self.UPDATE, out, err)
  582. out.write("VALIDATING UPDATE ... ")
  583. ret_tuple = self.validateUpdate(output, out, err)
  584. if ret_tuple[0]:
  585. self.update_url_passed = True
  586. out.write("PASS\n\n")
  587. else:
  588. self.update_url_passed = False
  589. out.write("\nFAIL " + ret_tuple[1] + "\n\n")
  590. result = False
  591. out.flush()
  592. # plaintext
  593. if self.runTests[self.PLAINTEXT]:
  594. out.write(header("VERIFYING PLAINTEXT (%s)" % self.plaintext_url))
  595. out.flush()
  596. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  597. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  598. out.write("VALIDATING PLAINTEXT ... ")
  599. ret_tuple = self.validatePlaintext(output, out, err)
  600. if ret_tuple[0]:
  601. self.plaintext_url_passed = True
  602. out.write("PASS\n\n")
  603. else:
  604. self.plaintext_url_passed = False
  605. out.write("\nFAIL\n\n" + ret_tuple[1] + "\n\n")
  606. result = False
  607. out.flush()
  608. return result
  609. ############################################################
  610. # End verify_urls
  611. ############################################################
  612. ############################################################
  613. # contains_type(type)
  614. # true if this test contains an implementation of the given
  615. # test type (json, db, etc.)
  616. ############################################################
  617. def contains_type(self, type):
  618. try:
  619. if type == self.JSON and self.json_url is not None:
  620. return True
  621. if type == self.DB and self.db_url is not None:
  622. return True
  623. if type == self.QUERY and self.query_url is not None:
  624. return True
  625. if type == self.FORTUNE and self.fortune_url is not None:
  626. return True
  627. if type == self.UPDATE and self.update_url is not None:
  628. return True
  629. if type == self.PLAINTEXT and self.plaintext_url is not None:
  630. return True
  631. except AttributeError:
  632. pass
  633. return False
  634. ############################################################
  635. # End stop
  636. ############################################################
  637. ############################################################
  638. # benchmark
  639. # Runs the benchmark for each type of test that it implements
  640. # JSON/DB/Query.
  641. ############################################################
  642. def benchmark(self, out, err):
  643. # JSON
  644. if self.runTests[self.JSON]:
  645. try:
  646. out.write("BENCHMARKING JSON ... ")
  647. out.flush()
  648. results = None
  649. output_file = self.benchmarker.output_file(self.name, self.JSON)
  650. if not os.path.exists(output_file):
  651. with open(output_file, 'w'):
  652. # Simply opening the file in write mode should create the empty file.
  653. pass
  654. if self.json_url_passed:
  655. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  656. self.__begin_logging(self.JSON)
  657. self.__run_benchmark(remote_script, output_file, err)
  658. self.__end_logging()
  659. results = self.__parse_test(self.JSON)
  660. print results
  661. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  662. out.write( "Complete\n" )
  663. out.flush()
  664. except AttributeError:
  665. pass
  666. # DB
  667. if self.runTests[self.DB]:
  668. try:
  669. out.write("BENCHMARKING DB ... ")
  670. out.flush()
  671. results = None
  672. output_file = self.benchmarker.output_file(self.name, self.DB)
  673. warning_file = self.benchmarker.warning_file(self.name, self.DB)
  674. if not os.path.exists(output_file):
  675. with open(output_file, 'w'):
  676. # Simply opening the file in write mode should create the empty file.
  677. pass
  678. if self.db_url_warn:
  679. with open(warning_file, 'w'):
  680. pass
  681. if self.db_url_passed:
  682. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  683. self.__begin_logging(self.DB)
  684. self.__run_benchmark(remote_script, output_file, err)
  685. self.__end_logging()
  686. results = self.__parse_test(self.DB)
  687. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  688. out.write( "Complete\n" )
  689. except AttributeError:
  690. pass
  691. # Query
  692. if self.runTests[self.QUERY]:
  693. try:
  694. out.write("BENCHMARKING Query ... ")
  695. out.flush()
  696. results = None
  697. output_file = self.benchmarker.output_file(self.name, self.QUERY)
  698. warning_file = self.benchmarker.warning_file(self.name, self.QUERY)
  699. if not os.path.exists(output_file):
  700. with open(output_file, 'w'):
  701. # Simply opening the file in write mode should create the empty file.
  702. pass
  703. if self.query_url_warn:
  704. with open(warning_file, 'w'):
  705. pass
  706. if self.query_url_passed:
  707. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  708. self.__begin_logging(self.QUERY)
  709. self.__run_benchmark(remote_script, output_file, err)
  710. self.__end_logging()
  711. results = self.__parse_test(self.QUERY)
  712. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  713. out.write( "Complete\n" )
  714. out.flush()
  715. except AttributeError:
  716. pass
  717. # fortune
  718. if self.runTests[self.FORTUNE]:
  719. try:
  720. out.write("BENCHMARKING Fortune ... ")
  721. out.flush()
  722. results = None
  723. output_file = self.benchmarker.output_file(self.name, self.FORTUNE)
  724. if not os.path.exists(output_file):
  725. with open(output_file, 'w'):
  726. # Simply opening the file in write mode should create the empty file.
  727. pass
  728. if self.fortune_url_passed:
  729. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  730. self.__begin_logging(self.FORTUNE)
  731. self.__run_benchmark(remote_script, output_file, err)
  732. self.__end_logging()
  733. results = self.__parse_test(self.FORTUNE)
  734. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  735. out.write( "Complete\n" )
  736. out.flush()
  737. except AttributeError:
  738. pass
  739. # update
  740. if self.runTests[self.UPDATE]:
  741. try:
  742. out.write("BENCHMARKING Update ... ")
  743. out.flush()
  744. results = None
  745. output_file = self.benchmarker.output_file(self.name, self.UPDATE)
  746. if not os.path.exists(output_file):
  747. with open(output_file, 'w'):
  748. # Simply opening the file in write mode should create the empty file.
  749. pass
  750. if self.update_url_passed:
  751. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  752. self.__begin_logging(self.UPDATE)
  753. self.__run_benchmark(remote_script, output_file, err)
  754. self.__end_logging()
  755. results = self.__parse_test(self.UPDATE)
  756. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  757. out.write( "Complete\n" )
  758. out.flush()
  759. except AttributeError:
  760. pass
  761. # plaintext
  762. if self.runTests[self.PLAINTEXT]:
  763. try:
  764. out.write("BENCHMARKING Plaintext ... ")
  765. out.flush()
  766. results = None
  767. output_file = self.benchmarker.output_file(self.name, self.PLAINTEXT)
  768. if not os.path.exists(output_file):
  769. with open(output_file, 'w'):
  770. # Simply opening the file in write mode should create the empty file.
  771. pass
  772. if self.plaintext_url_passed:
  773. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk", intervals=[256,1024,4096,16384], pipeline="16")
  774. self.__begin_logging(self.PLAINTEXT)
  775. self.__run_benchmark(remote_script, output_file, err)
  776. self.__end_logging()
  777. results = self.__parse_test(self.PLAINTEXT)
  778. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  779. out.write( "Complete\n" )
  780. out.flush()
  781. except AttributeError:
  782. traceback.print_exc()
  783. pass
  784. ############################################################
  785. # End benchmark
  786. ############################################################
  787. ############################################################
  788. # parse_all
  789. # Method meant to be run for a given timestamp
  790. ############################################################
  791. def parse_all(self):
  792. # JSON
  793. if os.path.exists(self.benchmarker.get_output_file(self.name, self.JSON)):
  794. results = self.__parse_test(self.JSON)
  795. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  796. # DB
  797. if os.path.exists(self.benchmarker.get_output_file(self.name, self.DB)):
  798. results = self.__parse_test(self.DB)
  799. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  800. # Query
  801. if os.path.exists(self.benchmarker.get_output_file(self.name, self.QUERY)):
  802. results = self.__parse_test(self.QUERY)
  803. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  804. # Fortune
  805. if os.path.exists(self.benchmarker.get_output_file(self.name, self.FORTUNE)):
  806. results = self.__parse_test(self.FORTUNE)
  807. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  808. # Update
  809. if os.path.exists(self.benchmarker.get_output_file(self.name, self.UPDATE)):
  810. results = self.__parse_test(self.UPDATE)
  811. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  812. # Plaintext
  813. if os.path.exists(self.benchmarker.get_output_file(self.name, self.PLAINTEXT)):
  814. results = self.__parse_test(self.PLAINTEXT)
  815. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  816. ############################################################
  817. # End parse_all
  818. ############################################################
  819. ############################################################
  820. # __parse_test(test_type)
  821. ############################################################
  822. def __parse_test(self, test_type):
  823. try:
  824. results = dict()
  825. results['results'] = []
  826. stats = []
  827. if os.path.exists(self.benchmarker.get_output_file(self.name, test_type)):
  828. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  829. is_warmup = True
  830. rawData = None
  831. for line in raw_data:
  832. if "Queries:" in line or "Concurrency:" in line:
  833. is_warmup = False
  834. rawData = None
  835. continue
  836. if "Warmup" in line or "Primer" in line:
  837. is_warmup = True
  838. continue
  839. if not is_warmup:
  840. if rawData == None:
  841. rawData = dict()
  842. results['results'].append(rawData)
  843. #if "Requests/sec:" in line:
  844. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  845. # rawData['reportedResults'] = m.group(1)
  846. # search for weighttp data such as succeeded and failed.
  847. if "Latency" in line:
  848. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  849. if len(m) == 4:
  850. rawData['latencyAvg'] = m[0]
  851. rawData['latencyStdev'] = m[1]
  852. rawData['latencyMax'] = m[2]
  853. # rawData['latencyStdevPercent'] = m[3]
  854. #if "Req/Sec" in line:
  855. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  856. # if len(m) == 4:
  857. # rawData['requestsAvg'] = m[0]
  858. # rawData['requestsStdev'] = m[1]
  859. # rawData['requestsMax'] = m[2]
  860. # rawData['requestsStdevPercent'] = m[3]
  861. #if "requests in" in line:
  862. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  863. # if m != None:
  864. # # parse out the raw time, which may be in minutes or seconds
  865. # raw_time = m.group(1)
  866. # if "ms" in raw_time:
  867. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  868. # elif "s" in raw_time:
  869. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  870. # elif "m" in raw_time:
  871. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  872. # elif "h" in raw_time:
  873. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  874. if "requests in" in line:
  875. m = re.search("([0-9]+) requests in", line)
  876. if m != None:
  877. rawData['totalRequests'] = int(m.group(1))
  878. if "Socket errors" in line:
  879. if "connect" in line:
  880. m = re.search("connect ([0-9]+)", line)
  881. rawData['connect'] = int(m.group(1))
  882. if "read" in line:
  883. m = re.search("read ([0-9]+)", line)
  884. rawData['read'] = int(m.group(1))
  885. if "write" in line:
  886. m = re.search("write ([0-9]+)", line)
  887. rawData['write'] = int(m.group(1))
  888. if "timeout" in line:
  889. m = re.search("timeout ([0-9]+)", line)
  890. rawData['timeout'] = int(m.group(1))
  891. if "Non-2xx" in line:
  892. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  893. if m != None:
  894. rawData['5xx'] = int(m.group(1))
  895. if "STARTTIME" in line:
  896. m = re.search("[0-9]+", line)
  897. rawData["startTime"] = int(m.group(0))
  898. if "ENDTIME" in line:
  899. m = re.search("[0-9]+", line)
  900. rawData["endTime"] = int(m.group(0))
  901. test_stats = self.__parse_stats(test_type, rawData["startTime"], rawData["endTime"], 1)
  902. # rawData["averageStats"] = self.__calculate_average_stats(test_stats)
  903. stats.append(test_stats)
  904. with open(self.benchmarker.stats_file(self.name, test_type) + ".json", "w") as stats_file:
  905. json.dump(stats, stats_file)
  906. return results
  907. except IOError:
  908. return None
  909. ############################################################
  910. # End benchmark
  911. ############################################################
  912. ##########################################################################################
  913. # Private Methods
  914. ##########################################################################################
  915. ############################################################
  916. # __run_benchmark(script, output_file)
  917. # Runs a single benchmark using the script which is a bash
  918. # template that uses weighttp to run the test. All the results
  919. # outputed to the output_file.
  920. ############################################################
  921. def __run_benchmark(self, script, output_file, err):
  922. with open(output_file, 'w') as raw_file:
  923. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  924. p.communicate(script)
  925. err.flush()
  926. ############################################################
  927. # End __run_benchmark
  928. ############################################################
  929. ############################################################
  930. # __generate_concurrency_script(url, port)
  931. # Generates the string containing the bash script that will
  932. # be run on the client to benchmark a single test. This
  933. # specifically works for the variable concurrency tests (JSON
  934. # and DB)
  935. ############################################################
  936. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  937. if len(intervals) == 0:
  938. intervals = self.benchmarker.concurrency_levels
  939. headers = self.__get_request_headers(accept_header)
  940. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  941. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  942. interval=" ".join("{}".format(item) for item in intervals),
  943. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  944. pipeline=pipeline)
  945. ############################################################
  946. # End __generate_concurrency_script
  947. ############################################################
  948. ############################################################
  949. # __generate_query_script(url, port)
  950. # Generates the string containing the bash script that will
  951. # be run on the client to benchmark a single test. This
  952. # specifically works for the variable query tests (Query)
  953. ############################################################
  954. def __generate_query_script(self, url, port, accept_header):
  955. headers = self.__get_request_headers(accept_header)
  956. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  957. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  958. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  959. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  960. ############################################################
  961. # End __generate_query_script
  962. ############################################################
  963. ############################################################
  964. # __get_request_headers(accept_header)
  965. # Generates the complete HTTP header string
  966. ############################################################
  967. def __get_request_headers(self, accept_header):
  968. return self.headers_template.format(accept=accept_header)
  969. ############################################################
  970. # End __format_request_headers
  971. ############################################################
  972. ############################################################
  973. # __curl_url
  974. # Dump HTTP response and headers. Throw exception if there
  975. # is an HTTP error.
  976. ############################################################
  977. def __curl_url(self, url, testType, out, err):
  978. output = None
  979. try:
  980. # Use -m 15 to make curl stop trying after 15sec.
  981. # Use -i to output response with headers.
  982. # Don't use -f so that the HTTP response code is ignored.
  983. # Use --stderr - to redirect stderr to stdout so we get
  984. # error output for sure in stdout.
  985. # Use -sS to hide progress bar, but show errors.
  986. subprocess.check_call(["curl", "-m", "15", "-i", "-sS", url], stderr=err, stdout=out)
  987. # HTTP output may not end in a newline, so add that here.
  988. out.write( "\n\n" )
  989. out.flush()
  990. err.flush()
  991. # We need to get the respond body from the curl and return it.
  992. p = subprocess.Popen(["curl", "-m", "15", "-s", url], stdout=subprocess.PIPE)
  993. output = p.communicate()
  994. except:
  995. pass
  996. if output:
  997. # We have the response body - return it
  998. return output[0]
  999. ##############################################################
  1000. # End __curl_url
  1001. ##############################################################
  1002. def requires_database(self):
  1003. """Returns True/False if this test requires a database"""
  1004. return (self.contains_type(self.FORTUNE) or
  1005. self.contains_type(self.DB) or
  1006. self.contains_type(self.QUERY) or
  1007. self.contains_type(self.UPDATE))
  1008. ############################################################
  1009. # __begin_logging
  1010. # Starts a thread to monitor the resource usage, to be synced with the client's time
  1011. # TODO: MySQL and InnoDB are possible. Figure out how to implement them.
  1012. ############################################################
  1013. def __begin_logging(self, test_name):
  1014. output_file = "{file_name}".format(file_name=self.benchmarker.get_stats_file(self.name, test_name))
  1015. dstat_string = "dstat -afilmprsT --aio --fs --ipc --lock --raw --socket --tcp \
  1016. --raw --socket --tcp --udp --unix --vm --disk-util \
  1017. --rpc --rpcd --output {output_file}".format(output_file=output_file)
  1018. cmd = shlex.split(dstat_string)
  1019. dev_null = open(os.devnull, "w")
  1020. self.subprocess_handle = subprocess.Popen(cmd, stdout=dev_null)
  1021. ##############################################################
  1022. # End __begin_logging
  1023. ##############################################################
  1024. ##############################################################
  1025. # Begin __end_logging
  1026. # Stops the logger thread and blocks until shutdown is complete.
  1027. ##############################################################
  1028. def __end_logging(self):
  1029. self.subprocess_handle.terminate()
  1030. self.subprocess_handle.communicate()
  1031. ##############################################################
  1032. # End __end_logging
  1033. ##############################################################
  1034. ##############################################################
  1035. # Begin __parse_stats
  1036. # For each test type, process all the statistics, and return a multi-layered dictionary
  1037. # that has a structure as follows:
  1038. # (timestamp)
  1039. # | (main header) - group that the stat is in
  1040. # | | (sub header) - title of the stat
  1041. # | | | (stat) - the stat itself, usually a floating point number
  1042. ##############################################################
  1043. def __parse_stats(self, test_type, start_time, end_time, interval):
  1044. stats_dict = dict()
  1045. stats_file = self.benchmarker.stats_file(self.name, test_type)
  1046. with open(stats_file) as stats:
  1047. while(stats.next() != "\n"): # dstat doesn't output a completely compliant CSV file - we need to strip the header
  1048. pass
  1049. stats_reader = csv.reader(stats)
  1050. main_header = stats_reader.next()
  1051. sub_header = stats_reader.next()
  1052. time_row = sub_header.index("epoch")
  1053. int_counter = 0
  1054. for row in stats_reader:
  1055. time = float(row[time_row])
  1056. int_counter+=1
  1057. if time < start_time:
  1058. continue
  1059. elif time > end_time:
  1060. return stats_dict
  1061. if int_counter % interval != 0:
  1062. continue
  1063. row_dict = dict()
  1064. for nextheader in main_header:
  1065. if nextheader != "":
  1066. row_dict[nextheader] = dict()
  1067. header = ""
  1068. for item_num, column in enumerate(row):
  1069. if(len(main_header[item_num]) != 0):
  1070. header = main_header[item_num]
  1071. 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
  1072. stats_dict[time] = row_dict
  1073. return stats_dict
  1074. ##############################################################
  1075. # End __parse_stats
  1076. ##############################################################
  1077. def __getattr__(self, name):
  1078. """For backwards compatibility, we used to pass benchmarker
  1079. as the argument to the setup.py files"""
  1080. return getattr(self.benchmarker, name)
  1081. ##############################################################
  1082. # Begin __calculate_average_stats
  1083. # We have a large amount of raw data for the statistics that
  1084. # may be useful for the stats nerds, but most people care about
  1085. # a couple of numbers. For now, we're only going to supply:
  1086. # * Average CPU
  1087. # * Average Memory
  1088. # * Total network use
  1089. # * Total disk use
  1090. # More may be added in the future. If they are, please update
  1091. # the above list.
  1092. # Note: raw_stats is directly from the __parse_stats method.
  1093. # Recall that this consists of a dictionary of timestamps,
  1094. # each of which contain a dictionary of stat categories which
  1095. # contain a dictionary of stats
  1096. ##############################################################
  1097. def __calculate_average_stats(self, raw_stats):
  1098. raw_stat_collection = dict()
  1099. for timestamp, time_dict in raw_stats.items():
  1100. for main_header, sub_headers in time_dict.items():
  1101. item_to_append = None
  1102. if 'cpu' in main_header:
  1103. # We want to take the idl stat and subtract it from 100
  1104. # to get the time that the CPU is NOT idle.
  1105. item_to_append = sub_headers['idl'] - 100.0
  1106. elif main_header == 'memory usage':
  1107. item_to_append = sub_headers['used']
  1108. elif 'net' in main_header:
  1109. # Network stats have two parts - recieve and send. We'll use a tuple of
  1110. # style (recieve, send)
  1111. item_to_append = (sub_headers['recv'], sub_headers['send'])
  1112. elif 'dsk' or 'io' in main_header:
  1113. # Similar for network, except our tuple looks like (read, write)
  1114. item_to_append = (sub_headers['read'], sub_headers['writ'])
  1115. if item_to_append is not None:
  1116. if main_header not in raw_stat_collection:
  1117. raw_stat_collection[main_header] = list()
  1118. raw_stat_collection[main_header].append(item_to_append)
  1119. # Simple function to determine human readable size
  1120. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  1121. def sizeof_fmt(num):
  1122. # We'll assume that any number we get is convertable to a float, just in case
  1123. num = float(num)
  1124. for x in ['bytes','KB','MB','GB']:
  1125. if num < 1024.0 and num > -1024.0:
  1126. return "%3.1f%s" % (num, x)
  1127. num /= 1024.0
  1128. return "%3.1f%s" % (num, 'TB')
  1129. # Now we have our raw stats in a readable format - we need to format it for display
  1130. # We need a floating point sum, so the built in sum doesn't cut it
  1131. display_stat_collection = dict()
  1132. for header, values in raw_stat_collection.items():
  1133. display_stat = None
  1134. if 'cpu' in header:
  1135. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1136. elif main_header == 'memory usage':
  1137. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  1138. elif 'net' in main_header:
  1139. receive, send = zip(*values) # unzip
  1140. display_stat = {'receive': sizeof_fmt(math.fsum(receive)), 'send': sizeof_fmt(math.fsum(send))}
  1141. else: # if 'dsk' or 'io' in header:
  1142. read, write = zip(*values) # unzip
  1143. display_stat = {'read': sizeof_fmt(math.fsum(read)), 'write': sizeof_fmt(math.fsum(write))}
  1144. display_stat_collection[header] = display_stat
  1145. return display_stat
  1146. ###########################################################################################
  1147. # End __calculate_average_stats
  1148. #########################################################################################
  1149. ##########################################################################################
  1150. # Constructor
  1151. ##########################################################################################
  1152. def __init__(self, name, directory, benchmarker, runTests, args):
  1153. self.name = name
  1154. self.directory = directory
  1155. self.benchmarker = benchmarker
  1156. self.runTests = runTests
  1157. self.fwroot = benchmarker.fwroot
  1158. # setup logging
  1159. logging.basicConfig(stream=sys.stderr, level=logging.INFO)
  1160. self.install_root="%s/%s" % (self.fwroot, "installs")
  1161. if benchmarker.install_strategy is 'pertest':
  1162. self.install_root="%s/pertest/%s" % (self.install_root, name)
  1163. self.__dict__.update(args)
  1164. # ensure directory has __init__.py file so that we can use it as a Python package
  1165. if not os.path.exists(os.path.join(directory, "__init__.py")):
  1166. logging.warning("Please add an empty __init__.py file to directory %s", directory)
  1167. open(os.path.join(directory, "__init__.py"), 'w').close()
  1168. # Import the module (TODO - consider using sys.meta_path)
  1169. dir_rel_to_fwroot = os.path.relpath(os.path.dirname(directory), self.fwroot)
  1170. if dir_rel_to_fwroot != ".":
  1171. sys.path.append("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1172. logging.debug("Adding %s to import %s.%s", dir_rel_to_fwroot, os.path.basename(directory), self.setup_file)
  1173. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1174. sys.path.remove("%s/%s" % (self.fwroot, dir_rel_to_fwroot))
  1175. else:
  1176. logging.debug("Importing %s.%s", directory, self.setup_file)
  1177. self.setup_module = setup_module = importlib.import_module(os.path.basename(directory) + '.' + self.setup_file)
  1178. ############################################################
  1179. # End __init__
  1180. ############################################################
  1181. ############################################################
  1182. # End FrameworkTest
  1183. ############################################################
  1184. ##########################################################################################
  1185. # Static methods
  1186. ##########################################################################################
  1187. ##############################################################
  1188. # parse_config(config, directory, benchmarker)
  1189. # parses a config file and returns a list of FrameworkTest
  1190. # objects based on that config file.
  1191. ##############################################################
  1192. def parse_config(config, directory, benchmarker):
  1193. tests = []
  1194. # The config object can specify multiple tests, we neep to loop
  1195. # over them and parse them out
  1196. for test in config['tests']:
  1197. for key, value in test.iteritems():
  1198. test_name = config['framework']
  1199. runTests = dict()
  1200. runTests["json"] = (benchmarker.type == "all" or benchmarker.type == "json") and value.get("json_url", False)
  1201. runTests["db"] = (benchmarker.type == "all" or benchmarker.type == "db") and value.get("db_url", False)
  1202. runTests["query"] = (benchmarker.type == "all" or benchmarker.type == "query") and value.get("query_url", False)
  1203. runTests["fortune"] = (benchmarker.type == "all" or benchmarker.type == "fortune") and value.get("fortune_url", False)
  1204. runTests["update"] = (benchmarker.type == "all" or benchmarker.type == "update") and value.get("update_url", False)
  1205. runTests["plaintext"] = (benchmarker.type == "all" or benchmarker.type == "plaintext") and value.get("plaintext_url", False)
  1206. # if the test uses the 'defualt' keywork, then we don't
  1207. # append anything to it's name. All configs should only have 1 default
  1208. if key != 'default':
  1209. # we need to use the key in the test_name
  1210. test_name = test_name + "-" + key
  1211. tests.append(FrameworkTest(test_name, directory, benchmarker, runTests, value))
  1212. return tests
  1213. ##############################################################
  1214. # End parse_config
  1215. ##############################################################