framework_test.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. import importlib
  2. import os
  3. import subprocess
  4. import time
  5. import re
  6. import pprint
  7. import sys
  8. import traceback
  9. import json
  10. class FrameworkTest:
  11. ##########################################################################################
  12. # Class variables
  13. ##########################################################################################
  14. headers_template = "-H 'Host: localhost' -H '{accept}' -H 'Connection: keep-alive'"
  15. 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'"
  16. accept_json = "Accept: application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  17. accept_html = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  18. accept_plaintext = "Accept: text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7"
  19. concurrency_template = """
  20. echo ""
  21. echo "---------------------------------------------------------"
  22. echo " Running Primer {name}"
  23. echo " {wrk} {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}\""
  24. echo "---------------------------------------------------------"
  25. echo ""
  26. {wrk} {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}"
  27. sleep 5
  28. echo ""
  29. echo "---------------------------------------------------------"
  30. echo " Running Warmup {name}"
  31. echo " {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}\""
  32. echo "---------------------------------------------------------"
  33. echo ""
  34. {wrk} {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}"
  35. sleep 5
  36. for c in {interval}
  37. do
  38. echo ""
  39. echo "---------------------------------------------------------"
  40. echo " Concurrency: $c for {name}"
  41. echo " {wrk} {headers} {pipeline} -d {duration} -c $c -t $(($c>{max_threads}?{max_threads}:$c)) \"http://{server_host}:{port}{url}\""
  42. echo "---------------------------------------------------------"
  43. echo ""
  44. {wrk} {headers} {pipeline} -d {duration} -c "$c" -t "$(($c>{max_threads}?{max_threads}:$c))" http://{server_host}:{port}{url}
  45. sleep 2
  46. done
  47. """
  48. query_template = """
  49. echo ""
  50. echo "---------------------------------------------------------"
  51. echo " Running Primer {name}"
  52. echo " wrk {headers} -d 5 -c 8 -t 8 \"http://{server_host}:{port}{url}2\""
  53. echo "---------------------------------------------------------"
  54. echo ""
  55. wrk {headers} -d 5 -c 8 -t 8 "http://{server_host}:{port}{url}2"
  56. sleep 5
  57. echo ""
  58. echo "---------------------------------------------------------"
  59. echo " Running Warmup {name}"
  60. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}2\""
  61. echo "---------------------------------------------------------"
  62. echo ""
  63. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}2"
  64. sleep 5
  65. for c in {interval}
  66. do
  67. echo ""
  68. echo "---------------------------------------------------------"
  69. echo " Queries: $c for {name}"
  70. echo " wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} \"http://{server_host}:{port}{url}$c\""
  71. echo "---------------------------------------------------------"
  72. echo ""
  73. wrk {headers} -d {duration} -c {max_concurrency} -t {max_threads} "http://{server_host}:{port}{url}$c"
  74. sleep 2
  75. done
  76. """
  77. language = None
  78. platform = None
  79. webserver = None
  80. classification = None
  81. database = None
  82. approach = None
  83. orm = None
  84. framework = None
  85. os = None
  86. database_os = None
  87. display_name = None
  88. notes = None
  89. versus = None
  90. ############################################################
  91. # Test Variables
  92. ############################################################
  93. JSON = "json"
  94. DB = "db"
  95. QUERY = "query"
  96. FORTUNE = "fortune"
  97. UPDATE = "update"
  98. PLAINTEXT = "plaintext"
  99. ##########################################################################################
  100. # Public Methods
  101. ##########################################################################################
  102. ############################################################
  103. # Validates the jsonString is a JSON object with a 'message'
  104. # key with the value "hello, world!" (case-insensitive).
  105. ############################################################
  106. def validateJson(self, jsonString):
  107. obj = json.loads(jsonString)
  108. if not obj:
  109. return False
  110. if not obj["message"]:
  111. return False
  112. if not obj["message"].lower() == "hello, world!":
  113. return False
  114. return True
  115. ############################################################
  116. # Validates the jsonString is an array with a length of
  117. # 2, that each entry in the array is a JSON object, that
  118. # each object has an "id" and a "randomNumber" key, and that
  119. # both keys map to integers.
  120. ############################################################
  121. def validateDb(self, jsonString):
  122. arr = json.loads(jsonString)
  123. if not arr:
  124. return False
  125. if not len(arr) == 2:
  126. return False
  127. if type(arr[0]) is not dict or type(arr[1]) is not dict:
  128. return False
  129. if not arr[0]["id"] or not arr[0]["randomNumber"]:
  130. return False
  131. if type(arr[0]["id"]) is not int or type(arr[0]["randomNumber"]) is not int:
  132. return False
  133. if not arr[1]["id"] or not arr[1]["randomNumber"]:
  134. return False
  135. if type(arr[1]["id"]) is not int or type(arr[1]["randomNumber"]) is not int:
  136. return False
  137. return True
  138. ############################################################
  139. # start(benchmarker)
  140. # Start the test using it's setup file
  141. ############################################################
  142. def start(self, out, err):
  143. return self.setup_module.start(self.benchmarker, out, err)
  144. ############################################################
  145. # End start
  146. ############################################################
  147. ############################################################
  148. # stop(benchmarker)
  149. # Stops the test using it's setup file
  150. ############################################################
  151. def stop(self, out, err):
  152. return self.setup_module.stop(out, err)
  153. ############################################################
  154. # End stop
  155. ############################################################
  156. ############################################################
  157. # verify_urls
  158. # Verifys each of the URLs for this test. THis will sinply
  159. # curl the URL and check for it's return status.
  160. # For each url, a flag will be set on this object for whether
  161. # or not it passed
  162. ############################################################
  163. def verify_urls(self, out, err):
  164. # JSON
  165. try:
  166. out.write( "VERIFYING JSON (" + self.json_url + ") ...\n" )
  167. out.flush()
  168. url = self.benchmarker.generate_url(self.json_url, self.port)
  169. output = self.__curl_url(url, self.JSON, out, err)
  170. if self.validateJson(output):
  171. self.json_url_passed = True
  172. else:
  173. self.json_url_passed = False
  174. except (AttributeError, subprocess.CalledProcessError) as e:
  175. self.json_url_passed = False
  176. # DB
  177. try:
  178. out.write( "VERIFYING DB (" + self.db_url + ") ...\n" )
  179. out.flush()
  180. url = self.benchmarker.generate_url(self.db_url, self.port)
  181. output = self.__curl_url(url, self.DB, out, err)
  182. if self.validateDb(output):
  183. self.db_url_passed = True
  184. else:
  185. self.db_url_passed = False
  186. except (AttributeError, subprocess.CalledProcessError) as e:
  187. self.db_url_passed = False
  188. # Query
  189. try:
  190. out.write( "VERIFYING Query (" + self.query_url + "2) ...\n" )
  191. out.flush()
  192. url = self.benchmarker.generate_url(self.query_url + "2", self.port)
  193. output = self.__curl_url(url, self.QUERY, out, err)
  194. self.query_url_passed = True
  195. except (AttributeError, subprocess.CalledProcessError) as e:
  196. self.query_url_passed = False
  197. # Fortune
  198. try:
  199. out.write( "VERIFYING Fortune (" + self.fortune_url + ") ...\n" )
  200. out.flush()
  201. url = self.benchmarker.generate_url(self.fortune_url, self.port)
  202. output = self.__curl_url(url, self.FORTUNE, out, err)
  203. self.fortune_url_passed = True
  204. except (AttributeError, subprocess.CalledProcessError) as e:
  205. self.fortune_url_passed = False
  206. # Update
  207. try:
  208. out.write( "VERIFYING Update (" + self.update_url + "2) ...\n" )
  209. out.flush()
  210. url = self.benchmarker.generate_url(self.update_url + "2", self.port)
  211. output = self.__curl_url(url, self.UPDATE, out, err)
  212. self.update_url_passed = True
  213. except (AttributeError, subprocess.CalledProcessError) as e:
  214. self.update_url_passed = False
  215. # plaintext
  216. try:
  217. out.write( "VERIFYING Plaintext (" + self.plaintext_url + ") ...\n" )
  218. out.flush()
  219. url = self.benchmarker.generate_url(self.plaintext_url, self.port)
  220. output = self.__curl_url(url, self.PLAINTEXT, out, err)
  221. self.plaintext_url_passed = True
  222. except (AttributeError, subprocess.CalledProcessError) as e:
  223. self.plaintext_url_passed = False
  224. ############################################################
  225. # End verify_urls
  226. ############################################################
  227. ############################################################
  228. # contains_type(type)
  229. # true if this test contains an implementation of the given
  230. # test type (json, db, etc.)
  231. ############################################################
  232. def contains_type(self, type):
  233. try:
  234. if type == self.JSON and self.json_url != None:
  235. return True
  236. if type == self.DB and self.db_url != None:
  237. return True
  238. if type == self.QUERY and self.query_url != None:
  239. return True
  240. if type == self.FORTUNE and self.fortune_url != None:
  241. return True
  242. if type == self.UPDATE and self.update_url != None:
  243. return True
  244. if type == self.PLAINTEXT and self.plaintext_url != None:
  245. return True
  246. except AttributeError:
  247. pass
  248. return False
  249. ############################################################
  250. # End stop
  251. ############################################################
  252. ############################################################
  253. # benchmark
  254. # Runs the benchmark for each type of test that it implements
  255. # JSON/DB/Query.
  256. ############################################################
  257. def benchmark(self, out, err):
  258. # JSON
  259. try:
  260. if self.benchmarker.type == "all" or self.benchmarker.type == self.JSON:
  261. out.write("BENCHMARKING JSON ... ")
  262. out.flush()
  263. results = None
  264. if self.json_url_passed:
  265. remote_script = self.__generate_concurrency_script(self.json_url, self.port, self.accept_json)
  266. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.JSON), err)
  267. results = self.__parse_test(self.JSON)
  268. else:
  269. # This should report results with a mark of failed JSON.
  270. results = dict()
  271. results['results'] = []
  272. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'], passed=self.json_url_passed)
  273. out.write( "Complete\n" )
  274. out.flush()
  275. except AttributeError:
  276. pass
  277. # DB
  278. try:
  279. if self.db_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == self.DB):
  280. out.write("BENCHMARKING DB ... ")
  281. out.flush()
  282. remote_script = self.__generate_concurrency_script(self.db_url, self.port, self.accept_json)
  283. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.DB), err)
  284. results = self.__parse_test(self.DB)
  285. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'], passed=self.db_url_passed)
  286. out.write( "Complete\n" )
  287. except AttributeError:
  288. traceback.print_exc()
  289. pass
  290. # Query
  291. try:
  292. if self.query_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == self.QUERY):
  293. out.write("BENCHMARKING Query ... ")
  294. out.flush()
  295. remote_script = self.__generate_query_script(self.query_url, self.port, self.accept_json)
  296. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.QUERY), err)
  297. results = self.__parse_test(self.QUERY)
  298. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'], passed=self.query_url_passed)
  299. out.write( "Complete\n" )
  300. out.flush()
  301. except AttributeError:
  302. traceback.print_exc()
  303. pass
  304. # fortune
  305. try:
  306. if self.fortune_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == self.FORTUNE):
  307. out.write("BENCHMARKING Fortune ... ")
  308. out.flush()
  309. remote_script = self.__generate_concurrency_script(self.fortune_url, self.port, self.accept_html)
  310. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.FORTUNE), err)
  311. results = self.__parse_test(self.FORTUNE)
  312. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'], passed=self.fortune_url_passed)
  313. out.write( "Complete\n" )
  314. out.flush()
  315. except AttributeError:
  316. traceback.print_exc()
  317. pass
  318. # update
  319. try:
  320. if self.update_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == self.UPDATE):
  321. out.write("BENCHMARKING Update ... ")
  322. out.flush()
  323. remote_script = self.__generate_query_script(self.update_url, self.port, self.accept_json)
  324. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.UPDATE), err)
  325. results = self.__parse_test(self.UPDATE)
  326. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'], passed=self.update_url_passed)
  327. out.write( "Complete\n" )
  328. out.flush()
  329. except AttributeError:
  330. # TODO - this needs to report some logging
  331. traceback.print_exc()
  332. pass
  333. # plaintext
  334. try:
  335. if self.plaintext_url_passed and (self.benchmarker.type == "all" or self.benchmarker.type == self.PLAINTEXT):
  336. out.write("BENCHMARKING Plaintext ... ")
  337. out.flush()
  338. remote_script = self.__generate_concurrency_script(self.plaintext_url, self.port, self.accept_plaintext, wrk_command="wrk-pipeline", intervals=[256,1024,4096,16384], pipeline="--pipeline 16")
  339. self.__run_benchmark(remote_script, self.benchmarker.output_file(self.name, self.PLAINTEXT), err)
  340. results = self.__parse_test(self.PLAINTEXT)
  341. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'], passed=self.plaintext_url_passed)
  342. out.write( "Complete\n" )
  343. out.flush()
  344. except AttributeError:
  345. traceback.print_exc()
  346. pass
  347. ############################################################
  348. # End benchmark
  349. ############################################################
  350. ############################################################
  351. # parse_all
  352. # Method meant to be run for a given timestamp
  353. ############################################################
  354. def parse_all(self):
  355. # JSON
  356. if os.path.exists(self.benchmarker.output_file(self.name, self.JSON)):
  357. results = self.__parse_test(self.JSON)
  358. self.benchmarker.report_results(framework=self, test=self.JSON, results=results['results'])
  359. # DB
  360. if os.path.exists(self.benchmarker.output_file(self.name, self.DB)):
  361. results = self.__parse_test(self.DB)
  362. self.benchmarker.report_results(framework=self, test=self.DB, results=results['results'])
  363. # Query
  364. if os.path.exists(self.benchmarker.output_file(self.name, self.QUERY)):
  365. results = self.__parse_test(self.QUERY)
  366. self.benchmarker.report_results(framework=self, test=self.QUERY, results=results['results'])
  367. # Fortune
  368. if os.path.exists(self.benchmarker.output_file(self.name, self.FORTUNE)):
  369. results = self.__parse_test(self.FORTUNE)
  370. self.benchmarker.report_results(framework=self, test=self.FORTUNE, results=results['results'])
  371. # Update
  372. if os.path.exists(self.benchmarker.output_file(self.name, self.UPDATE)):
  373. results = self.__parse_test(self.UPDATE)
  374. self.benchmarker.report_results(framework=self, test=self.UPDATE, results=results['results'])
  375. # Plaintext
  376. if os.path.exists(self.benchmarker.output_file(self.name, self.PLAINTEXT)):
  377. results = self.__parse_test(self.PLAINTEXT)
  378. self.benchmarker.report_results(framework=self, test=self.PLAINTEXT, results=results['results'])
  379. ############################################################
  380. # End parse_all
  381. ############################################################
  382. ############################################################
  383. # __parse_test(test_type)
  384. ############################################################
  385. def __parse_test(self, test_type):
  386. try:
  387. results = dict()
  388. results['results'] = []
  389. with open(self.benchmarker.output_file(self.name, test_type)) as raw_data:
  390. is_warmup = True
  391. rawData = None
  392. for line in raw_data:
  393. if "Queries:" in line or "Concurrency:" in line:
  394. is_warmup = False
  395. rawData = None
  396. continue
  397. if "Warmup" in line or "Primer" in line:
  398. is_warmup = True
  399. continue
  400. if not is_warmup:
  401. if rawData == None:
  402. rawData = dict()
  403. results['results'].append(rawData)
  404. #if "Requests/sec:" in line:
  405. # m = re.search("Requests/sec:\s+([0-9]+)", line)
  406. # rawData['reportedResults'] = m.group(1)
  407. # search for weighttp data such as succeeded and failed.
  408. if "Latency" in line:
  409. m = re.findall("([0-9]+\.*[0-9]*[us|ms|s|m|%]+)", line)
  410. if len(m) == 4:
  411. rawData['latencyAvg'] = m[0]
  412. rawData['latencyStdev'] = m[1]
  413. rawData['latencyMax'] = m[2]
  414. # rawData['latencyStdevPercent'] = m[3]
  415. #if "Req/Sec" in line:
  416. # m = re.findall("([0-9]+\.*[0-9]*[k|%]*)", line)
  417. # if len(m) == 4:
  418. # rawData['requestsAvg'] = m[0]
  419. # rawData['requestsStdev'] = m[1]
  420. # rawData['requestsMax'] = m[2]
  421. # rawData['requestsStdevPercent'] = m[3]
  422. #if "requests in" in line:
  423. # m = re.search("requests in ([0-9]+\.*[0-9]*[ms|s|m|h]+)", line)
  424. # if m != None:
  425. # # parse out the raw time, which may be in minutes or seconds
  426. # raw_time = m.group(1)
  427. # if "ms" in raw_time:
  428. # rawData['total_time'] = float(raw_time[:len(raw_time)-2]) / 1000.0
  429. # elif "s" in raw_time:
  430. # rawData['total_time'] = float(raw_time[:len(raw_time)-1])
  431. # elif "m" in raw_time:
  432. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 60.0
  433. # elif "h" in raw_time:
  434. # rawData['total_time'] = float(raw_time[:len(raw_time)-1]) * 3600.0
  435. if "requests in" in line:
  436. m = re.search("([0-9]+) requests in", line)
  437. if m != None:
  438. rawData['totalRequests'] = int(m.group(1))
  439. if "Socket errors" in line:
  440. if "connect" in line:
  441. m = re.search("connect ([0-9]+)", line)
  442. rawData['connect'] = int(m.group(1))
  443. if "read" in line:
  444. m = re.search("read ([0-9]+)", line)
  445. rawData['read'] = int(m.group(1))
  446. if "write" in line:
  447. m = re.search("write ([0-9]+)", line)
  448. rawData['write'] = int(m.group(1))
  449. if "timeout" in line:
  450. m = re.search("timeout ([0-9]+)", line)
  451. rawData['timeout'] = int(m.group(1))
  452. if "Non-2xx" in line:
  453. m = re.search("Non-2xx or 3xx responses: ([0-9]+)", line)
  454. if m != None:
  455. rawData['5xx'] = int(m.group(1))
  456. return results
  457. except IOError:
  458. return None
  459. ############################################################
  460. # End benchmark
  461. ############################################################
  462. ##########################################################################################
  463. # Private Methods
  464. ##########################################################################################
  465. ############################################################
  466. # __run_benchmark(script, output_file)
  467. # Runs a single benchmark using the script which is a bash
  468. # template that uses weighttp to run the test. All the results
  469. # outputed to the output_file.
  470. ############################################################
  471. def __run_benchmark(self, script, output_file, err):
  472. with open(output_file, 'w') as raw_file:
  473. p = subprocess.Popen(self.benchmarker.client_ssh_string.split(" "), stdin=subprocess.PIPE, stdout=raw_file, stderr=err)
  474. p.communicate(script)
  475. err.flush()
  476. ############################################################
  477. # End __run_benchmark
  478. ############################################################
  479. ############################################################
  480. # __generate_concurrency_script(url, port)
  481. # Generates the string containing the bash script that will
  482. # be run on the client to benchmark a single test. This
  483. # specifically works for the variable concurrency tests (JSON
  484. # and DB)
  485. ############################################################
  486. def __generate_concurrency_script(self, url, port, accept_header, wrk_command="wrk", intervals=[], pipeline=""):
  487. if len(intervals) == 0:
  488. intervals = self.benchmarker.concurrency_levels
  489. headers = self.__get_request_headers(accept_header)
  490. return self.concurrency_template.format(max_concurrency=self.benchmarker.max_concurrency,
  491. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  492. interval=" ".join("{}".format(item) for item in intervals),
  493. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers, wrk=wrk_command,
  494. pipeline=pipeline)
  495. ############################################################
  496. # End __generate_concurrency_script
  497. ############################################################
  498. ############################################################
  499. # __generate_query_script(url, port)
  500. # Generates the string containing the bash script that will
  501. # be run on the client to benchmark a single test. This
  502. # specifically works for the variable query tests (Query)
  503. ############################################################
  504. def __generate_query_script(self, url, port, accept_header):
  505. headers = self.__get_request_headers(accept_header)
  506. return self.query_template.format(max_concurrency=self.benchmarker.max_concurrency,
  507. max_threads=self.benchmarker.max_threads, name=self.name, duration=self.benchmarker.duration,
  508. interval=" ".join("{}".format(item) for item in self.benchmarker.query_intervals),
  509. server_host=self.benchmarker.server_host, port=port, url=url, headers=headers)
  510. ############################################################
  511. # End __generate_query_script
  512. ############################################################
  513. ############################################################
  514. # __get_request_headers(accept_header)
  515. # Generates the complete HTTP header string
  516. ############################################################
  517. def __get_request_headers(self, accept_header):
  518. return self.headers_template.format(accept=accept_header)
  519. ############################################################
  520. # End __format_request_headers
  521. ############################################################
  522. ############################################################
  523. # __curl_url
  524. # Dump HTTP response and headers. Throw exception if there
  525. # is an HTTP error.
  526. ############################################################
  527. def __curl_url(self, url, testType, out, err):
  528. # Use -i to output response with headers.
  529. # Don't use -f so that the HTTP response code is ignored.
  530. # Use --stderr - to redirect stderr to stdout so we get
  531. # error output for sure in stdout.
  532. # Use -sS to hide progress bar, but show errors.
  533. subprocess.check_call(["curl", "-i", "-sS", url], stderr=err, stdout=out)
  534. out.flush()
  535. err.flush()
  536. # HTTP output may not end in a newline, so add that here.
  537. out.write( "\n" )
  538. out.flush()
  539. # We need to get the respond body from the curl and return it.
  540. p = subprocess.Popen(["curl", "-s", url], stdout=subprocess.PIPE)
  541. output = p.communicate()
  542. # In the curl invocation above we could not use -f because
  543. # then the HTTP response would not be output, so use -f in
  544. # an additional invocation so that if there is an HTTP error,
  545. # subprocess.CalledProcessError will be thrown. Note that this
  546. # uses check_output() instead of check_call() so that we can
  547. # ignore the HTTP response because we already output that in
  548. # the first curl invocation.
  549. subprocess.check_output(["curl", "-fsS", url], stderr=err)
  550. out.flush()
  551. err.flush()
  552. # HTTP output may not end in a newline, so add that here.
  553. out.write( "\n" )
  554. out.flush()
  555. if output:
  556. # We have the response body - return it
  557. return output[0]
  558. ##############################################################
  559. # End __curl_url
  560. ##############################################################
  561. ##########################################################################################
  562. # Constructor
  563. ##########################################################################################
  564. def __init__(self, name, directory, benchmarker, args):
  565. self.name = name
  566. self.directory = directory
  567. self.benchmarker = benchmarker
  568. self.__dict__.update(args)
  569. # ensure directory has __init__.py file so that we can use it as a Python package
  570. if not os.path.exists(os.path.join(directory, "__init__.py")):
  571. open(os.path.join(directory, "__init__.py"), 'w').close()
  572. self.setup_module = setup_module = importlib.import_module(directory + '.' + self.setup_file)
  573. ############################################################
  574. # End __init__
  575. ############################################################
  576. ############################################################
  577. # End FrameworkTest
  578. ############################################################
  579. ##########################################################################################
  580. # Static methods
  581. ##########################################################################################
  582. ##############################################################
  583. # parse_config(config, directory, benchmarker)
  584. # parses a config file and returns a list of FrameworkTest
  585. # objects based on that config file.
  586. ##############################################################
  587. def parse_config(config, directory, benchmarker):
  588. tests = []
  589. # The config object can specify multiple tests, we neep to loop
  590. # over them and parse them out
  591. for test in config['tests']:
  592. for key, value in test.iteritems():
  593. test_name = config['framework']
  594. # if the test uses the 'defualt' keywork, then we don't
  595. # append anything to it's name. All configs should only have 1 default
  596. if key != 'default':
  597. # we need to use the key in the test_name
  598. test_name = test_name + "-" + key
  599. tests.append(FrameworkTest(test_name, directory, benchmarker, value))
  600. return tests
  601. ##############################################################
  602. # End parse_config
  603. ##############################################################