1# Copyright 2015 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 5import optparse 6import os 7import sys 8 9from devil.android.constants import chrome 10from devil.android import device_utils, device_errors 11 12class OptionParserIgnoreErrors(optparse.OptionParser): 13 """Wrapper for OptionParser that ignores errors and produces no output.""" 14 15 def error(self, msg): 16 pass 17 18 def exit(self, status=0, msg=None): 19 pass 20 21 def print_usage(self, out_file=None): 22 pass 23 24 def print_help(self, out_file=None): 25 pass 26 27 def print_version(self, out_file=None): 28 pass 29 30 31def run_adb_shell(shell_args, device_serial): 32 """Runs "adb shell" with the given arguments. 33 34 Args: 35 shell_args: array of arguments to pass to adb shell. 36 device_serial: if not empty, will add the appropriate command-line 37 parameters so that adb targets the given device. 38 Returns: 39 A tuple containing the adb output (stdout & stderr) and the return code 40 from adb. Will exit if adb fails to start. 41 """ 42 adb_output = [] 43 adb_return_code = 0 44 device = device_utils.DeviceUtils.HealthyDevices(device_arg=device_serial)[0] 45 try: 46 adb_output = device.RunShellCommand(shell_args, shell=False, 47 check_return=True, raw_output=True) 48 except device_errors.AdbShellCommandFailedError as error: 49 adb_return_code = error.status 50 adb_output = error.output 51 52 return (adb_output, adb_return_code) 53 54 55def get_device_sdk_version(): 56 """Uses adb to attempt to determine the SDK version of a running device.""" 57 58 getprop_args = ['getprop', 'ro.build.version.sdk'] 59 60 # get_device_sdk_version() is called before we even parse our command-line 61 # args. Therefore, parse just the device serial number part of the 62 # command-line so we can send the adb command to the correct device. 63 parser = OptionParserIgnoreErrors() 64 parser.add_option('-e', '--serial', dest='device_serial', type='string') 65 options, unused_args = parser.parse_args() # pylint: disable=unused-variable 66 67 success = False 68 69 adb_output, adb_return_code = run_adb_shell(getprop_args, 70 options.device_serial) 71 72 if adb_return_code == 0: 73 # ADB may print output other than the version number (e.g. it chould 74 # print a message about starting the ADB server). 75 # Break the ADB output into white-space delimited segments. 76 parsed_output = str.split(adb_output) 77 if parsed_output: 78 # Assume that the version number is the last thing printed by ADB. 79 version_string = parsed_output[-1] 80 if version_string: 81 try: 82 # Try to convert the text into an integer. 83 version = int(version_string) 84 except ValueError: 85 version = -1 86 else: 87 success = True 88 89 if not success: 90 print >> sys.stderr, adb_output 91 raise Exception("Failed to get device sdk version") 92 93 return version 94 95 96def get_supported_browsers(): 97 """Returns the package names of all supported browsers.""" 98 # Add aliases for backwards compatibility. 99 supported_browsers = { 100 'stable': chrome.PACKAGE_INFO['chrome_stable'], 101 'beta': chrome.PACKAGE_INFO['chrome_beta'], 102 'dev': chrome.PACKAGE_INFO['chrome_dev'], 103 'build': chrome.PACKAGE_INFO['chrome'], 104 } 105 supported_browsers.update(chrome.PACKAGE_INFO) 106 return supported_browsers 107 108 109def get_default_serial(): 110 if 'ANDROID_SERIAL' in os.environ: 111 return os.environ['ANDROID_SERIAL'] 112 return None 113 114 115def get_main_options(parser): 116 parser.add_option('-o', dest='output_file', help='write trace output to FILE', 117 default=None, metavar='FILE') 118 parser.add_option('-t', '--time', dest='trace_time', type='int', 119 help='trace for N seconds', metavar='N') 120 parser.add_option('-j', '--json', dest='write_json', 121 default=False, action='store_true', 122 help='write a JSON file') 123 parser.add_option('--link-assets', dest='link_assets', default=False, 124 action='store_true', 125 help='(deprecated)') 126 parser.add_option('--from-file', dest='from_file', action='store', 127 help='read the trace from a file (compressed) rather than' 128 'running a live trace') 129 parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer', 130 type='string', help='(deprecated)') 131 parser.add_option('-e', '--serial', dest='device_serial_number', 132 default=get_default_serial(), 133 type='string', help='adb device serial number') 134 parser.add_option('--target', dest='target', default='android', type='string', 135 help='choose tracing target (android or linux)') 136 parser.add_option('--timeout', dest='timeout', type='int', 137 help='timeout for start and stop tracing (seconds)') 138 parser.add_option('--collection-timeout', dest='collection_timeout', 139 type='int', help='timeout for data collection (seconds)') 140 parser.add_option('-a', '--app', dest='app_name', default=None, 141 type='string', action='store', 142 help='enable application-level tracing for ' 143 'comma-separated list of app cmdlines') 144 parser.add_option('-t', '--time', dest='trace_time', type='int', 145 help='trace for N seconds', metavar='N') 146 parser.add_option('-b', '--buf-size', dest='trace_buf_size', 147 type='int', help='use a trace buffer size ' 148 ' of N KB', metavar='N') 149 return parser 150