- add sources.
[platform/framework/web/crosswalk.git] / src / tools / run-bisect-perf-regression.py
1 #!/usr/bin/env python
2 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 """Run Performance Test Bisect Tool
7
8 This script is used by a trybot to run the src/tools/bisect-perf-regression.py
9 script with the parameters specified in run-bisect-perf-regression.cfg. It will
10 check out a copy of the depot in a subdirectory 'bisect' of the working
11 directory provided, and run the bisect-perf-regression.py script there.
12
13 """
14
15 import imp
16 import optparse
17 import os
18 import subprocess
19 import sys
20 import traceback
21
22 import bisect_utils
23 bisect = imp.load_source('bisect-perf-regression',
24     os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),
25         'bisect-perf-regression.py'))
26
27
28 CROS_BOARD_ENV = 'BISECT_CROS_BOARD'
29 CROS_IP_ENV = 'BISECT_CROS_IP'
30
31
32 class Goma(object):
33
34   def __init__(self, path_to_goma):
35     self._abs_path_to_goma = None
36     self._abs_path_to_goma_file = None
37     if path_to_goma:
38       self._abs_path_to_goma = os.path.abspath(path_to_goma)
39       self._abs_path_to_goma_file = self._GetExecutablePath(
40           self._abs_path_to_goma)
41
42   def __enter__(self):
43     if self._HasGOMAPath():
44       self._SetupAndStart()
45     return self
46
47   def __exit__(self, *_):
48     if self._HasGOMAPath():
49       self._Stop()
50
51   def _HasGOMAPath(self):
52     return bool(self._abs_path_to_goma)
53
54   def _GetExecutablePath(self, path_to_goma):
55     if os.name == 'nt':
56       return os.path.join(path_to_goma, 'goma_ctl.bat')
57     else:
58       return os.path.join(path_to_goma, 'goma_ctl.sh')
59
60   def _SetupEnvVars(self):
61     if os.name == 'nt':
62       os.environ['CC'] = (os.path.join(self._abs_path_to_goma, 'gomacc.exe') +
63           ' cl.exe')
64       os.environ['CXX'] = (os.path.join(self._abs_path_to_goma, 'gomacc.exe') +
65           ' cl.exe')
66     else:
67       os.environ['PATH'] = os.pathsep.join([self._abs_path_to_goma,
68           os.environ['PATH']])
69
70   def _SetupAndStart(self):
71     """Sets up GOMA and launches it.
72
73     Args:
74       path_to_goma: Path to goma directory.
75
76     Returns:
77       True if successful."""
78     self._SetupEnvVars()
79
80     # Sometimes goma is lingering around if something went bad on a previous
81     # run. Stop it before starting a new process. Can ignore the return code
82     # since it will return an error if it wasn't running.
83     self._Stop()
84
85     if subprocess.call([self._abs_path_to_goma_file, 'start']):
86       raise RuntimeError('GOMA failed to start.')
87
88   def _Stop(self):
89     subprocess.call([self._abs_path_to_goma_file, 'stop'])
90
91
92
93 def _LoadConfigFile(path_to_file):
94   """Attempts to load the specified config file as a module
95   and grab the global config dict.
96
97   Args:
98     path_to_file: Path to the file.
99
100   Returns:
101     The config dict which should be formatted as follows:
102     {'command': string, 'good_revision': string, 'bad_revision': string
103      'metric': string, etc...}.
104     Returns None on failure.
105   """
106   try:
107     local_vars = {}
108     execfile(path_to_file, local_vars)
109
110     return local_vars['config']
111   except:
112     print
113     traceback.print_exc()
114     print
115     return {}
116
117
118 def _OutputFailedResults(text_to_print):
119   bisect_utils.OutputAnnotationStepStart('Results - Failed')
120   print
121   print text_to_print
122   print
123   bisect_utils.OutputAnnotationStepClosed()
124
125
126 def _CreateBisectOptionsFromConfig(config):
127   opts_dict = {}
128   opts_dict['command'] = config['command']
129   opts_dict['metric'] = config['metric']
130
131   if config['repeat_count']:
132     opts_dict['repeat_test_count'] = int(config['repeat_count'])
133
134   if config['truncate_percent']:
135     opts_dict['truncate_percent'] = int(config['truncate_percent'])
136
137   if config['max_time_minutes']:
138     opts_dict['max_time_minutes'] = int(config['max_time_minutes'])
139
140   if config.has_key('use_goma'):
141     opts_dict['use_goma'] = config['use_goma']
142
143   opts_dict['build_preference'] = 'ninja'
144   opts_dict['output_buildbot_annotations'] = True
145
146   if '--browser=cros' in config['command']:
147     opts_dict['target_platform'] = 'cros'
148
149     if os.environ[CROS_BOARD_ENV] and os.environ[CROS_IP_ENV]:
150       opts_dict['cros_board'] = os.environ[CROS_BOARD_ENV]
151       opts_dict['cros_remote_ip'] = os.environ[CROS_IP_ENV]
152     else:
153       raise RuntimeError('Cros build selected, but BISECT_CROS_IP or'
154           'BISECT_CROS_BOARD undefined.')
155   elif 'android' in config['command']:
156     opts_dict['target_platform'] = 'android'
157
158   return bisect.BisectOptions.FromDict(opts_dict)
159
160
161 def _RunPerformanceTest(config, path_to_file):
162   # Bisect script expects to be run from src
163   os.chdir(os.path.join(path_to_file, '..'))
164
165   bisect_utils.OutputAnnotationStepStart('Building With Patch')
166
167   opts = _CreateBisectOptionsFromConfig(config)
168   b = bisect.BisectPerformanceMetrics(None, opts)
169
170   if bisect_utils.RunGClient(['runhooks']):
171     raise RuntimeError('Failed to run gclient runhooks')
172
173   if not b.BuildCurrentRevision('chromium'):
174     raise RuntimeError('Patched version failed to build.')
175
176   bisect_utils.OutputAnnotationStepClosed()
177   bisect_utils.OutputAnnotationStepStart('Running With Patch')
178
179   results_with_patch = b.RunPerformanceTestAndParseResults(
180       opts.command, opts.metric, reset_on_first_run=True, results_label='Patch')
181
182   if results_with_patch[1]:
183     raise RuntimeError('Patched version failed to run performance test.')
184
185   bisect_utils.OutputAnnotationStepClosed()
186
187   bisect_utils.OutputAnnotationStepStart('Reverting Patch')
188   if bisect_utils.RunGClient(['revert']):
189     raise RuntimeError('Failed to run gclient runhooks')
190   bisect_utils.OutputAnnotationStepClosed()
191
192   bisect_utils.OutputAnnotationStepStart('Building Without Patch')
193
194   if bisect_utils.RunGClient(['runhooks']):
195     raise RuntimeError('Failed to run gclient runhooks')
196
197   if not b.BuildCurrentRevision('chromium'):
198     raise RuntimeError('Unpatched version failed to build.')
199
200   bisect_utils.OutputAnnotationStepClosed()
201   bisect_utils.OutputAnnotationStepStart('Running Without Patch')
202
203   results_without_patch = b.RunPerformanceTestAndParseResults(
204       opts.command, opts.metric, upload_on_last_run=True, results_label='ToT')
205
206   if results_without_patch[1]:
207     raise RuntimeError('Unpatched version failed to run performance test.')
208
209   # Find the link to the cloud stored results file.
210   output = results_without_patch[2]
211   cloud_file_link = [t for t in output.splitlines()
212       if 'storage.googleapis.com/chromium-telemetry/html-results/' in t]
213   if cloud_file_link:
214     # What we're getting here is basically "View online at http://..." so parse
215     # out just the url portion.
216     cloud_file_link = cloud_file_link[0]
217     cloud_file_link = [t for t in cloud_file_link.split(' ')
218         if 'storage.googleapis.com/chromium-telemetry/html-results/' in t]
219     assert cloud_file_link, "Couldn't parse url from output."
220     cloud_file_link = cloud_file_link[0]
221   else:
222     cloud_file_link = ''
223
224   # Calculate the % difference in the means of the 2 runs.
225   percent_diff_in_means = (results_with_patch[0]['mean'] /
226       max(0.0001, results_without_patch[0]['mean'])) * 100.0 - 100.0
227   std_err = bisect.CalculatePooledStandardError(
228       [results_with_patch[0]['values'], results_without_patch[0]['values']])
229
230   bisect_utils.OutputAnnotationStepClosed()
231   bisect_utils.OutputAnnotationStepStart('Results - %.02f +- %0.02f delta' %
232       (percent_diff_in_means, std_err))
233   print ' %s %s %s' % (''.center(10, ' '), 'Mean'.center(20, ' '),
234       'Std. Error'.center(20, ' '))
235   print ' %s %s %s' % ('Patch'.center(10, ' '),
236       ('%.02f' % results_with_patch[0]['mean']).center(20, ' '),
237       ('%.02f' % results_with_patch[0]['std_err']).center(20, ' '))
238   print ' %s %s %s' % ('No Patch'.center(10, ' '),
239       ('%.02f' % results_without_patch[0]['mean']).center(20, ' '),
240       ('%.02f' % results_without_patch[0]['std_err']).center(20, ' '))
241   if cloud_file_link:
242     bisect_utils.OutputAnnotationStepLink('HTML Results', cloud_file_link)
243   bisect_utils.OutputAnnotationStepClosed()
244
245
246 def _SetupAndRunPerformanceTest(config, path_to_file, path_to_goma):
247   """Attempts to build and run the current revision with and without the
248   current patch, with the parameters passed in.
249
250   Args:
251     config: The config read from run-perf-test.cfg.
252     path_to_file: Path to the bisect-perf-regression.py script.
253     path_to_goma: Path to goma directory.
254
255   Returns:
256     0 on success, otherwise 1.
257   """
258   try:
259     with Goma(path_to_goma) as goma:
260       config['use_goma'] = bool(path_to_goma)
261       _RunPerformanceTest(config, path_to_file)
262     return 0
263   except RuntimeError, e:
264     bisect_utils.OutputAnnotationStepClosed()
265     _OutputFailedResults('Error: %s' % e.message)
266     return 1
267
268
269 def _RunBisectionScript(config, working_directory, path_to_file, path_to_goma,
270     dry_run):
271   """Attempts to execute src/tools/bisect-perf-regression.py with the parameters
272   passed in.
273
274   Args:
275     config: A dict containing the parameters to pass to the script.
276     working_directory: A working directory to provide to the
277       bisect-perf-regression.py script, where it will store it's own copy of
278       the depot.
279     path_to_file: Path to the bisect-perf-regression.py script.
280     path_to_goma: Path to goma directory.
281     dry_run: Do a dry run, skipping sync, build, and performance testing steps.
282
283   Returns:
284     0 on success, otherwise 1.
285   """
286   bisect_utils.OutputAnnotationStepStart('Config')
287   print
288   for k, v in config.iteritems():
289     print '  %s : %s' % (k, v)
290   print
291   bisect_utils.OutputAnnotationStepClosed()
292
293   cmd = ['python', os.path.join(path_to_file, 'bisect-perf-regression.py'),
294          '-c', config['command'],
295          '-g', config['good_revision'],
296          '-b', config['bad_revision'],
297          '-m', config['metric'],
298          '--working_directory', working_directory,
299          '--output_buildbot_annotations']
300
301   if config['repeat_count']:
302     cmd.extend(['-r', config['repeat_count']])
303
304   if config['truncate_percent']:
305     cmd.extend(['-t', config['truncate_percent']])
306
307   if config['max_time_minutes']:
308     cmd.extend(['--max_time_minutes', config['max_time_minutes']])
309
310   cmd.extend(['--build_preference', 'ninja'])
311
312   if '--browser=cros' in config['command']:
313     cmd.extend(['--target_platform', 'cros'])
314
315     if os.environ[CROS_BOARD_ENV] and os.environ[CROS_IP_ENV]:
316       cmd.extend(['--cros_board', os.environ[CROS_BOARD_ENV]])
317       cmd.extend(['--cros_remote_ip', os.environ[CROS_IP_ENV]])
318     else:
319       print 'Error: Cros build selected, but BISECT_CROS_IP or'\
320             'BISECT_CROS_BOARD undefined.'
321       print
322       return 1
323
324   if 'android' in config['command']:
325     cmd.extend(['--target_platform', 'android'])
326
327   if path_to_goma:
328     cmd.append('--use_goma')
329
330   if dry_run:
331     cmd.extend(['--debug_ignore_build', '--debug_ignore_sync',
332         '--debug_ignore_perf_test'])
333   cmd = [str(c) for c in cmd]
334
335   with Goma(path_to_goma) as goma:
336     return_code = subprocess.call(cmd)
337
338   if return_code:
339     print 'Error: bisect-perf-regression.py returned with error %d' %\
340         return_code
341     print
342
343   return return_code
344
345
346 def main():
347
348   usage = ('%prog [options] [-- chromium-options]\n'
349            'Used by a trybot to run the bisection script using the parameters'
350            ' provided in the run-bisect-perf-regression.cfg file.')
351
352   parser = optparse.OptionParser(usage=usage)
353   parser.add_option('-w', '--working_directory',
354                     type='str',
355                     help='A working directory to supply to the bisection '
356                     'script, which will use it as the location to checkout '
357                     'a copy of the chromium depot.')
358   parser.add_option('-p', '--path_to_goma',
359                     type='str',
360                     help='Path to goma directory. If this is supplied, goma '
361                     'builds will be enabled.')
362   parser.add_option('--dry_run',
363                     action="store_true",
364                     help='The script will perform the full bisect, but '
365                     'without syncing, building, or running the performance '
366                     'tests.')
367   (opts, args) = parser.parse_args()
368
369   path_to_current_directory = os.path.abspath(os.path.dirname(sys.argv[0]))
370   path_to_bisect_cfg = os.path.join(path_to_current_directory,
371       'run-bisect-perf-regression.cfg')
372
373   config = _LoadConfigFile(path_to_bisect_cfg)
374
375   # Check if the config is empty
376   config_has_values = [v for v in config.values() if v]
377
378   if config and config_has_values:
379     if not opts.working_directory:
380       print 'Error: missing required parameter: --working_directory'
381       print
382       parser.print_help()
383       return 1
384
385     return _RunBisectionScript(config, opts.working_directory,
386         path_to_current_directory, opts.path_to_goma, opts.dry_run)
387   else:
388     perf_cfg_files = ['run-perf-test.cfg', os.path.join('..', 'third_party',
389         'WebKit', 'Tools', 'run-perf-test.cfg')]
390
391     for current_perf_cfg_file in perf_cfg_files:
392       path_to_perf_cfg = os.path.join(
393           os.path.abspath(os.path.dirname(sys.argv[0])), current_perf_cfg_file)
394
395       config = _LoadConfigFile(path_to_perf_cfg)
396       config_has_values = [v for v in config.values() if v]
397
398       if config and config_has_values:
399         return _SetupAndRunPerformanceTest(config, path_to_current_directory,
400             opts.path_to_goma)
401
402     print 'Error: Could not load config file. Double check your changes to '\
403           'run-bisect-perf-regression.cfg/run-perf-test.cfg for syntax errors.'
404     print
405     return 1
406
407
408 if __name__ == '__main__':
409   sys.exit(main())