framework_test.py 59 KB

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