results.py 22 KB

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