framework_test.py 58 KB

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