framework_test.py 58 KB

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