benchmark_log_tool.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  3. # This source code is licensed under both the GPLv2 (found in the
  4. # COPYING file in the root directory) and Apache 2.0 License
  5. # (found in the LICENSE.Apache file in the root directory).
  6. """Access the results of benchmark runs
  7. Send these results on to OpenSearch graphing service
  8. """
  9. import argparse
  10. import itertools
  11. import logging
  12. import os
  13. import re
  14. import sys
  15. import requests
  16. from dateutil import parser
  17. logging.basicConfig(level=logging.DEBUG)
  18. class Configuration:
  19. opensearch_user = os.environ["ES_USER"]
  20. opensearch_pass = os.environ["ES_PASS"]
  21. class BenchmarkResultException(Exception):
  22. def __init__(self, message, content):
  23. super().__init__(self, message)
  24. self.content = content
  25. class BenchmarkUtils:
  26. expected_keys = [
  27. "ops_sec",
  28. "mb_sec",
  29. "lsm_sz",
  30. "blob_sz",
  31. "c_wgb",
  32. "w_amp",
  33. "c_mbps",
  34. "c_wsecs",
  35. "c_csecs",
  36. "b_rgb",
  37. "b_wgb",
  38. "usec_op",
  39. "p50",
  40. "p99",
  41. "p99.9",
  42. "p99.99",
  43. "pmax",
  44. "uptime",
  45. "stall%",
  46. "Nstall",
  47. "u_cpu",
  48. "s_cpu",
  49. "rss",
  50. "test",
  51. "date",
  52. "version",
  53. "job_id",
  54. ]
  55. def sanity_check(row):
  56. if "test" not in row:
  57. logging.debug(f"not 'test' in row: {row}")
  58. return False
  59. if row["test"] == "":
  60. logging.debug(f"row['test'] == '': {row}")
  61. return False
  62. if "date" not in row:
  63. logging.debug(f"not 'date' in row: {row}")
  64. return False
  65. if "ops_sec" not in row:
  66. logging.debug(f"not 'ops_sec' in row: {row}")
  67. return False
  68. try:
  69. _ = int(row["ops_sec"])
  70. except (ValueError, TypeError):
  71. logging.debug(f"int(row['ops_sec']): {row}")
  72. return False
  73. try:
  74. (_, _) = parser.parse(row["date"], fuzzy_with_tokens=True)
  75. except (parser.ParserError):
  76. logging.error(
  77. f"parser.parse((row['date']): not a valid format for date in row: {row}"
  78. )
  79. return False
  80. return True
  81. def conform_opensearch(row):
  82. (dt, _) = parser.parse(row["date"], fuzzy_with_tokens=True)
  83. # create a test_date field, which was previously what was expected
  84. # repair the date field, which has what can be a WRONG ISO FORMAT, (no leading 0 on single-digit day-of-month)
  85. # e.g. 2022-07-1T00:14:55 should be 2022-07-01T00:14:55
  86. row["test_date"] = dt.isoformat()
  87. row["date"] = dt.isoformat()
  88. return {key.replace(".", "_"): value for key, value in row.items()}
  89. class ResultParser:
  90. def __init__(self, field=r"(\w|[+-:.%])+", intrafield=r"(\s)+", separator="\t"):
  91. self.field = re.compile(field)
  92. self.intra = re.compile(intrafield)
  93. self.sep = re.compile(separator)
  94. def ignore(self, l_in: str):
  95. if len(l_in) == 0:
  96. return True
  97. if l_in[0:1] == "#":
  98. return True
  99. return False
  100. def line(self, line_in: str):
  101. """Parse a line into items
  102. Being clever about separators
  103. """
  104. line = line_in
  105. row = []
  106. while line != "":
  107. match_item = self.field.match(line)
  108. if match_item:
  109. item = match_item.group(0)
  110. row.append(item)
  111. line = line[len(item) :]
  112. else:
  113. match_intra = self.intra.match(line)
  114. if match_intra:
  115. intra = match_intra.group(0)
  116. # Count the separators
  117. # If there are >1 then generate extra blank fields
  118. # White space with no true separators fakes up a single separator
  119. tabbed = self.sep.split(intra)
  120. sep_count = len(tabbed) - 1
  121. if sep_count == 0:
  122. sep_count = 1
  123. for _ in range(sep_count - 1):
  124. row.append("")
  125. line = line[len(intra) :]
  126. else:
  127. raise BenchmarkResultException(
  128. "Invalid TSV line", f"{line_in} at {line}"
  129. )
  130. return row
  131. def parse(self, lines):
  132. """Parse something that iterates lines"""
  133. rows = [self.line(line) for line in lines if not self.ignore(line)]
  134. header = rows[0]
  135. width = len(header)
  136. records = [
  137. {k: v for (k, v) in itertools.zip_longest(header, row[:width])}
  138. for row in rows[1:]
  139. ]
  140. return records
  141. def load_report_from_tsv(filename: str):
  142. file = open(filename)
  143. contents = file.readlines()
  144. file.close()
  145. parser = ResultParser()
  146. report = parser.parse(contents)
  147. logging.debug(f"Loaded TSV Report: {report}")
  148. return report
  149. def push_report_to_opensearch(report, esdocument):
  150. sanitized = [
  151. BenchmarkUtils.conform_opensearch(row)
  152. for row in report
  153. if BenchmarkUtils.sanity_check(row)
  154. ]
  155. logging.debug(
  156. f"upload {len(sanitized)} sane of {len(report)} benchmarks to opensearch"
  157. )
  158. for single_benchmark in sanitized:
  159. logging.debug(f"upload benchmark: {single_benchmark}")
  160. response = requests.post(
  161. esdocument,
  162. json=single_benchmark,
  163. auth=(os.environ["ES_USER"], os.environ["ES_PASS"]),
  164. )
  165. logging.debug(
  166. f"Sent to OpenSearch, status: {response.status_code}, result: {response.text}"
  167. )
  168. response.raise_for_status()
  169. def push_report_to_null(report):
  170. for row in report:
  171. if BenchmarkUtils.sanity_check(row):
  172. logging.debug(f"row {row}")
  173. conformed = BenchmarkUtils.conform_opensearch(row)
  174. logging.debug(f"conformed row {conformed}")
  175. def main():
  176. """Tool for fetching, parsing and uploading benchmark results to OpenSearch / ElasticSearch
  177. This tool will
  178. (1) Open a local tsv benchmark report file
  179. (2) Upload to OpenSearch document, via https/JSON
  180. """
  181. parser = argparse.ArgumentParser(description="CircleCI benchmark scraper.")
  182. # --tsvfile is the name of the file to read results from
  183. # --esdocument is the ElasticSearch document to push these results into
  184. #
  185. parser.add_argument(
  186. "--tsvfile",
  187. default="build_tools/circle_api_scraper_input.txt",
  188. help="File from which to read tsv report",
  189. )
  190. parser.add_argument(
  191. "--esdocument",
  192. help="ElasticSearch/OpenSearch document URL to upload report into",
  193. )
  194. parser.add_argument(
  195. "--upload", choices=["opensearch", "none"], default="opensearch"
  196. )
  197. args = parser.parse_args()
  198. logging.debug(f"Arguments: {args}")
  199. reports = load_report_from_tsv(args.tsvfile)
  200. if args.upload == "opensearch":
  201. push_report_to_opensearch(reports, args.esdocument)
  202. else:
  203. push_report_to_null(reports)
  204. if __name__ == "__main__":
  205. sys.exit(main())