framework_test.py 57 KB

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