framework_test.py 58 KB

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