perftestsrunner.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # Copyright (C) 2012 Google Inc. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above
  10. # copyright notice, this list of conditions and the following disclaimer
  11. # in the documentation and/or other materials provided with the
  12. # distribution.
  13. # * Neither the name of Google Inc. nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. """Run Inspector's perf tests in perf mode."""
  29. import os
  30. import json
  31. import logging
  32. import optparse
  33. import time
  34. import datetime
  35. from webkitpy.common import find_files
  36. from webkitpy.common.checkout.scm.detection import SCMDetector
  37. from webkitpy.common.config.urls import view_source_url
  38. from webkitpy.common.host import Host
  39. from webkitpy.common.net.file_uploader import FileUploader
  40. from webkitpy.performance_tests.perftest import PerfTestFactory
  41. from webkitpy.performance_tests.perftest import DEFAULT_TEST_RUNNER_COUNT
  42. _log = logging.getLogger(__name__)
  43. class PerfTestsRunner(object):
  44. _default_branch = 'webkit-trunk'
  45. EXIT_CODE_BAD_BUILD = -1
  46. EXIT_CODE_BAD_SOURCE_JSON = -2
  47. EXIT_CODE_BAD_MERGE = -3
  48. EXIT_CODE_FAILED_UPLOADING = -4
  49. EXIT_CODE_BAD_PREPARATION = -5
  50. _DEFAULT_JSON_FILENAME = 'PerformanceTestsResults.json'
  51. def __init__(self, args=None, port=None):
  52. self._options, self._args = PerfTestsRunner._parse_args(args)
  53. if port:
  54. self._port = port
  55. self._host = self._port.host
  56. else:
  57. self._host = Host()
  58. self._port = self._host.port_factory.get(self._options.platform, self._options)
  59. self._host.initialize_scm()
  60. self._webkit_base_dir_len = len(self._port.webkit_base())
  61. self._base_path = self._port.perf_tests_dir()
  62. self._timestamp = time.time()
  63. self._utc_timestamp = datetime.datetime.utcnow()
  64. @staticmethod
  65. def _parse_args(args=None):
  66. def _expand_path(option, opt_str, value, parser):
  67. path = os.path.expandvars(os.path.expanduser(value))
  68. setattr(parser.values, option.dest, path)
  69. perf_option_list = [
  70. optparse.make_option('--debug', action='store_const', const='Debug', dest="configuration",
  71. help='Set the configuration to Debug'),
  72. optparse.make_option('--release', action='store_const', const='Release', dest="configuration",
  73. help='Set the configuration to Release'),
  74. optparse.make_option("--platform",
  75. help="Specify port/platform being tested (i.e. chromium-mac)"),
  76. optparse.make_option("--builder-name",
  77. help=("The name of the builder shown on the waterfall running this script e.g. google-mac-2.")),
  78. optparse.make_option("--build-number",
  79. help=("The build number of the builder running this script.")),
  80. optparse.make_option("--build", dest="build", action="store_true", default=True,
  81. help="Check to ensure the DumpRenderTree build is up-to-date (default)."),
  82. optparse.make_option("--no-build", dest="build", action="store_false",
  83. help="Don't check to see if the DumpRenderTree build is up-to-date."),
  84. optparse.make_option("--build-directory",
  85. help="Path to the directory under which build files are kept (should not include configuration)"),
  86. optparse.make_option("--time-out-ms", default=600 * 1000,
  87. help="Set the timeout for each test"),
  88. optparse.make_option("--no-results", action="store_false", dest="generate_results", default=True,
  89. help="Do no generate results JSON and results page."),
  90. optparse.make_option("--output-json-path", action='callback', callback=_expand_path, type="str",
  91. help="Path to generate a JSON file at; may contain previous results if it already exists."),
  92. optparse.make_option("--reset-results", action="store_true",
  93. help="Clears the content in the generated JSON file before adding the results."),
  94. optparse.make_option("--slave-config-json-path", action='callback', callback=_expand_path, type="str",
  95. help="Only used on bots. Path to a slave configuration file."),
  96. optparse.make_option("--description",
  97. help="Add a description to the output JSON file if one is generated"),
  98. optparse.make_option("--no-show-results", action="store_false", default=True, dest="show_results",
  99. help="Don't launch a browser with results after the tests are done"),
  100. optparse.make_option("--test-results-server",
  101. help="Upload the generated JSON file to the specified server when --output-json-path is present."),
  102. optparse.make_option("--webkit-test-runner", "-2", action="store_true",
  103. help="Use WebKitTestRunner rather than DumpRenderTree."),
  104. optparse.make_option("--replay", dest="replay", action="store_true", default=False,
  105. help="Run replay tests."),
  106. optparse.make_option("--force", dest="use_skipped_list", action="store_false", default=True,
  107. help="Run all tests, including the ones in the Skipped list."),
  108. optparse.make_option("--profile", action="store_true",
  109. help="Output per-test profile information."),
  110. optparse.make_option("--profiler", action="store",
  111. help="Output per-test profile information, using the specified profiler."),
  112. optparse.make_option("--additional-drt-flag", action="append",
  113. default=[], help="Additional command line flag to pass to DumpRenderTree "
  114. "Specify multiple times to add multiple flags."),
  115. optparse.make_option("--driver-name", type="string",
  116. help="Alternative DumpRenderTree binary to use"),
  117. optparse.make_option("--repeat", default=1, type="int",
  118. help="Specify number of times to run test set (default: 1)."),
  119. optparse.make_option("--test-runner-count", default=DEFAULT_TEST_RUNNER_COUNT, type="int",
  120. help="Specify number of times to invoke test runner for each performance test."),
  121. ]
  122. return optparse.OptionParser(option_list=(perf_option_list)).parse_args(args)
  123. def _collect_tests(self):
  124. test_extensions = ['.html', '.svg']
  125. if self._options.replay:
  126. test_extensions.append('.replay')
  127. def _is_test_file(filesystem, dirname, filename):
  128. return filesystem.splitext(filename)[1] in test_extensions
  129. filesystem = self._host.filesystem
  130. paths = []
  131. for arg in self._args:
  132. if filesystem.exists(filesystem.join(self._base_path, arg)):
  133. paths.append(arg)
  134. else:
  135. relpath = filesystem.relpath(arg, self._base_path)
  136. if filesystem.exists(filesystem.join(self._base_path, relpath)):
  137. paths.append(filesystem.normpath(relpath))
  138. else:
  139. _log.warn('Path was not found:' + arg)
  140. skipped_directories = set(['.svn', 'resources'])
  141. test_files = find_files.find(filesystem, self._base_path, paths, skipped_directories, _is_test_file)
  142. tests = []
  143. for path in test_files:
  144. relative_path = filesystem.relpath(path, self._base_path).replace('\\', '/')
  145. if self._options.use_skipped_list and self._port.skips_perf_test(relative_path) and filesystem.normpath(relative_path) not in paths:
  146. continue
  147. test = PerfTestFactory.create_perf_test(self._port, relative_path, path, test_runner_count=self._options.test_runner_count)
  148. tests.append(test)
  149. return tests
  150. def run(self):
  151. if not self._port.check_build(needs_http=False):
  152. _log.error("Build not up to date for %s" % self._port._path_to_driver())
  153. return self.EXIT_CODE_BAD_BUILD
  154. run_count = 0
  155. repeat = self._options.repeat
  156. while (run_count < repeat):
  157. run_count += 1
  158. tests = self._collect_tests()
  159. runs = ' (Run %d of %d)' % (run_count, repeat) if repeat > 1 else ''
  160. _log.info("Running %d tests%s" % (len(tests), runs))
  161. for test in tests:
  162. if not test.prepare(self._options.time_out_ms):
  163. return self.EXIT_CODE_BAD_PREPARATION
  164. unexpected = self._run_tests_set(sorted(list(tests), key=lambda test: test.test_name()))
  165. if self._options.generate_results and not self._options.profile:
  166. exit_code = self._generate_results()
  167. if exit_code:
  168. return exit_code
  169. if self._options.generate_results and not self._options.profile:
  170. test_results_server = self._options.test_results_server
  171. if test_results_server and not self._upload_json(test_results_server, self._output_json_path()):
  172. return self.EXIT_CODE_FAILED_UPLOADING
  173. if self._options.show_results:
  174. self._port.show_results_html_file(self._results_page_path())
  175. return unexpected
  176. def _output_json_path(self):
  177. output_json_path = self._options.output_json_path
  178. if output_json_path:
  179. return output_json_path
  180. return self._host.filesystem.join(self._port.perf_results_directory(), self._DEFAULT_JSON_FILENAME)
  181. def _results_page_path(self):
  182. return self._host.filesystem.splitext(self._output_json_path())[0] + '.html'
  183. def _generate_results(self):
  184. options = self._options
  185. output_json_path = self._output_json_path()
  186. output = self._generate_results_dict(self._timestamp, options.description, options.platform, options.builder_name, options.build_number)
  187. if options.slave_config_json_path:
  188. output = self._merge_slave_config_json(options.slave_config_json_path, output)
  189. if not output:
  190. return self.EXIT_CODE_BAD_SOURCE_JSON
  191. output = self._merge_outputs_if_needed(output_json_path, output)
  192. if not output:
  193. return self.EXIT_CODE_BAD_MERGE
  194. filesystem = self._host.filesystem
  195. json_output = json.dumps(output)
  196. filesystem.write_text_file(output_json_path, json_output)
  197. template_path = filesystem.join(self._port.perf_tests_dir(), 'resources/results-template.html')
  198. template = filesystem.read_text_file(template_path)
  199. absolute_path_to_trunk = filesystem.dirname(self._port.perf_tests_dir())
  200. results_page = template.replace('%AbsolutePathToWebKitTrunk%', absolute_path_to_trunk)
  201. results_page = results_page.replace('%PeformanceTestsResultsJSON%', json_output)
  202. filesystem.write_text_file(self._results_page_path(), results_page)
  203. def _generate_results_dict(self, timestamp, description, platform, builder_name, build_number):
  204. revisions = {}
  205. for (name, path) in self._port.repository_paths():
  206. scm = SCMDetector(self._host.filesystem, self._host.executive).detect_scm_system(path) or self._host.scm()
  207. revision = scm.svn_revision(path)
  208. revisions[name] = {'revision': revision, 'timestamp': scm.timestamp_of_revision(path, revision)}
  209. meta_info = {
  210. 'description': description,
  211. 'buildTime': self._datetime_in_ES5_compatible_iso_format(self._utc_timestamp),
  212. 'platform': platform,
  213. 'revisions': revisions,
  214. 'builderName': builder_name,
  215. 'buildNumber': int(build_number) if build_number else None}
  216. contents = {'tests': {}}
  217. for key, value in meta_info.items():
  218. if value:
  219. contents[key] = value
  220. for test, metrics in self._results:
  221. for metric_name, iteration_values in metrics.iteritems():
  222. if not isinstance(iteration_values, list): # We can't reports results without individual measurements.
  223. continue
  224. tests = contents['tests']
  225. path = test.test_name_without_file_extension().split('/')
  226. for i in range(0, len(path)):
  227. is_last_token = i + 1 == len(path)
  228. url = view_source_url('PerformanceTests/' + (test.test_name() if is_last_token else '/'.join(path[0:i + 1])))
  229. tests.setdefault(path[i], {'url': url})
  230. current_test = tests[path[i]]
  231. if is_last_token:
  232. current_test.setdefault('metrics', {})
  233. assert metric_name not in current_test['metrics']
  234. current_test['metrics'][metric_name] = {'current': iteration_values}
  235. else:
  236. current_test.setdefault('tests', {})
  237. tests = current_test['tests']
  238. return contents
  239. @staticmethod
  240. def _datetime_in_ES5_compatible_iso_format(datetime):
  241. return datetime.strftime('%Y-%m-%dT%H:%M:%S.%f')
  242. def _merge_slave_config_json(self, slave_config_json_path, contents):
  243. if not self._host.filesystem.isfile(slave_config_json_path):
  244. _log.error("Missing slave configuration JSON file: %s" % slave_config_json_path)
  245. return None
  246. try:
  247. slave_config_json = self._host.filesystem.open_text_file_for_reading(slave_config_json_path)
  248. slave_config = json.load(slave_config_json)
  249. for key in slave_config:
  250. contents['builder' + key.capitalize()] = slave_config[key]
  251. return contents
  252. except Exception, error:
  253. _log.error("Failed to merge slave configuration JSON file %s: %s" % (slave_config_json_path, error))
  254. return None
  255. def _merge_outputs_if_needed(self, output_json_path, output):
  256. if self._options.reset_results or not self._host.filesystem.isfile(output_json_path):
  257. return [output]
  258. try:
  259. existing_outputs = json.loads(self._host.filesystem.read_text_file(output_json_path))
  260. return existing_outputs + [output]
  261. except Exception, error:
  262. _log.error("Failed to merge output JSON file %s: %s" % (output_json_path, error))
  263. return None
  264. def _upload_json(self, test_results_server, json_path, host_path="/api/report", file_uploader=FileUploader):
  265. url = "https://%s%s" % (test_results_server, host_path)
  266. uploader = file_uploader(url, 120)
  267. try:
  268. response = uploader.upload_single_text_file(self._host.filesystem, 'application/json', json_path)
  269. except Exception, error:
  270. _log.error("Failed to upload JSON file to %s in 120s: %s" % (url, error))
  271. return False
  272. response_body = [line.strip('\n') for line in response]
  273. if response_body != ['OK']:
  274. try:
  275. parsed_response = json.loads('\n'.join(response_body))
  276. except:
  277. _log.error("Uploaded JSON to %s but got a bad response:" % url)
  278. for line in response_body:
  279. _log.error(line)
  280. return False
  281. if parsed_response.get('status') != 'OK':
  282. _log.error("Uploaded JSON to %s but got an error:" % url)
  283. _log.error(json.dumps(parsed_response, indent=4))
  284. return False
  285. _log.info("JSON file uploaded to %s." % url)
  286. return True
  287. def _run_tests_set(self, tests):
  288. result_count = len(tests)
  289. failures = 0
  290. self._results = []
  291. for i, test in enumerate(tests):
  292. _log.info('Running %s (%d of %d)' % (test.test_name(), i + 1, len(tests)))
  293. start_time = time.time()
  294. metrics = test.run(self._options.time_out_ms)
  295. if metrics:
  296. self._results.append((test, metrics))
  297. else:
  298. failures += 1
  299. _log.error('FAILED')
  300. _log.info('Finished: %f s' % (time.time() - start_time))
  301. _log.info('')
  302. return failures