[Android] Change object types from AndroidCommands to DeviceUtils everywhere else.

BUG=267773

Review URL: https://codereview.chromium.org/243403003

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@266818 0039d316-1c4b-4281-b951-d872f2087c98
parent 8e215a66
......@@ -40,6 +40,7 @@ if util.IsLinux():
from pylib import constants
from pylib import forwarder
from pylib import valgrind_tools
from pylib.device import device_utils
_NEGATIVE_FILTER = [
......@@ -179,18 +180,18 @@ class ChromeDriverTest(ChromeDriverBaseTest):
chrome_paths.GetTestData())
ChromeDriverTest._sync_server = webserver.SyncWebServer()
if _ANDROID_PACKAGE_KEY:
ChromeDriverTest._adb = android_commands.AndroidCommands(
ChromeDriverTest._device = device_utils.DeviceUtils(
android_commands.GetAttachedDevices()[0])
http_host_port = ChromeDriverTest._http_server._server.server_port
sync_host_port = ChromeDriverTest._sync_server._server.server_port
forwarder.Forwarder.Map(
[(http_host_port, http_host_port), (sync_host_port, sync_host_port)],
ChromeDriverTest._adb)
ChromeDriverTest._device)
@staticmethod
def GlobalTearDown():
if _ANDROID_PACKAGE_KEY:
forwarder.Forwarder.UnmapAllDevicePorts(ChromeDriverTest._adb)
forwarder.Forwarder.UnmapAllDevicePorts(ChromeDriverTest._device)
ChromeDriverTest._http_server.Shutdown()
@staticmethod
......
......@@ -18,9 +18,9 @@ _THIS_DIR = os.path.abspath(os.path.dirname(__file__))
if util.IsLinux():
sys.path.insert(0, os.path.join(chrome_paths.GetSrc(), 'build', 'android'))
from pylib import android_commands
from pylib import forwarder
from pylib import valgrind_tools
from pylib.device import device_utils
ANDROID_TEST_HTTP_PORT = 2311
ANDROID_TEST_HTTPS_PORT = 2411
......@@ -87,22 +87,22 @@ class AndroidTestEnvironment(DesktopTestEnvironment):
def __init__(self, package, chrome_version='HEAD'):
super(AndroidTestEnvironment, self).__init__(chrome_version)
self._package = package
self._adb = None
self._device = None
self._forwarder = None
# override
def GlobalSetUp(self):
os.putenv('TEST_HTTP_PORT', str(ANDROID_TEST_HTTP_PORT))
os.putenv('TEST_HTTPS_PORT', str(ANDROID_TEST_HTTPS_PORT))
self._adb = android_commands.AndroidCommands()
self._device = device_utils.DeviceUtils(None)
forwarder.Forwarder.Map(
[(ANDROID_TEST_HTTP_PORT, ANDROID_TEST_HTTP_PORT),
(ANDROID_TEST_HTTPS_PORT, ANDROID_TEST_HTTPS_PORT)],
self._adb)
self._device)
# override
def GlobalTearDown(self):
forwarder.Forwarder.UnmapAllDevicePorts(self._adb)
forwarder.Forwarder.UnmapAllDevicePorts(self._device)
# override
def GetOS(self):
......
......@@ -18,8 +18,8 @@ from string import Template
sys.path.append(os.path.join(sys.path[0], os.pardir, os.pardir, os.pardir,
'build','android'))
from pylib import android_commands
from pylib import constants
from pylib.device import device_utils
_ENTRIES = [
......@@ -205,10 +205,10 @@ def _RunManualGraph(package_name, interval):
def _CollectStats(count):
adb = android_commands.AndroidCommands()
pid_list = adb.ExtractPid(package_name)
memdump = adb.RunShellCommand('/data/local/tmp/memdump ' +
' '.join(pid_list))
device = device_utils.DeviceUtils()
pid_list = device.old_interface.ExtractPid(package_name)
memdump = device.old_interface.RunShellCommand(
'/data/local/tmp/memdump ' + ' '.join(pid_list))
process_stats = _CollectMemoryStats(memdump,
[value for (key, value) in _ENTRIES])
for (pid, process) in zip(pid_list, process_stats):
......
......@@ -14,9 +14,9 @@ BUILD_ANDROID_DIR = os.path.join(os.path.dirname(__file__),
'build',
'android')
sys.path.append(BUILD_ANDROID_DIR)
from pylib import android_commands
from pylib import constants
from pylib import flag_changer
from pylib.device import device_utils
# Browser Constants
DEFAULT_BROWSER = 'chrome'
......@@ -84,14 +84,14 @@ def main(argv):
package = package_info.package
activity = package_info.activity
adb = android_commands.AndroidCommands(device=None)
device = device_utils.DeviceUtils(None)
adb.EnableAdbRoot()
flags = flag_changer.FlagChanger(adb, package_info.cmdline_file)
device.old_interface.EnableAdbRoot()
flags = flag_changer.FlagChanger(device, package_info.cmdline_file)
if ENABLE_TEST_INTENTS_FLAG not in flags.Get():
flags.AddFlags([ENABLE_TEST_INTENTS_FLAG])
adb.StartActivity(package, activity, action=action)
device.old_interface.StartActivity(package, activity, action=action)
if __name__ == '__main__':
sys.exit(main(sys.argv))
......@@ -13,7 +13,11 @@ def CommonChecks(input_api, output_api):
output = []
blacklist = [r'classification_rules.*']
output.extend(input_api.canned_checks.RunPylint(
input_api, output_api, black_list=blacklist))
input_api, output_api, black_list=blacklist,
extra_paths_list=[
input_api.os_path.join(input_api.PresubmitLocalPath(), '..', '..',
'build', 'android')
]))
output.extend(input_api.canned_checks.RunUnitTests(
input_api,
output_api,
......
......@@ -25,8 +25,9 @@ from memory_inspector.core import symbol
# The memory_inspector/__init__ module will add the <CHROME_SRC>/build/android
# deps to the PYTHONPATH for pylib.
from pylib import android_commands # pylint: disable=F0401
from pylib.symbols import elf_symbolizer # pylint: disable=F0401
from pylib import android_commands
from pylib.device import device_utils
from pylib.symbols import elf_symbolizer
_MEMDUMP_PREBUILT_PATH = os.path.join(constants.PROJECT_SRC,
......@@ -62,7 +63,7 @@ class AndroidBackend(backends.Backend):
device = self._devices.get(device_id)
if not device:
device = AndroidDevice(
self, android_commands.AndroidCommands(device_id))
self, device_utils.DeviceUtils(device_id))
self._devices[device_id] = device
yield device
......@@ -157,13 +158,13 @@ class AndroidDevice(backends.Device):
_SETTINGS_KEYS = {
'native_symbol_paths': 'Comma-separated list of native libs search path'}
def __init__(self, backend, adb):
def __init__(self, backend, underlying_device):
super(AndroidDevice, self).__init__(
backend=backend,
settings=backends.Settings(AndroidDevice._SETTINGS_KEYS))
self.adb = adb
self._id = adb.GetDevice()
self._name = adb.GetProductModel()
self.underlying_device = underlying_device
self._id = underlying_device.old_interface.GetDevice()
self._name = underlying_device.old_interface.GetProductModel()
self._sys_stats = None
self._last_device_stats = None
self._sys_stats_last_update = None
......@@ -172,7 +173,7 @@ class AndroidDevice(backends.Device):
def Initialize(self):
"""Starts adb root and deploys the prebuilt binaries on initialization."""
self.adb.EnableAdbRoot()
self.underlying_device.old_interface.EnableAdbRoot()
# Download (from GCS) and deploy prebuilt helper binaries on the device.
self._DeployPrebuiltOnDeviceIfNeeded(_MEMDUMP_PREBUILT_PATH,
......@@ -183,16 +184,18 @@ class AndroidDevice(backends.Device):
def IsNativeTracingEnabled(self):
"""Checks for the libc.debug.malloc system property."""
return bool(self.adb.system_properties[_DLMALLOC_DEBUG_SYSPROP])
return bool(self.underlying_device.old_interface.system_properties[
_DLMALLOC_DEBUG_SYSPROP])
def EnableNativeTracing(self, enabled):
"""Enables libc.debug.malloc and restarts the shell."""
assert(self._initialized)
prop_value = '1' if enabled else ''
self.adb.system_properties[_DLMALLOC_DEBUG_SYSPROP] = prop_value
self.underlying_device.old_interface.system_properties[
_DLMALLOC_DEBUG_SYSPROP] = prop_value
assert(self.IsNativeTracingEnabled())
# The libc.debug property takes effect only after restarting the Zygote.
self.adb.RestartShell()
self.underlying_device.old_interface.RestartShell()
def ListProcesses(self):
"""Returns a sequence of |AndroidProcess|."""
......@@ -248,7 +251,9 @@ class AndroidDevice(backends.Device):
datetime.datetime.now() - self._sys_stats_last_update <= max_ttl):
return self._sys_stats
dump_out = '\n'.join(self.adb.RunShellCommand(_PSEXT_PATH_ON_DEVICE))
dump_out = '\n'.join(
self.underlying_device.old_interface.RunShellCommand(
_PSEXT_PATH_ON_DEVICE))
stats = json.loads(dump_out)
assert(all([x in stats for x in ['cpu', 'processes', 'time', 'mem']])), (
'ps_ext returned a malformed JSON dictionary.')
......@@ -275,11 +280,13 @@ class AndroidDevice(backends.Device):
prebuilts_fetcher.GetIfChanged(local_path)
with open(local_path, 'rb') as f:
local_hash = hashlib.md5(f.read()).hexdigest()
device_md5_out = self.adb.RunShellCommand('md5 "%s"' % path_on_device)
device_md5_out = self.underlying_device.old_interface.RunShellCommand(
'md5 "%s"' % path_on_device)
if local_hash in device_md5_out:
return
self.adb.Adb().Push(local_path, path_on_device)
self.adb.RunShellCommand('chmod 755 "%s"' % path_on_device)
self.underlying_device.old_interface.Adb().Push(local_path, path_on_device)
self.underlying_device.old_interface.RunShellCommand(
'chmod 755 "%s"' % path_on_device)
@property
def name(self):
......@@ -302,7 +309,7 @@ class AndroidProcess(backends.Process):
def DumpMemoryMaps(self):
"""Grabs and parses memory maps through memdump."""
cmd = '%s %d' % (_MEMDUMP_PATH_ON_DEVICE, self.pid)
dump_out = self.device.adb.RunShellCommand(cmd)
dump_out = self.device.underlying_device.old_interface.RunShellCommand(cmd)
return memdump_parser.Parse(dump_out)
def DumpNativeHeap(self):
......@@ -310,12 +317,14 @@ class AndroidProcess(backends.Process):
# TODO(primiano): grab also mmap bt (depends on pending framework change).
dump_file_path = _DUMPHEAP_OUT_FILE_PATH % self.pid
cmd = 'am dumpheap -n %d %s' % (self.pid, dump_file_path)
self.device.adb.RunShellCommand(cmd)
self.device.underlying_device.old_interface.RunShellCommand(cmd)
# TODO(primiano): Some pre-KK versions of Android might need a sleep here
# as, IIRC, 'am dumpheap' did not wait for the dump to be completed before
# returning. Double check this and either add a sleep or remove this TODO.
dump_out = self.device.adb.GetFileContents(dump_file_path)
self.device.adb.RunShellCommand('rm %s' % dump_file_path)
dump_out = self.device.underlying_device.old_interface.GetFileContents(
dump_file_path)
self.device.underlying_device.old_interface.RunShellCommand(
'rm %s' % dump_file_path)
return dumpheap_native_parser.Parse(dump_out)
def GetStats(self):
......
......@@ -25,11 +25,12 @@ try:
from pylib import ports # pylint: disable=F0401
except Exception:
ports = None
from pylib.device import device_utils
from pylib.utils import apk_helper # pylint: disable=F0401
def IsAndroidSupported():
return android_commands != None
return device_utils != None
def GetAttachedDevices():
......@@ -52,21 +53,22 @@ class AdbCommands(object):
"""A thin wrapper around ADB"""
def __init__(self, device):
self._adb = android_commands.AndroidCommands(device)
self._device = device
self._device = device_utils.DeviceUtils(device)
self._device_serial = device
def device_serial(self):
return self._device_serial
def device(self):
return self._device
def Adb(self):
return self._adb
def __getattr__(self, name):
"""Delegate all unknown calls to the underlying _adb object."""
return getattr(self._adb, name)
"""Delegate all unknown calls to the underlying AndroidCommands object."""
return getattr(self._device.old_interface, name)
def Forward(self, local, remote):
ret = self._adb.Adb().SendCommand('forward %s %s' % (local, remote))
ret = self._device.old_interface.Adb().SendCommand(
'forward %s %s' % (local, remote))
assert ret == ''
def Install(self, apk_path):
......@@ -84,10 +86,11 @@ class AdbCommands(object):
constants.SetBuildType('Debug')
apk_package_name = apk_helper.GetPackageName(apk_path)
return self._adb.ManagedInstall(apk_path, package_name=apk_package_name)
return self._device.old_interface.ManagedInstall(
apk_path, package_name=apk_package_name)
def IsUserBuild(self):
return self._adb.GetBuildType() == 'user'
return self._device.old_interface.GetBuildType() == 'user'
def GetBuildTypeOfPath(path):
......
......@@ -86,10 +86,11 @@ class ChromeBackendSettings(AndroidBrowserBackendSettings):
profile_base = os.path.basename(profile_parent)
saved_profile_location = '/sdcard/profile/%s' % profile_base
self.adb.Adb().PushIfNeeded(new_profile_dir, saved_profile_location)
self.adb.device().old_interface.PushIfNeeded(
new_profile_dir, saved_profile_location)
self.adb.Adb().EfficientDeviceDirectoryCopy(saved_profile_location,
self.profile_dir)
self.adb.device().old_interface.EfficientDeviceDirectoryCopy(
saved_profile_location, self.profile_dir)
dumpsys = self.adb.RunShellCommand('dumpsys package %s' % self.package)
id_line = next(line for line in dumpsys if 'userId=' in line)
uid = re.search('\d+', id_line).group()
......@@ -194,7 +195,7 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
# Kill old browser.
self._adb.CloseApplication(self._backend_settings.package)
if self._adb.Adb().CanAccessProtectedFileContents():
if self._adb.device().old_interface.CanAccessProtectedFileContents():
if self.browser_options.profile_dir:
self._backend_settings.PushProfile(self.browser_options.profile_dir)
elif not self.browser_options.dont_override_profile:
......@@ -240,8 +241,8 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
def _SetCommandLineFile(self, file_contents):
logging.debug('Using command line: ' + file_contents)
def IsProtectedFile(name):
if self._adb.Adb().FileExistsOnDevice(name):
return not self._adb.Adb().IsFileWritableOnDevice(name)
if self._adb.device().old_interface.FileExistsOnDevice(name):
return not self._adb.device().old_interface.IsFileWritableOnDevice(name)
else:
parent_name = os.path.dirname(name)
if parent_name != '':
......@@ -250,19 +251,23 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
return True
if IsProtectedFile(self._backend_settings.cmdline_file):
if not self._adb.Adb().CanAccessProtectedFileContents():
if not self._adb.device().old_interface.CanAccessProtectedFileContents():
logging.critical('Cannot set Chrome command line. '
'Fix this by flashing to a userdebug build.')
sys.exit(1)
self._saved_cmdline = ''.join(self._adb.Adb().GetProtectedFileContents(
self._backend_settings.cmdline_file) or [])
self._adb.Adb().SetProtectedFileContents(
self._saved_cmdline = ''.join(
self._adb.device().old_interface.GetProtectedFileContents(
self._backend_settings.cmdline_file)
or [])
self._adb.device().old_interface.SetProtectedFileContents(
self._backend_settings.cmdline_file, file_contents)
else:
self._saved_cmdline = ''.join(self._adb.Adb().GetFileContents(
self._backend_settings.cmdline_file) or [])
self._adb.Adb().SetFileContents(self._backend_settings.cmdline_file,
file_contents)
self._saved_cmdline = ''.join(
self._adb.device().old_interface.GetFileContents(
self._backend_settings.cmdline_file)
or [])
self._adb.device().old_interface.SetFileContents(
self._backend_settings.cmdline_file, file_contents)
def Start(self):
self._SetUpCommandLine()
......@@ -275,7 +280,7 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
# If we have no existing tabs start with a blank page since default
# startup with the NTP can lead to race conditions with Telemetry
url = 'about:blank'
self._adb.Adb().DismissCrashDialogIfNeeded()
self._adb.device().old_interface.DismissCrashDialogIfNeeded()
self._adb.StartActivity(self._backend_settings.package,
self._backend_settings.activity,
True,
......@@ -291,7 +296,7 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
self._PostBrowserStartupInitialization()
except exceptions.BrowserGoneException:
logging.critical('Failed to connect to browser.')
if not self._adb.Adb().CanAccessProtectedFileContents():
if not self._adb.device().old_interface.CanAccessProtectedFileContents():
logging.critical(
'Resolve this by either: '
'(1) Flashing to a userdebug build OR '
......@@ -383,7 +388,8 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
# is fixed in android's adb_interface at 60 seconds, which may
# be too short to pull the cache.
cmd = 'pull %s %s' % (source, dest)
self._adb.Adb().Adb().SendCommand(cmd, timeout_time=240)
self._adb.device().old_interface.Adb().SendCommand(
cmd, timeout_time=240)
def IsBrowserRunning(self):
pids = self._adb.ExtractPid(self._backend_settings.package)
......@@ -415,7 +421,7 @@ class AndroidBrowserBackend(chrome_browser_backend.ChromeBrowserBackend):
if os.path.exists(tombstones):
ret += Decorate('Tombstones',
subprocess.Popen([tombstones, '-w', '--device',
self._adb.device()],
self._adb.device_serial()],
stdout=subprocess.PIPE).communicate()[0])
return ret
......
......@@ -96,7 +96,7 @@ class PossibleAndroidBrowser(possible_browser.PossibleBrowser):
@decorators.Cache
def _platform_backend(self):
return android_platform_backend.AndroidPlatformBackend(
self._backend_settings.adb.Adb(),
self._backend_settings.adb.device(),
self.finder_options.no_performance_mode)
def Create(self):
......
......@@ -52,14 +52,14 @@ class AndroidForwarder(forwarders.Forwarder):
def __init__(self, adb, port_pairs):
super(AndroidForwarder, self).__init__(port_pairs)
self._adb = adb.Adb()
forwarder.Forwarder.Map([p for p in port_pairs if p], self._adb)
self._device = adb.device()
forwarder.Forwarder.Map([p for p in port_pairs if p], self._device)
# TODO(tonyg): Verify that each port can connect to host.
def Close(self):
for port_pair in self._port_pairs:
if port_pair:
forwarder.Forwarder.UnmapDevicePort(port_pair.local_port, self._adb)
forwarder.Forwarder.UnmapDevicePort(port_pair.local_port, self._device)
super(AndroidForwarder, self).Close()
......@@ -157,9 +157,10 @@ class AndroidRndisConfigurator(object):
_TELEMETRY_INTERFACE_FILE = '/etc/network/interfaces.d/telemetry-{}.conf'
def __init__(self, adb):
is_root_enabled = adb.Adb().EnableAdbRoot()
self._device = adb.device()
is_root_enabled = self._device.old_interface.EnableAdbRoot()
assert is_root_enabled, 'RNDIS forwarding requires a rooted device.'
self._adb = adb.Adb()
self._device_ip = None
self._host_iface = None
......@@ -175,15 +176,15 @@ class AndroidRndisConfigurator(object):
def _IsRndisSupported(self):
"""Checks that the device has RNDIS support in the kernel."""
return self._adb.FileExistsOnDevice(
return self._device.old_interface.FileExistsOnDevice(
'%s/f_rndis/device' % self._RNDIS_DEVICE)
def _WaitForDevice(self):
self._adb.Adb().SendCommand('wait-for-device')
self._device.old_interface.Adb().SendCommand('wait-for-device')
def _FindDeviceRndisInterface(self):
"""Returns the name of the RNDIS network interface if present."""
config = self._adb.RunShellCommand('netcfg')
config = self._device.old_interface.RunShellCommand('netcfg')
interfaces = [line.split()[0] for line in config]
candidates = [iface for iface in interfaces if re.match('rndis|usb', iface)]
if candidates:
......@@ -200,7 +201,7 @@ class AndroidRndisConfigurator(object):
def _FindHostRndisInterface(self):
"""Returns the name of the host-side network interface."""
interface_list = self._EnumerateHostInterfaces()
ether_address = self._adb.GetFileContents(
ether_address = self._device.old_interface.GetFileContents(
'%s/f_rndis/ethaddr' % self._RNDIS_DEVICE)[0]
interface_name = None
for line in interface_list:
......@@ -214,7 +215,7 @@ class AndroidRndisConfigurator(object):
['sudo', 'bash', '-c', 'echo -e "%s" > %s' % (contents, path)])
def _DisableRndis(self):
self._adb.system_properties['sys.usb.config'] = 'adb'
self._device.old_interface.system_properties['sys.usb.config'] = 'adb'
self._WaitForDevice()
def _EnableRndis(self):
......@@ -253,12 +254,13 @@ function doit() {
doit &
""" % {'dev': self._RNDIS_DEVICE, 'functions': 'rndis,adb',
'prefix': script_prefix }
self._adb.SetFileContents('%s.sh' % script_prefix, script)
self._device.old_interface.SetFileContents('%s.sh' % script_prefix, script)
# TODO(szym): run via su -c if necessary.
self._adb.RunShellCommand('rm %s.log' % script_prefix)
self._adb.RunShellCommand('. %s.sh' % script_prefix)
self._device.old_interface.RunShellCommand('rm %s.log' % script_prefix)
self._device.old_interface.RunShellCommand('. %s.sh' % script_prefix)
self._WaitForDevice()
result = self._adb.GetFileContents('%s.log' % script_prefix)
result = self._device.old_interface.GetFileContents(
'%s.log' % script_prefix)
assert any('DONE' in line for line in result), 'RNDIS script did not run!'
def _CheckEnableRndis(self, force):
......@@ -305,15 +307,16 @@ doit &
"""Returns the IP addresses on all connected devices.
Excludes interface |excluded_iface| on the selected device.
"""
my_device = self._adb.GetDevice()
my_device = self._device.old_interface.GetDevice()
addresses = []
for device in adb_commands.GetAttachedDevices():
adb = adb_commands.AdbCommands(device).Adb()
if device == my_device:
for device_serial in adb_commands.GetAttachedDevices():
device = adb_commands.AdbCommands(device_serial).device()
if device_serial == my_device:
excluded = excluded_iface
else:
excluded = 'no interfaces excluded on other devices'
addresses += [line.split()[2] for line in adb.RunShellCommand('netcfg')
addresses += [line.split()[2]
for line in device.old_interface.RunShellCommand('netcfg')
if excluded not in line]
return addresses
......@@ -410,7 +413,7 @@ doit &
netmask = _Long2Ip(netmask)
# TODO(szym) run via su -c if necessary.
self._adb.RunShellCommand('ifconfig %s %s netmask %s up' %
self._device.old_interface.RunShellCommand('ifconfig %s %s netmask %s up' %
(device_iface, device_ip, netmask))
# Enabling the interface sometimes breaks adb.
self._WaitForDevice()
......
......@@ -41,24 +41,24 @@ _HOST_APPLICATIONS = [
class AndroidPlatformBackend(
proc_supporting_platform_backend.ProcSupportingPlatformBackend):
def __init__(self, adb, no_performance_mode):
def __init__(self, device, no_performance_mode):
super(AndroidPlatformBackend, self).__init__()
self._adb = adb
self._device = device
self._surface_stats_collector = None
self._perf_tests_setup = perf_control.PerfControl(self._adb)
self._thermal_throttle = thermal_throttle.ThermalThrottle(self._adb)
self._perf_tests_setup = perf_control.PerfControl(self._device)
self._thermal_throttle = thermal_throttle.ThermalThrottle(self._device)
self._no_performance_mode = no_performance_mode
self._raw_display_frame_rate_measurements = []
self._host_platform_backend = factory.GetPlatformBackendForCurrentOS()
self._can_access_protected_file_contents = \
self._adb.CanAccessProtectedFileContents()
self._device.old_interface.CanAccessProtectedFileContents()
power_controller = power_monitor_controller.PowerMonitorController([
monsoon_power_monitor.MonsoonPowerMonitor(),
android_ds2784_power_monitor.DS2784PowerMonitor(adb),
android_dumpsys_power_monitor.DumpsysPowerMonitor(adb),
android_ds2784_power_monitor.DS2784PowerMonitor(device),
android_dumpsys_power_monitor.DumpsysPowerMonitor(device),
])
self._powermonitor = android_temperature_monitor.AndroidTemperatureMonitor(
power_controller, adb)
power_controller, device)
self._video_recorder = None
self._video_output = None
if self._no_performance_mode:
......@@ -72,7 +72,7 @@ class AndroidPlatformBackend(
# Clear any leftover data from previous timed out tests
self._raw_display_frame_rate_measurements = []
self._surface_stats_collector = \
surface_stats_collector.SurfaceStatsCollector(self._adb)
surface_stats_collector.SurfaceStatsCollector(self._device)
self._surface_stats_collector.Start()
def StopRawDisplayFrameRateMeasurement(self):
......@@ -110,14 +110,16 @@ class AndroidPlatformBackend(
return self._thermal_throttle.HasBeenThrottled()
def GetSystemCommitCharge(self):
for line in self._adb.RunShellCommand('dumpsys meminfo', log_result=False):
for line in self._device.old_interface.RunShellCommand(
'dumpsys meminfo', log_result=False):
if line.startswith('Total PSS: '):
return int(line.split()[2]) * 1024
return 0
@decorators.Cache
def GetSystemTotalPhysicalMemory(self):
for line in self._adb.RunShellCommand('dumpsys meminfo', log_result=False):
for line in self._device.old_interface.RunShellCommand(
'dumpsys meminfo', log_result=False):
if line.startswith('Total RAM: '):
return int(line.split()[2]) * 1024
return 0
......@@ -140,16 +142,16 @@ class AndroidPlatformBackend(
This can be used to make memory measurements more stable in particular.
"""
if not android_prebuilt_profiler_helper.InstallOnDevice(
self._adb, 'purge_ashmem'):
self._device, 'purge_ashmem'):
raise Exception('Error installing purge_ashmem.')
if self._adb.RunShellCommand(
if self._device.old_interface.RunShellCommand(
android_prebuilt_profiler_helper.GetDevicePath('purge_ashmem'),
log_result=True):
return
raise Exception('Error while purging ashmem.')
def GetMemoryStats(self, pid):
memory_usage = self._adb.GetMemoryUsageForPid(pid)[0]
memory_usage = self._device.old_interface.GetMemoryUsageForPid(pid)[0]
return {'ProportionalSetSize': memory_usage['Pss'] * 1024,
'SharedDirty': memory_usage['Shared_Dirty'] * 1024,
'PrivateDirty': memory_usage['Private_Dirty'] * 1024,
......@@ -182,20 +184,21 @@ class AndroidPlatformBackend(
@decorators.Cache
def GetOSVersionName(self):
return self._adb.GetBuildId()[0]
return self._device.old_interface.GetBuildId()[0]
def CanFlushIndividualFilesFromSystemCache(self):
return False
def FlushEntireSystemCache(self):
cache = cache_control.CacheControl(self._adb)
cache = cache_control.CacheControl(self._device)
cache.DropRamCaches()
def FlushSystemCacheForDirectory(self, directory, ignoring=None):
raise NotImplementedError()
def FlushDnsCache(self):
self._adb.RunShellCommandWithSU('ndc resolver flushdefaultif')
self._device.old_interface.RunShellCommandWithSU(
'ndc resolver flushdefaultif')
def LaunchApplication(
self, application, parameters=None, elevate_privilege=False):
......@@ -207,12 +210,13 @@ class AndroidPlatformBackend(
raise NotImplementedError("elevate_privilege isn't supported on android.")
if not parameters:
parameters = ''
self._adb.RunShellCommand('am start ' + parameters + ' ' + application)
self._device.old_interface.RunShellCommand(
'am start ' + parameters + ' ' + application)
def IsApplicationRunning(self, application):
if application in _HOST_APPLICATIONS:
return self._host_platform_backend.IsApplicationRunning(application)
return len(self._adb.ExtractPid(application)) > 0
return len(self._device.old_interface.ExtractPid(application)) > 0
def CanLaunchApplication(self, application):
if application in _HOST_APPLICATIONS:
......@@ -239,7 +243,7 @@ class AndroidPlatformBackend(
if self.is_video_capture_running:
self._video_recorder.Stop()
self._video_recorder = screenshot.VideoRecorder(
self._adb, self._video_output, megabits_per_second=min_bitrate_mbps)
self._device, self._video_output, megabits_per_second=min_bitrate_mbps)
self._video_recorder.Start()
util.WaitFor(self._video_recorder.IsStarted, 5)
......@@ -323,7 +327,7 @@ class AndroidPlatformBackend(
logging.warning('%s cannot be retrieved on non-rooted device.' % fname)
return ''
return '\n'.join(
self._adb.GetProtectedFileContents(fname))
self._device.old_interface.GetProtectedFileContents(fname))
def _GetPsOutput(self, columns, pid=None):
assert columns == ['pid', 'name'] or columns == ['pid'], \
......@@ -331,7 +335,8 @@ class AndroidPlatformBackend(
command = 'ps'
if pid:
command += ' -p %d' % pid
ps = self._adb.RunShellCommand(command, log_result=False)[1:]
ps = self._device.old_interface.RunShellCommand(
command, log_result=False)[1:]
output = []
for line in ps:
data = line.split()
......
......@@ -34,6 +34,11 @@ class MockAdbCommands(object):
return []
class MockDevice(object):
def __init__(self, mock_adb_commands):
self.old_interface = mock_adb_commands
class AndroidPlatformBackendTest(unittest.TestCase):
def setUp(self):
self._stubs = system_stub.Override(android_platform_backend,
......@@ -50,7 +55,7 @@ class AndroidPlatformBackendTest(unittest.TestCase):
'4294967295 1074458624 1074463824 3197495984 3197494152 '
'1074767676 0 4612 0 38136 4294967295 0 0 17 0 0 0 0 0 0 '
'1074470376 1074470912 1102155776']
adb_valid_proc_content = MockAdbCommands(proc_stat_content, {})
adb_valid_proc_content = MockDevice(MockAdbCommands(proc_stat_content, {}))
backend = android_platform_backend.AndroidPlatformBackend(
adb_valid_proc_content, False)
cpu_stats = backend.GetCpuStats('7702')
......@@ -59,7 +64,7 @@ class AndroidPlatformBackendTest(unittest.TestCase):
@test.Disabled('chromeos')
def testGetCpuStatsInvalidPID(self):
# Mock an empty /proc/pid/stat.
adb_empty_proc_stat = MockAdbCommands([], {})
adb_empty_proc_stat = MockDevice(MockAdbCommands([], {}))
backend = android_platform_backend.AndroidPlatformBackend(
adb_empty_proc_stat, False)
cpu_stats = backend.GetCpuStats('7702')
......@@ -67,7 +72,7 @@ class AndroidPlatformBackendTest(unittest.TestCase):
@test.Disabled
def testFramesFromMp4(self):
mock_adb = MockAdbCommands([])
mock_adb = MockDevice(MockAdbCommands([]))
backend = android_platform_backend.AndroidPlatformBackend(mock_adb, False)
try:
......
......@@ -19,23 +19,23 @@ VOLTAGE = os.path.join(FUEL_GAUGE_PATH, 'voltage_now')
class DS2784PowerMonitor(power_monitor.PowerMonitor):
def __init__(self, adb):
def __init__(self, device):
super(DS2784PowerMonitor, self).__init__()
self._adb = adb
self._device = device
self._powermonitor_process_port = None
android_prebuilt_profiler_helper.InstallOnDevice(adb, 'file_poller')
android_prebuilt_profiler_helper.InstallOnDevice(device, 'file_poller')
self._file_poller_binary = android_prebuilt_profiler_helper.GetDevicePath(
'file_poller')
@decorators.Cache
def _HasFuelGauge(self):
return self._adb.FileExistsOnDevice(CHARGE_COUNTER)
return self._device.old_interface.FileExistsOnDevice(CHARGE_COUNTER)
def CanMonitorPower(self):
if not self._HasFuelGauge():
return False
if self._adb.IsDeviceCharging():
if self._device.old_interface.IsDeviceCharging():
logging.warning('Can\'t monitor power usage since device is charging.')
return False
return True
......@@ -43,15 +43,16 @@ class DS2784PowerMonitor(power_monitor.PowerMonitor):
def StartMonitoringPower(self, browser):
assert not self._powermonitor_process_port, (
'Must call StopMonitoringPower().')
self._powermonitor_process_port = int(self._adb.RunShellCommand(
'%s %d %s %s %s' % (self._file_poller_binary, SAMPLE_RATE_HZ,
CHARGE_COUNTER, CURRENT, VOLTAGE))[0])
self._powermonitor_process_port = int(
self._device.old_interface.RunShellCommand(
'%s %d %s %s %s' % (self._file_poller_binary, SAMPLE_RATE_HZ,
CHARGE_COUNTER, CURRENT, VOLTAGE))[0])
def StopMonitoringPower(self):
assert self._powermonitor_process_port, (
'StartMonitoringPower() not called.')
try:
result = '\n'.join(self._adb.RunShellCommand(
result = '\n'.join(self._device.old_interface.RunShellCommand(
'%s %d' % (self._file_poller_binary,
self._powermonitor_process_port)))
assert result, 'PowerMonitor produced no output'
......
......@@ -15,18 +15,18 @@ class DumpsysPowerMonitor(power_monitor.PowerMonitor):
consumption of a single android application. This measure uses a heuristic
and is the same information end-users see with the battery application.
"""
def __init__(self, adb):
def __init__(self, device):
"""Constructor.
Args:
adb: adb proxy.
device: DeviceUtils instance.
"""
super(DumpsysPowerMonitor, self).__init__()
self._adb = adb
self._device = device
self._browser = None
def CanMonitorPower(self):
return self._adb.CanControlUsbCharging()
return self._device.old_interface.CanControlUsbCharging()
def StartMonitoringPower(self, browser):
assert not self._browser, (
......@@ -35,18 +35,19 @@ class DumpsysPowerMonitor(power_monitor.PowerMonitor):
# Disable the charging of the device over USB. This is necessary because the
# device only collects information about power usage when the device is not
# charging.
self._adb.DisableUsbCharging()
self._device.old_interface.DisableUsbCharging()
def StopMonitoringPower(self):
assert self._browser, (
'StartMonitoringPower() not called.')
try:
self._adb.EnableUsbCharging()
self._device.old_interface.EnableUsbCharging()
# pylint: disable=W0212
package = self._browser._browser_backend.package
# By default, 'dumpsys batterystats' measures power consumption during the
# last unplugged period.
result = self._adb.RunShellCommand('dumpsys batterystats -c %s' % package)
result = self._device.old_interface.RunShellCommand(
'dumpsys batterystats -c %s' % package)
assert result, 'Dumpsys produced no output'
return DumpsysPowerMonitor.ParseSamplingOutput(package, result)
finally:
......
......@@ -13,9 +13,9 @@ class AndroidTemperatureMonitor(power_monitor.PowerMonitor):
Delegates monitoring to another PowerMonitor and adds temperature measurements
to overall results.
"""
def __init__(self, monitor, adb):
def __init__(self, monitor, device):
super(AndroidTemperatureMonitor, self).__init__()
self._adb = adb
self._device = device
self._power_monitor = monitor
self._can_monitor_with_power_monitor = None
......@@ -58,7 +58,7 @@ class AndroidTemperatureMonitor(power_monitor.PowerMonitor):
return power_data
def _GetBoardTemperatureCelsius(self):
contents = self._adb.GetFileContents(_TEMPERATURE_FILE)
contents = self._device.old_interface.GetFileContents(_TEMPERATURE_FILE)
if len(contents) > 0:
return float(contents[0])
return None
......
......@@ -62,9 +62,11 @@ class AndroidTemperatureMonitorTest(unittest.TestCase):
mock_power_monitor.ExpectCall('CanMonitorPower').WillReturn(False)
mock_adb = simple_mock.MockObject()
mock_adb.ExpectCall('GetFileContents', _).WillReturn([])
mock_device_utils = simple_mock.MockObject()
setattr(mock_device_utils, 'old_interface', mock_adb)
monitor = android_temperature_monitor.AndroidTemperatureMonitor(
mock_power_monitor, mock_adb)
mock_power_monitor, mock_device_utils)
self.assertTrue(monitor.CanMonitorPower())
monitor.StartMonitoringPower(None)
measurements = monitor.StopMonitoringPower()
......
......@@ -19,7 +19,7 @@ def GetDevicePath(profiler_binary):
@decorators.Cache
def InstallOnDevice(adb, profiler_binary):
def InstallOnDevice(device, profiler_binary):
host_path = support_binaries.FindPath(profiler_binary, 'android')
if not host_path:
logging.error('Profiler binary "%s" not found. Could not be installed',
......@@ -27,6 +27,7 @@ def InstallOnDevice(adb, profiler_binary):
return False
device_binary_path = GetDevicePath(profiler_binary)
adb.PushIfNeeded(host_path, device_binary_path)
adb.RunShellCommand('chmod 777 ' + device_binary_path)
device.old_interface.PushIfNeeded(host_path, device_binary_path)
device.old_interface.RunShellCommand('chmod 777 ' + device_binary_path)
return True
......@@ -21,7 +21,7 @@ class AndroidScreenRecordingProfiler(profiler.Profiler):
'screenshot.py'),
'--video',
'--file', self._output_path,
'--device', browser_backend.adb.device()],
'--device', browser_backend.adb.device_serial()],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
@classmethod
......
......@@ -18,7 +18,7 @@ class AndroidTraceviewProfiler(profiler.Profiler):
super(AndroidTraceviewProfiler, self).__init__(
browser_backend, platform_backend, output_path, state)
if self._browser_backend.adb.Adb().FileExistsOnDevice(
if self._browser_backend.adb.device().old_interface.FileExistsOnDevice(
self._DEFAULT_DEVICE_DIR):
self._browser_backend.adb.RunShellCommand(
'rm ' + os.path.join(self._DEFAULT_DEVICE_DIR, '*'))
......@@ -52,7 +52,7 @@ class AndroidTraceviewProfiler(profiler.Profiler):
self._browser_backend.adb.RunShellCommand('am profile %s stop' % pid)
util.WaitFor(lambda: self._FileSize(trace_file) > 0, timeout=10)
output_files.append(trace_file)
self._browser_backend.adb.Adb().Adb().Pull(
self._browser_backend.adb.device().old_interface.Adb().Pull(
self._DEFAULT_DEVICE_DIR, self._output_path)
self._browser_backend.adb.RunShellCommand(
'rm ' + os.path.join(self._DEFAULT_DEVICE_DIR, '*'))
......@@ -62,5 +62,6 @@ class AndroidTraceviewProfiler(profiler.Profiler):
return output_files
def _FileSize(self, file_name):
f = self._browser_backend.adb.Adb().ListPathContents(file_name)
f = self._browser_backend.adb.device().old_interface.ListPathContents(
file_name)
return f.get(os.path.basename(file_name), (0, ))[0]
......@@ -46,7 +46,7 @@ class JavaHeapProfiler(profiler.Profiler):
def CollectProfile(self):
self._timer.cancel()
self._DumpJavaHeap(True)
self._browser_backend.adb.Adb().Adb().Pull(
self._browser_backend.adb.device().old_interface.Adb().Pull(
self._DEFAULT_DEVICE_DIR, self._output_path)
self._browser_backend.adb.RunShellCommand(
'rm ' + os.path.join(self._DEFAULT_DEVICE_DIR, '*'))
......@@ -65,7 +65,7 @@ class JavaHeapProfiler(profiler.Profiler):
self._DumpJavaHeap(False)
def _DumpJavaHeap(self, wait_for_completion):
if not self._browser_backend.adb.Adb().FileExistsOnDevice(
if not self._browser_backend.adb.device().old_interface.FileExistsOnDevice(
self._DEFAULT_DEVICE_DIR):
self._browser_backend.adb.RunShellCommand(
'mkdir -p ' + self._DEFAULT_DEVICE_DIR)
......@@ -83,5 +83,6 @@ class JavaHeapProfiler(profiler.Profiler):
self._run_count += 1
def _FileSize(self, file_name):
f = self._browser_backend.adb.Adb().ListPathContents(file_name)
f = self._browser_backend.adb.device().old_interface.ListPathContents(
file_name)
return f.get(os.path.basename(file_name), (0, ))[0]
......@@ -35,9 +35,11 @@ class NetLogProfiler(profiler.Profiler):
# On Android pull the output file to the host.
if self._platform_backend.GetOSName() == 'android':
host_output_file = '%s.json' % self._output_path
self._browser_backend.adb.Adb().Adb().Pull(output_file, host_output_file)
self._browser_backend.adb.device().old_interface.Adb().Pull(
output_file, host_output_file)
# Clean the device
self._browser_backend.adb.Adb().RunShellCommand('rm %s' % output_file)
self._browser_backend.adb.device().old_interface.RunShellCommand(
'rm %s' % output_file)
output_file = host_output_file
print 'Net-internals log saved as %s' % output_file
print 'To view, open in chrome://net-internals'
......
......@@ -32,7 +32,7 @@ class _SingleProcessPerfProfiler(object):
if self._is_android:
perf_binary = android_prebuilt_profiler_helper.GetDevicePath(
'perf')
cmd_prefix = ['adb', '-s', browser_backend.adb.device(), 'shell',
cmd_prefix = ['adb', '-s', browser_backend.adb.device_serial(), 'shell',
perf_binary]
output_file = os.path.join('/sdcard', 'perf_profiles',
os.path.basename(output_file))
......@@ -56,10 +56,12 @@ class _SingleProcessPerfProfiler(object):
'To collect a full profile rerun with '
'"--extra-browser-args=--single-process"')
if self._is_android:
adb = self._browser_backend.adb.Adb()
perf_pids = adb.ExtractPid('perf')
adb.RunShellCommand('kill -SIGINT ' + ' '.join(perf_pids))
util.WaitFor(lambda: not adb.ExtractPid('perf'), timeout=2)
device = self._browser_backend.adb.device()
perf_pids = device.old_interface.ExtractPid('perf')
device.old_interface.RunShellCommand(
'kill -SIGINT ' + ' '.join(perf_pids))
util.WaitFor(lambda: not device.old_interface.ExtractPid('perf'),
timeout=2)
self._proc.send_signal(signal.SIGINT)
exit_code = self._proc.wait()
try:
......@@ -100,8 +102,8 @@ Try rerunning this script under sudo or setting
List of arguments to be passed to perf to point it to the created symfs.
"""
assert self._is_android
adb = self._browser_backend.adb.Adb()
adb.Adb().Pull(self._device_output_file, self._output_file)
device = self._browser_backend.adb.device()
device.old_interface.Adb().Pull(self._device_output_file, self._output_file)
symfs_dir = os.path.dirname(self._output_file)
host_app_symfs = os.path.join(symfs_dir, 'data', 'app-lib')
if not os.path.exists(host_app_symfs):
......@@ -114,7 +116,7 @@ Try rerunning this script under sudo or setting
# the one in the device, and symlink it in the host to match --symfs.
device_dir = filter(
lambda app_lib: app_lib.startswith(self._browser_backend.package),
adb.RunShellCommand('ls /data/app-lib'))
device.old_interface.RunShellCommand('ls /data/app-lib'))
os.symlink(os.path.abspath(
os.path.join(util.GetChromiumSrcDir(),
os.environ.get('CHROMIUM_OUT_DIR', 'out'),
......@@ -144,11 +146,12 @@ Try rerunning this script under sudo or setting
'libz.so',
]
for lib in common_system_libs:
adb.Adb().Pull('/system/lib/%s' % lib, host_system_symfs)
device.old_interface.Adb().Pull('/system/lib/%s' % lib,
host_system_symfs)
# Pull a copy of the kernel symbols.
host_kallsyms = os.path.join(symfs_dir, 'kallsyms')
if not os.path.exists(host_kallsyms):
adb.Adb().Pull('/proc/kallsyms', host_kallsyms)
device.old_interface.Adb().Pull('/proc/kallsyms', host_kallsyms)
return ['--kallsyms', host_kallsyms, '--symfs', symfs_dir]
def _GetStdOut(self):
......@@ -169,9 +172,9 @@ class PerfProfiler(profiler.Profiler):
self._process_profilers = []
if platform_backend.GetOSName() == 'android':
android_prebuilt_profiler_helper.InstallOnDevice(
browser_backend.adb.Adb(), 'perf')
browser_backend.adb.device(), 'perf')
# Make sure kernel pointers are not hidden.
browser_backend.adb.Adb().SetProtectedFileContents(
browser_backend.adb.device().old_interface.SetProtectedFileContents(
'/proc/sys/kernel/kptr_restrict', '0')
for pid, output_file in process_output_file_map.iteritems():
if 'zygote' in output_file:
......
......@@ -34,13 +34,13 @@ class _TCMallocHeapProfilerAndroid(object):
def _SetDeviceProperties(self, properties):
device_configured = False
# This profiler requires adb root to set properties.
self._browser_backend.adb.Adb().EnableAdbRoot()
self._browser_backend.adb.device().old_interface.EnableAdbRoot()
for values in properties.itervalues():
device_property = self._browser_backend.adb.system_properties[values[0]]
if not device_property or not device_property.strip():
self._browser_backend.adb.system_properties[values[0]] = values[1]
device_configured = True
if not self._browser_backend.adb.Adb().FileExistsOnDevice(
if not self._browser_backend.adb.device().old_interface.FileExistsOnDevice(
self._DEFAULT_DEVICE_DIR):
self._browser_backend.adb.RunShellCommand(
'mkdir -p ' + self._DEFAULT_DEVICE_DIR)
......@@ -51,7 +51,7 @@ class _TCMallocHeapProfilerAndroid(object):
raise Exception('Device required special config, run again.')
def CollectProfile(self):
self._browser_backend.adb.Adb().Adb().Pull(
self._browser_backend.adb.device().old_interface.Adb().Pull(
self._DEFAULT_DEVICE_DIR, self._output_path)
self._browser_backend.adb.RunShellCommand(
'rm ' + os.path.join(self._DEFAULT_DEVICE_DIR, '*'))
......
......@@ -30,7 +30,7 @@ class _TCPDumpProfilerAndroid(object):
self._adb.RunShellCommand('mkdir -p ' +
os.path.dirname(self._DEVICE_DUMP_FILE))
self._proc = subprocess.Popen(
['adb', '-s', self._adb.device(),
['adb', '-s', self._adb.device_serial(),
'shell', android_prebuilt_profiler_helper.GetDevicePath('tcpdump')] +
_TCP_DUMP_BASE_OPTS +
[self._DEVICE_DUMP_FILE])
......@@ -45,7 +45,8 @@ class _TCPDumpProfilerAndroid(object):
self._proc.terminate()
host_dump = os.path.join(self._output_path,
os.path.basename(self._DEVICE_DUMP_FILE))
self._adb.Adb().Adb().Pull(self._DEVICE_DUMP_FILE, host_dump)
self._adb.device().old_interface.Adb().Pull(self._DEVICE_DUMP_FILE,
host_dump)
print 'TCP dump available at: %s ' % host_dump
print 'Use Wireshark to open it.'
return host_dump
......@@ -99,7 +100,7 @@ class TCPDumpProfiler(profiler.Profiler):
browser_backend, platform_backend, output_path, state)
if platform_backend.GetOSName() == 'android':
android_prebuilt_profiler_helper.InstallOnDevice(
browser_backend.adb.Adb(), 'tcpdump')
browser_backend.adb.device(), 'tcpdump')
self._platform_profiler = _TCPDumpProfilerAndroid(
browser_backend.adb, output_path)
else:
......
......@@ -37,9 +37,11 @@ class V8Profiler(profiler.Profiler):
# On Android pull the output file to the host.
if self._platform_backend.GetOSName() == 'android':
host_output_file = '%s.log' % self._output_path
self._browser_backend.adb.Adb().Adb().Pull(output_file, host_output_file)
self._browser_backend.adb.device().old_interface.Adb().Pull(
output_file, host_output_file)
# Clean the device
self._browser_backend.adb.Adb().RunShellCommand('rm %s' % output_file)
self._browser_backend.adb.device().old_interface.RunShellCommand(
'rm %s' % output_file)
output_file = host_output_file
print 'V8 profile saved as %s' % output_file
print 'To view, open in ' \
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment