results.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. from toolset.utils.output_helper import log
  2. from toolset.test_types import test_types
  3. import os
  4. import subprocess
  5. import uuid
  6. import time
  7. import json
  8. import requests
  9. import threading
  10. import re
  11. import math
  12. import csv
  13. import traceback
  14. from datetime import datetime
  15. # Cross-platform colored text
  16. from colorama import Fore, Style
  17. class Results:
  18. def __init__(self, benchmarker):
  19. '''
  20. Constructor
  21. '''
  22. self.benchmarker = benchmarker
  23. self.config = benchmarker.config
  24. self.directory = os.path.join(self.config.results_root,
  25. self.config.timestamp)
  26. try:
  27. os.makedirs(self.directory)
  28. except OSError:
  29. pass
  30. self.file = os.path.join(self.directory, "results.json")
  31. self.uuid = str(uuid.uuid4())
  32. self.name = datetime.now().strftime(self.config.results_name)
  33. self.environmentDescription = self.config.results_environment
  34. try:
  35. self.git = dict()
  36. self.git['commitId'] = self.__get_git_commit_id()
  37. self.git['repositoryUrl'] = self.__get_git_repository_url()
  38. self.git['branchName'] = self.__get_git_branch_name()
  39. except Exception:
  40. #Could not read local git repository, which is fine.
  41. self.git = None
  42. self.startTime = int(round(time.time() * 1000))
  43. self.completionTime = None
  44. self.concurrencyLevels = self.config.concurrency_levels
  45. self.pipelineConcurrencyLevels = self.config.pipeline_concurrency_levels
  46. self.queryIntervals = self.config.query_levels
  47. self.cachedQueryIntervals = self.config.cached_query_levels
  48. self.frameworks = [t.name for t in benchmarker.tests]
  49. self.duration = self.config.duration
  50. self.rawData = dict()
  51. self.completed = dict()
  52. self.succeeded = dict()
  53. self.failed = dict()
  54. self.verify = dict()
  55. for type in test_types:
  56. self.rawData[type] = dict()
  57. self.failed[type] = []
  58. self.succeeded[type] = []
  59. #############################################################################
  60. # PUBLIC FUNCTIONS
  61. #############################################################################
  62. def parse(self, tests):
  63. '''
  64. Ensures that the system has all necessary software to run
  65. the tests. This does not include that software for the individual
  66. test, but covers software such as curl and weighttp that
  67. are needed.
  68. '''
  69. # Run the method to get the commmit count of each framework.
  70. self.__count_commits()
  71. # Call the method which counts the sloc for each framework
  72. self.__count_sloc()
  73. # Time to create parsed files
  74. # Aggregate JSON file
  75. with open(self.file, "w") as f:
  76. f.write(json.dumps(self.__to_jsonable(), indent=2))
  77. def parse_test(self, framework_test, test_type):
  78. '''
  79. Parses the given test and test_type from the raw_file.
  80. '''
  81. results = dict()
  82. results['results'] = []
  83. stats = []
  84. if os.path.exists(self.get_raw_file(framework_test.name, test_type)):
  85. with open(self.get_raw_file(framework_test.name,
  86. test_type)) as raw_data:
  87. is_warmup = True
  88. rawData = None
  89. for line in raw_data:
  90. if "Queries:" in line or "Concurrency:" in line:
  91. is_warmup = False
  92. rawData = None
  93. continue
  94. if "Warmup" in line or "Primer" in line:
  95. is_warmup = True
  96. continue
  97. if not is_warmup:
  98. if rawData is None:
  99. rawData = dict()
  100. results['results'].append(rawData)
  101. if "Latency" in line:
  102. m = re.findall(r"([0-9]+\.*[0-9]*[us|ms|s|m|%]+)",
  103. line)
  104. if len(m) == 4:
  105. rawData['latencyAvg'] = m[0]
  106. rawData['latencyStdev'] = m[1]
  107. rawData['latencyMax'] = m[2]
  108. if "requests in" in line:
  109. m = re.search("([0-9]+) requests in", line)
  110. if m is not None:
  111. rawData['totalRequests'] = int(m.group(1))
  112. if "Socket errors" in line:
  113. if "connect" in line:
  114. m = re.search("connect ([0-9]+)", line)
  115. rawData['connect'] = int(m.group(1))
  116. if "read" in line:
  117. m = re.search("read ([0-9]+)", line)
  118. rawData['read'] = int(m.group(1))
  119. if "write" in line:
  120. m = re.search("write ([0-9]+)", line)
  121. rawData['write'] = int(m.group(1))
  122. if "timeout" in line:
  123. m = re.search("timeout ([0-9]+)", line)
  124. rawData['timeout'] = int(m.group(1))
  125. if "Non-2xx" in line:
  126. m = re.search("Non-2xx or 3xx responses: ([0-9]+)",
  127. line)
  128. if m != None:
  129. rawData['5xx'] = int(m.group(1))
  130. if "STARTTIME" in line:
  131. m = re.search("[0-9]+", line)
  132. rawData["startTime"] = int(m.group(0))
  133. if "ENDTIME" in line:
  134. m = re.search("[0-9]+", line)
  135. rawData["endTime"] = int(m.group(0))
  136. test_stats = self.__parse_stats(
  137. framework_test, test_type,
  138. rawData["startTime"], rawData["endTime"], 1)
  139. stats.append(test_stats)
  140. with open(
  141. self.get_stats_file(framework_test.name, test_type) + ".json",
  142. "w") as stats_file:
  143. json.dump(stats, stats_file, indent=2)
  144. return results
  145. def parse_all(self, framework_test):
  146. '''
  147. Method meant to be run for a given timestamp
  148. '''
  149. for test_type in framework_test.runTests:
  150. if os.path.exists(
  151. self.get_raw_file(framework_test.name, test_type)):
  152. results = self.parse_test(framework_test, test_type)
  153. self.report_benchmark_results(framework_test, test_type,
  154. results['results'])
  155. def write_intermediate(self, test_name, status_message):
  156. '''
  157. Writes the intermediate results for the given test_name and status_message
  158. '''
  159. self.completed[test_name] = status_message
  160. self.__write_results()
  161. def set_completion_time(self):
  162. '''
  163. Sets the completionTime for these results and writes the results
  164. '''
  165. self.completionTime = int(round(time.time() * 1000))
  166. self.__write_results()
  167. def upload(self):
  168. '''
  169. Attempts to upload the results.json to the configured results_upload_uri
  170. '''
  171. if self.config.results_upload_uri is not None:
  172. try:
  173. requests.post(
  174. self.config.results_upload_uri,
  175. headers={'Content-Type': 'application/json'},
  176. data=json.dumps(self.__to_jsonable(), indent=2),
  177. timeout=300)
  178. except Exception:
  179. log("Error uploading results.json")
  180. def load(self):
  181. '''
  182. Load the results.json file
  183. '''
  184. try:
  185. with open(self.file) as f:
  186. self.__dict__.update(json.load(f))
  187. except (ValueError, IOError):
  188. pass
  189. def get_raw_file(self, test_name, test_type):
  190. '''
  191. Returns the output file for this test_name and test_type
  192. Example: fw_root/results/timestamp/test_type/test_name/raw.txt
  193. '''
  194. path = os.path.join(self.directory, test_name, test_type, "raw.txt")
  195. try:
  196. os.makedirs(os.path.dirname(path))
  197. except OSError:
  198. pass
  199. return path
  200. def get_stats_file(self, test_name, test_type):
  201. '''
  202. Returns the stats file name for this test_name and
  203. Example: fw_root/results/timestamp/test_type/test_name/stats.txt
  204. '''
  205. path = os.path.join(self.directory, test_name, test_type, "stats.txt")
  206. try:
  207. os.makedirs(os.path.dirname(path))
  208. except OSError:
  209. pass
  210. return path
  211. def report_verify_results(self, framework_test, test_type, result):
  212. '''
  213. Used by FrameworkTest to add verification details to our results
  214. TODO: Technically this is an IPC violation - we are accessing
  215. the parent process' memory from the child process
  216. '''
  217. if framework_test.name not in self.verify.keys():
  218. self.verify[framework_test.name] = dict()
  219. self.verify[framework_test.name][test_type] = result
  220. def report_benchmark_results(self, framework_test, test_type, results):
  221. '''
  222. Used by FrameworkTest to add benchmark data to this
  223. TODO: Technically this is an IPC violation - we are accessing
  224. the parent process' memory from the child process
  225. '''
  226. if test_type not in self.rawData.keys():
  227. self.rawData[test_type] = dict()
  228. # If results has a size from the parse, then it succeeded.
  229. if results:
  230. self.rawData[test_type][framework_test.name] = results
  231. # This may already be set for single-tests
  232. if framework_test.name not in self.succeeded[test_type]:
  233. self.succeeded[test_type].append(framework_test.name)
  234. else:
  235. # This may already be set for single-tests
  236. if framework_test.name not in self.failed[test_type]:
  237. self.failed[test_type].append(framework_test.name)
  238. def finish(self):
  239. '''
  240. Finishes these results.
  241. '''
  242. if not self.config.parse:
  243. # Normally you don't have to use Fore.BLUE before each line, but
  244. # Travis-CI seems to reset color codes on newline (see travis-ci/travis-ci#2692)
  245. # or stream flush, so we have to ensure that the color code is printed repeatedly
  246. log("Verification Summary",
  247. border='=',
  248. border_bottom='-',
  249. color=Fore.CYAN)
  250. for test in self.benchmarker.tests:
  251. log(Fore.CYAN + "| {!s}".format(test.name))
  252. if test.name in self.verify.keys():
  253. for test_type, result in self.verify[
  254. test.name].iteritems():
  255. if result.upper() == "PASS":
  256. color = Fore.GREEN
  257. elif result.upper() == "WARN":
  258. color = Fore.YELLOW
  259. else:
  260. color = Fore.RED
  261. log(Fore.CYAN + "| " + test_type.ljust(13) +
  262. ' : ' + color + result.upper())
  263. else:
  264. log(Fore.CYAN + "| " + Fore.RED +
  265. "NO RESULTS (Did framework launch?)")
  266. log('', border='=', border_bottom='', color=Fore.CYAN)
  267. log("Results are saved in " + self.directory)
  268. #############################################################################
  269. # PRIVATE FUNCTIONS
  270. #############################################################################
  271. def __to_jsonable(self):
  272. '''
  273. Returns a dict suitable for jsonification
  274. '''
  275. toRet = dict()
  276. toRet['uuid'] = self.uuid
  277. toRet['name'] = self.name
  278. toRet['environmentDescription'] = self.environmentDescription
  279. toRet['git'] = self.git
  280. toRet['startTime'] = self.startTime
  281. toRet['completionTime'] = self.completionTime
  282. toRet['concurrencyLevels'] = self.concurrencyLevels
  283. toRet['pipelineConcurrencyLevels'] = self.pipelineConcurrencyLevels
  284. toRet['queryIntervals'] = self.queryIntervals
  285. toRet['cachedQueryIntervals'] = self.cachedQueryIntervals
  286. toRet['frameworks'] = self.frameworks
  287. toRet['duration'] = self.duration
  288. toRet['rawData'] = self.rawData
  289. toRet['completed'] = self.completed
  290. toRet['succeeded'] = self.succeeded
  291. toRet['failed'] = self.failed
  292. toRet['verify'] = self.verify
  293. toRet['testMetadata'] = self.benchmarker.metadata.to_jsonable()
  294. return toRet
  295. def __write_results(self):
  296. try:
  297. with open(self.file, 'w') as f:
  298. f.write(json.dumps(self.__to_jsonable(), indent=2))
  299. except IOError:
  300. log("Error writing results.json")
  301. def __count_sloc(self):
  302. '''
  303. Counts the significant lines of code for all tests and stores in results.
  304. '''
  305. frameworks = self.benchmarker.metadata.gather_frameworks(
  306. self.config.test, self.config.exclude)
  307. framework_to_count = {}
  308. for framework, testlist in frameworks.items():
  309. wd = testlist[0].directory
  310. # Find the last instance of the word 'code' in the yaml output. This
  311. # should be the line count for the sum of all listed files or just
  312. # the line count for the last file in the case where there's only
  313. # one file listed.
  314. command = "cloc --yaml --follow-links . | grep code | tail -1 | cut -d: -f 2"
  315. log("Running \"%s\" (cwd=%s)" % (command, wd))
  316. try:
  317. line_count = int(subprocess.check_output(command, cwd=wd, shell=True))
  318. except (subprocess.CalledProcessError, ValueError) as e:
  319. log("Unable to count lines of code for %s due to error '%s'" %
  320. (framework, e))
  321. continue
  322. log("Counted %s lines of code" % line_count)
  323. framework_to_count[framework] = line_count
  324. self.rawData['slocCounts'] = framework_to_count
  325. def __count_commits(self):
  326. '''
  327. Count the git commits for all the framework tests
  328. '''
  329. frameworks = self.benchmarker.metadata.gather_frameworks(
  330. self.config.test, self.config.exclude)
  331. def count_commit(directory, jsonResult):
  332. command = "git rev-list HEAD -- " + directory + " | sort -u | wc -l"
  333. try:
  334. commitCount = subprocess.check_output(command, shell=True)
  335. jsonResult[framework] = int(commitCount)
  336. except subprocess.CalledProcessError:
  337. pass
  338. # Because git can be slow when run in large batches, this
  339. # calls git up to 4 times in parallel. Normal improvement is ~3-4x
  340. # in my trials, or ~100 seconds down to ~25
  341. # This is safe to parallelize as long as each thread only
  342. # accesses one key in the dictionary
  343. threads = []
  344. jsonResult = {}
  345. # t1 = datetime.now()
  346. for framework, testlist in frameworks.items():
  347. directory = testlist[0].directory
  348. t = threading.Thread(
  349. target=count_commit, args=(directory, jsonResult))
  350. t.start()
  351. threads.append(t)
  352. # Git has internal locks, full parallel will just cause contention
  353. # and slowness, so we rate-limit a bit
  354. if len(threads) >= 4:
  355. threads[0].join()
  356. threads.remove(threads[0])
  357. # Wait for remaining threads
  358. for t in threads:
  359. t.join()
  360. # t2 = datetime.now()
  361. # print "Took %s seconds " % (t2 - t1).seconds
  362. self.rawData['commitCounts'] = jsonResult
  363. self.config.commits = jsonResult
  364. def __get_git_commit_id(self):
  365. '''
  366. Get the git commit id for this benchmark
  367. '''
  368. return subprocess.check_output(
  369. ["git", "rev-parse", "HEAD"], cwd=self.config.fw_root).strip()
  370. def __get_git_repository_url(self):
  371. '''
  372. Gets the git repository url for this benchmark
  373. '''
  374. return subprocess.check_output(
  375. ["git", "config", "--get", "remote.origin.url"],
  376. cwd=self.config.fw_root).strip()
  377. def __get_git_branch_name(self):
  378. '''
  379. Gets the git branch name for this benchmark
  380. '''
  381. return subprocess.check_output(
  382. 'git rev-parse --abbrev-ref HEAD',
  383. shell=True,
  384. cwd=self.config.fw_root).strip()
  385. def __parse_stats(self, framework_test, test_type, start_time, end_time,
  386. interval):
  387. '''
  388. For each test type, process all the statistics, and return a multi-layered
  389. dictionary that has a structure as follows:
  390. (timestamp)
  391. | (main header) - group that the stat is in
  392. | | (sub header) - title of the stat
  393. | | | (stat) - the stat itself, usually a floating point number
  394. '''
  395. stats_dict = dict()
  396. stats_file = self.get_stats_file(framework_test.name, test_type)
  397. with open(stats_file) as stats:
  398. # dstat doesn't output a completely compliant CSV file - we need to strip the header
  399. for _ in range(4):
  400. stats.next()
  401. stats_reader = csv.reader(stats)
  402. main_header = stats_reader.next()
  403. sub_header = stats_reader.next()
  404. time_row = sub_header.index("epoch")
  405. int_counter = 0
  406. for row in stats_reader:
  407. time = float(row[time_row])
  408. int_counter += 1
  409. if time < start_time:
  410. continue
  411. elif time > end_time:
  412. return stats_dict
  413. if int_counter % interval != 0:
  414. continue
  415. row_dict = dict()
  416. for nextheader in main_header:
  417. if nextheader != "":
  418. row_dict[nextheader] = dict()
  419. header = ""
  420. for item_num, column in enumerate(row):
  421. if len(main_header[item_num]) != 0:
  422. header = main_header[item_num]
  423. # all the stats are numbers, so we want to make sure that they stay that way in json
  424. row_dict[header][sub_header[item_num]] = float(column)
  425. stats_dict[time] = row_dict
  426. return stats_dict
  427. def __calculate_average_stats(self, raw_stats):
  428. '''
  429. We have a large amount of raw data for the statistics that may be useful
  430. for the stats nerds, but most people care about a couple of numbers. For
  431. now, we're only going to supply:
  432. * Average CPU
  433. * Average Memory
  434. * Total network use
  435. * Total disk use
  436. More may be added in the future. If they are, please update the above list.
  437. Note: raw_stats is directly from the __parse_stats method.
  438. Recall that this consists of a dictionary of timestamps, each of which
  439. contain a dictionary of stat categories which contain a dictionary of stats
  440. '''
  441. raw_stat_collection = dict()
  442. for time_dict in raw_stats.items()[1]:
  443. for main_header, sub_headers in time_dict.items():
  444. item_to_append = None
  445. if 'cpu' in main_header:
  446. # We want to take the idl stat and subtract it from 100
  447. # to get the time that the CPU is NOT idle.
  448. item_to_append = sub_headers['idl'] - 100.0
  449. elif main_header == 'memory usage':
  450. item_to_append = sub_headers['used']
  451. elif 'net' in main_header:
  452. # Network stats have two parts - recieve and send. We'll use a tuple of
  453. # style (recieve, send)
  454. item_to_append = (sub_headers['recv'], sub_headers['send'])
  455. elif 'dsk' or 'io' in main_header:
  456. # Similar for network, except our tuple looks like (read, write)
  457. item_to_append = (sub_headers['read'], sub_headers['writ'])
  458. if item_to_append is not None:
  459. if main_header not in raw_stat_collection:
  460. raw_stat_collection[main_header] = list()
  461. raw_stat_collection[main_header].append(item_to_append)
  462. # Simple function to determine human readable size
  463. # http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  464. def sizeof_fmt(num):
  465. # We'll assume that any number we get is convertable to a float, just in case
  466. num = float(num)
  467. for x in ['bytes', 'KB', 'MB', 'GB']:
  468. if 1024.0 > num > -1024.0:
  469. return "%3.1f%s" % (num, x)
  470. num /= 1024.0
  471. return "%3.1f%s" % (num, 'TB')
  472. # Now we have our raw stats in a readable format - we need to format it for display
  473. # We need a floating point sum, so the built in sum doesn't cut it
  474. display_stat_collection = dict()
  475. for header, values in raw_stat_collection.items():
  476. display_stat = None
  477. if 'cpu' in header:
  478. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  479. elif main_header == 'memory usage':
  480. display_stat = sizeof_fmt(math.fsum(values) / len(values))
  481. elif 'net' in main_header:
  482. receive, send = zip(*values) # unzip
  483. display_stat = {
  484. 'receive': sizeof_fmt(math.fsum(receive)),
  485. 'send': sizeof_fmt(math.fsum(send))
  486. }
  487. else: # if 'dsk' or 'io' in header:
  488. read, write = zip(*values) # unzip
  489. display_stat = {
  490. 'read': sizeof_fmt(math.fsum(read)),
  491. 'write': sizeof_fmt(math.fsum(write))
  492. }
  493. display_stat_collection[header] = display_stat
  494. return display_stat