Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / browser_options.py
1 # Copyright 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import copy
6 import logging
7 import optparse
8 import os
9 import shlex
10 import sys
11
12 from telemetry.core import browser_finder
13 from telemetry.core import profile_types
14 from telemetry.core import util
15 from telemetry.core import wpr_modes
16 from telemetry.core.platform.profiler import profiler_finder
17
18 util.AddDirToPythonPath(
19     util.GetChromiumSrcDir(), 'third_party', 'webpagereplay')
20 import net_configs  # pylint: disable=F0401
21
22
23 class BrowserFinderOptions(optparse.Values):
24   """Options to be used for discovering a browser."""
25
26   def __init__(self, browser_type=None):
27     optparse.Values.__init__(self)
28
29     self.browser_type = browser_type
30     self.browser_executable = None
31     self.chrome_root = None
32     self.android_device = None
33     self.cros_ssh_identity = None
34
35     self.extensions_to_load = []
36
37     # If set, copy the generated profile to this path on exit.
38     self.output_profile_path = None
39
40     self.cros_remote = None
41
42     self.profiler = None
43     self.verbosity = 0
44
45     self.browser_options = BrowserOptions()
46     self.output_file = None
47
48     self.android_rndis = False
49
50   def __repr__(self):
51     return str(sorted(self.__dict__.items()))
52
53   def Copy(self):
54     return copy.deepcopy(self)
55
56   def CreateParser(self, *args, **kwargs):
57     parser = optparse.OptionParser(*args, **kwargs)
58
59     # Selection group
60     group = optparse.OptionGroup(parser, 'Which browser to use')
61     group.add_option('--browser',
62         dest='browser_type',
63         default=None,
64         help='Browser type to run, '
65              'in order of priority. Supported values: list,%s' %
66              ','.join(browser_finder.FindAllBrowserTypes()))
67     group.add_option('--browser-executable',
68         dest='browser_executable',
69         help='The exact browser to run.')
70     group.add_option('--chrome-root',
71         dest='chrome_root',
72         help='Where to look for chrome builds.'
73              'Defaults to searching parent dirs by default.')
74     group.add_option('--device',
75         dest='android_device',
76         help='The android device ID to use'
77              'If not specified, only 0 or 1 connected devcies are supported.')
78     group.add_option('--target-arch',
79         dest='target_arch',
80         help='The target architecture of the browser. Options available are: '
81              'x64, x86_64, arm, arm64 and mips. '
82              'Defaults to the default architecture of the platform if omitted.')
83     group.add_option(
84         '--remote',
85         dest='cros_remote',
86         help='The IP address of a remote ChromeOS device to use.')
87     identity = None
88     testing_rsa = os.path.join(
89         util.GetChromiumSrcDir(),
90         'third_party', 'chromite', 'ssh_keys', 'testing_rsa')
91     if os.path.exists(testing_rsa):
92       identity = testing_rsa
93     group.add_option('--identity',
94         dest='cros_ssh_identity',
95         default=identity,
96         help='The identity file to use when ssh\'ing into the ChromeOS device')
97     parser.add_option_group(group)
98
99     # Debugging options
100     group = optparse.OptionGroup(parser, 'When things go wrong')
101     profiler_choices = profiler_finder.GetAllAvailableProfilers()
102     group.add_option(
103         '--profiler', default=None, type='choice',
104         choices=profiler_choices,
105         help='Record profiling data using this tool. Supported values: ' +
106              ', '.join(profiler_choices))
107     group.add_option(
108         '--interactive', dest='interactive', action='store_true',
109         help='Let the user interact with the page; the actions specified for '
110              'the page are not run.')
111     group.add_option(
112         '-v', '--verbose', action='count', dest='verbosity',
113         help='Increase verbosity level (repeat as needed)')
114     group.add_option('--print-bootstrap-deps',
115                      action='store_true',
116                      help='Output bootstrap deps list.')
117     parser.add_option_group(group)
118
119     # Platform options
120     group = optparse.OptionGroup(parser, 'Platform options')
121     group.add_option('--no-performance-mode', action='store_true',
122         help='Some platforms run on "full performance mode" where the '
123         'test is executed at maximum CPU speed in order to minimize noise '
124         '(specially important for dashboards / continuous builds). '
125         'This option prevents Telemetry from tweaking such platform settings.')
126     group.add_option('--android-rndis', dest='android_rndis', default=False,
127         action='store_true', help='Use RNDIS forwarding on Android.')
128     group.add_option('--no-android-rndis', dest='android_rndis',
129         action='store_false', help='Do not use RNDIS forwarding on Android.'
130         ' [default]')
131     parser.add_option_group(group)
132
133     # Browser options.
134     self.browser_options.AddCommandLineArgs(parser)
135
136     real_parse = parser.parse_args
137     def ParseArgs(args=None):
138       defaults = parser.get_default_values()
139       for k, v in defaults.__dict__.items():
140         if k in self.__dict__ and self.__dict__[k] != None:
141           continue
142         self.__dict__[k] = v
143       ret = real_parse(args, self) # pylint: disable=E1121
144
145       if self.verbosity >= 2:
146         logging.getLogger().setLevel(logging.DEBUG)
147       elif self.verbosity:
148         logging.getLogger().setLevel(logging.INFO)
149       else:
150         logging.getLogger().setLevel(logging.WARNING)
151
152       if self.browser_executable and not self.browser_type:
153         self.browser_type = 'exact'
154       if self.browser_type == 'list':
155         try:
156           types = browser_finder.GetAllAvailableBrowserTypes(self)
157         except browser_finder.BrowserFinderException, ex:
158           sys.stderr.write('ERROR: ' + str(ex))
159           sys.exit(1)
160         sys.stdout.write('Available browsers:\n')
161         sys.stdout.write('  %s\n' % '\n  '.join(types))
162         sys.exit(0)
163
164       # Parse browser options.
165       self.browser_options.UpdateFromParseResults(self)
166
167       return ret
168     parser.parse_args = ParseArgs
169     return parser
170
171   def AppendExtraBrowserArgs(self, args):
172     self.browser_options.AppendExtraBrowserArgs(args)
173
174   def MergeDefaultValues(self, defaults):
175     for k, v in defaults.__dict__.items():
176       self.ensure_value(k, v)
177
178 class BrowserOptions(object):
179   """Options to be used for launching a browser."""
180   def __init__(self):
181     self.browser_type = None
182     self.show_stdout = False
183
184     # When set to True, the browser will use the default profile.  Telemetry
185     # will not provide an alternate profile directory.
186     self.dont_override_profile = False
187     self.profile_dir = None
188     self.profile_type = None
189     self._extra_browser_args = set()
190     self.extra_wpr_args = []
191     self.wpr_mode = wpr_modes.WPR_OFF
192     self.netsim = None
193
194     self.no_proxy_server = False
195     self.browser_user_agent_type = None
196
197     self.clear_sytem_cache_for_browser_and_profile_on_start = False
198     self.startup_url = 'about:blank'
199
200     # Background pages of built-in component extensions can interfere with
201     # performance measurements.
202     self.disable_component_extensions_with_background_pages = True
203
204     # Whether to use the new code path for choosing an ephemeral port for
205     # DevTools. The bots set this to true. When Chrome 37 reaches stable,
206     # remove this setting and the old code path. http://crbug.com/379980
207     self.use_devtools_active_port = False
208
209   def __repr__(self):
210     return str(sorted(self.__dict__.items()))
211
212   @classmethod
213   def AddCommandLineArgs(cls, parser):
214
215     ############################################################################
216     # Please do not add any more options here without first discussing with    #
217     # a telemetry owner. This is not the right place for platform-specific     #
218     # options.                                                                 #
219     ############################################################################
220
221     group = optparse.OptionGroup(parser, 'Browser options')
222     profile_choices = profile_types.GetProfileTypes()
223     group.add_option('--profile-type',
224         dest='profile_type',
225         type='choice',
226         default='clean',
227         choices=profile_choices,
228         help=('The user profile to use. A clean profile is used by default. '
229               'Supported values: ' + ', '.join(profile_choices)))
230     group.add_option('--profile-dir',
231         dest='profile_dir',
232         help='Profile directory to launch the browser with. '
233              'A clean profile is used by default')
234     group.add_option('--extra-browser-args',
235         dest='extra_browser_args_as_string',
236         help='Additional arguments to pass to the browser when it starts')
237     group.add_option('--extra-wpr-args',
238         dest='extra_wpr_args_as_string',
239         help=('Additional arguments to pass to Web Page Replay. '
240               'See third_party/webpagereplay/replay.py for usage.'))
241     group.add_option('--netsim', default=None, type='choice',
242         choices=net_configs.NET_CONFIG_NAMES,
243         help=('Run benchmark under simulated network conditions. '
244               'Will prompt for sudo. Supported values: ' +
245               ', '.join(net_configs.NET_CONFIG_NAMES)))
246     group.add_option('--show-stdout',
247         action='store_true',
248         help='When possible, will display the stdout of the process')
249     # This hidden option is to be removed, and the older code path deleted,
250     # once Chrome 37 reaches Stable. http://crbug.com/379980
251     group.add_option('--use-devtools-active-port',
252         action='store_true',
253         help=optparse.SUPPRESS_HELP)
254     parser.add_option_group(group)
255
256     group = optparse.OptionGroup(parser, 'Compatibility options')
257     group.add_option('--gtest_output',
258         help='Ignored argument for compatibility with runtest.py harness')
259     parser.add_option_group(group)
260
261     group = optparse.OptionGroup(parser, 'Synthetic gesture options')
262     synthetic_gesture_source_type_choices = [ 'default', 'mouse', 'touch' ]
263     group.add_option('--synthetic-gesture-source-type',
264         dest='synthetic_gesture_source_type',
265         default='default', type='choice',
266         choices=synthetic_gesture_source_type_choices,
267         help='Specify the source type for synthetic gestures. Note that some ' +
268              'actions only support a specific source type. ' +
269              'Supported values: ' +
270              ', '.join(synthetic_gesture_source_type_choices))
271     parser.add_option_group(group)
272
273
274   def UpdateFromParseResults(self, finder_options):
275     """Copies our options from finder_options"""
276     browser_options_list = [
277         'extra_browser_args_as_string',
278         'extra_wpr_args_as_string',
279         'netsim',
280         'profile_dir',
281         'profile_type',
282         'show_stdout',
283         'synthetic_gesture_source_type',
284         'use_devtools_active_port',
285         ]
286     for o in browser_options_list:
287       a = getattr(finder_options, o, None)
288       if a is not None:
289         setattr(self, o, a)
290         delattr(finder_options, o)
291
292     self.browser_type = finder_options.browser_type
293
294     if hasattr(self, 'extra_browser_args_as_string'): # pylint: disable=E1101
295       tmp = shlex.split(
296         self.extra_browser_args_as_string) # pylint: disable=E1101
297       self.AppendExtraBrowserArgs(tmp)
298       delattr(self, 'extra_browser_args_as_string')
299     if hasattr(self, 'extra_wpr_args_as_string'): # pylint: disable=E1101
300       tmp = shlex.split(
301         self.extra_wpr_args_as_string) # pylint: disable=E1101
302       self.extra_wpr_args.extend(tmp)
303       delattr(self, 'extra_wpr_args_as_string')
304     if self.profile_type == 'default':
305       self.dont_override_profile = True
306
307     if self.profile_dir and self.profile_type != 'clean':
308       logging.critical(
309           "It's illegal to specify both --profile-type and --profile-dir.\n"
310           "For more information see: http://goo.gl/ngdGD5")
311       sys.exit(1)
312
313     if self.profile_dir and not os.path.isdir(self.profile_dir):
314       logging.critical(
315           "Directory specified by --profile-dir (%s) doesn't exist "
316           "or isn't a directory.\n"
317           "For more information see: http://goo.gl/ngdGD5" % self.profile_dir)
318       sys.exit(1)
319
320     if not self.profile_dir:
321       self.profile_dir = profile_types.GetProfileDir(self.profile_type)
322
323     # This deferred import is necessary because browser_options is imported in
324     # telemetry/telemetry/__init__.py.
325     from telemetry.core.backends.chrome import chrome_browser_options
326     finder_options.browser_options = (
327         chrome_browser_options.CreateChromeBrowserOptions(self))
328
329   @property
330   def extra_browser_args(self):
331     return self._extra_browser_args
332
333   def AppendExtraBrowserArgs(self, args):
334     if isinstance(args, list):
335       self._extra_browser_args.update(args)
336     else:
337       self._extra_browser_args.add(args)