framework_test.py 56 KB

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