def __init__(self, device, finder_options):
        assert device, (
            'AndroidPlatformBackend can only be initialized from remote device'
        )
        super(AndroidPlatformBackend, self).__init__(device)
        self._adb = adb_commands.AdbCommands(device=device.device_id)
        installed_prebuilt_tools = adb_commands.SetupPrebuiltTools(self._adb)
        if not installed_prebuilt_tools:
            logging.error(
                '%s detected, however prebuilt android tools could not '
                'be used. To run on Android you must build them first:\n'
                '  $ ninja -C out/Release android_tools' % device.name)
            raise exceptions.PlatformError()
        # Trying to root the device, if possible.
        if not self._adb.IsRootEnabled():
            # Ignore result.
            self._adb.EnableAdbRoot()
        self._device = self._adb.device()
        self._battery = battery_utils.BatteryUtils(self._device)
        self._enable_performance_mode = device.enable_performance_mode
        self._surface_stats_collector = None
        self._perf_tests_setup = perf_control.PerfControl(self._device)
        self._thermal_throttle = thermal_throttle.ThermalThrottle(self._device)
        self._raw_display_frame_rate_measurements = []
        try:
            self._can_access_protected_file_contents = (self._device.HasRoot()
                                                        or
                                                        self._device.NeedsSU())
        except:
            logging.exception('New exception caused by DeviceUtils conversion')
            raise
        self._device_copy_script = None
        power_controller = power_monitor_controller.PowerMonitorController([
            monsoon_power_monitor.MonsoonPowerMonitor(self._device, self),
            android_ds2784_power_monitor.DS2784PowerMonitor(
                self._device, self),
            android_dumpsys_power_monitor.DumpsysPowerMonitor(
                self._battery, self),
        ])
        self._power_monitor = android_temperature_monitor.AndroidTemperatureMonitor(
            power_controller, self._device)
        self._video_recorder = None
        self._installed_applications = None

        self._wpr_ca_cert_path = None
        self._device_cert_util = None
        self._is_test_ca_installed = False

        self._use_rndis_forwarder = (
            finder_options.android_rndis
            or finder_options.browser_options.netsim
            or platform.GetHostPlatform().GetOSName() != 'linux')

        _FixPossibleAdbInstability()
Exemple #2
0
 def _GetDeviceAddresses(self, excluded_iface):
     """Returns the IP addresses on all connected devices.
 Excludes interface |excluded_iface| on the selected device.
 """
     my_device = self._adb.GetDevice()
     addresses = []
     for device in adb_commands.GetAttachedDevices():
         adb = adb_commands.AdbCommands(device).Adb()
         if device == my_device:
             excluded = excluded_iface
         else:
             excluded = 'no interfaces excluded on other devices'
         addresses += [
             line.split()[2] for line in adb.RunShellCommand('netcfg')
             if excluded not in line
         ]
     return addresses
Exemple #3
0
    def testSetUpCommandLineFlagsCmdRemoved(self):
        """Test that the command line file is removed if it did not exist before.

    Requires a device connected to the host.
    """
        serial = adb_commands.GetAttachedDevices()[0]
        cmd_file = '/data/local/tmp/test_cmd'
        adb = adb_commands.AdbCommands(device=serial)
        backend_settings = _MockBackendSettings('/data/local/tmp/test_cmd')
        startup_args = ['--some', '--test', '--args']
        device = adb.device()
        device.RunShellCommand(['rm', '-f', cmd_file], check_return=True)
        with android_command_line_backend.SetUpCommandLineFlags(
                adb, backend_settings, startup_args):
            self.assertEqual('chrome --some --test --args',
                             device.ReadFile(cmd_file).strip())
        self.assertFalse(device.FileExists(cmd_file))
Exemple #4
0
    def testSetUpCommandLineFlagsCmdRestored(self):
        """Test that a previous command line file is restored.

    Requires a device connected to the host.
    """
        serial = options_for_unittests.GetCopy().device
        if not serial:
            serial = adb_commands.GetAttachedDevices()[0]
        cmd_file = '/data/local/tmp/test_cmd'
        adb = adb_commands.AdbCommands(device=serial)
        backend_settings = _MockBackendSettings('/data/local/tmp/test_cmd')
        startup_args = ['--some', '--test', '--args']
        device = adb.device()
        device.WriteFile(cmd_file, 'chrome --args --to --save')
        with android_command_line_backend.SetUpCommandLineFlags(
                adb, backend_settings, startup_args):
            self.assertEqual('chrome --some --test --args',
                             device.ReadFile(cmd_file).strip())
        self.assertEqual('chrome --args --to --save',
                         device.ReadFile(cmd_file).strip())
        device.RunShellCommand(['rm', '-f', cmd_file], check_return=True)
Exemple #5
0
    def __init__(self, device):
        assert device, (
            'AndroidPlatformBackend can only be initialized from remote device'
        )
        super(AndroidPlatformBackend, self).__init__(device)
        self._adb = adb_commands.AdbCommands(device=device.device_id)
        installed_prebuilt_tools = adb_commands.SetupPrebuiltTools(self._adb)
        if not installed_prebuilt_tools:
            logging.error(
                '%s detected, however prebuilt android tools could not '
                'be used. To run on Android you must build them first:\n'
                '  $ ninja -C out/Release android_tools' % device.name)
            raise exceptions.PlatformError()
        # Trying to root the device, if possible.
        if not self._adb.IsRootEnabled():
            # Ignore result.
            self._adb.EnableAdbRoot()
        self._device = self._adb.device()
        self._enable_performance_mode = device.enable_performance_mode
        self._surface_stats_collector = None
        self._perf_tests_setup = perf_control.PerfControl(self._device)
        self._thermal_throttle = thermal_throttle.ThermalThrottle(self._device)
        self._raw_display_frame_rate_measurements = []
        self._can_access_protected_file_contents = \
            self._device.old_interface.CanAccessProtectedFileContents()
        power_controller = power_monitor_controller.PowerMonitorController([
            monsoon_power_monitor.MonsoonPowerMonitor(self._device, self),
            android_ds2784_power_monitor.DS2784PowerMonitor(
                self._device, self),
            android_dumpsys_power_monitor.DumpsysPowerMonitor(
                self._device, self),
        ])
        self._power_monitor = android_temperature_monitor.AndroidTemperatureMonitor(
            power_controller, self._device)
        self._video_recorder = None
        self._installed_applications = None

        self._wpr_ca_cert_path = None
        self._device_cert_util = None
        self._is_test_ca_installed = False
Exemple #6
0
def FindAllAvailableBrowsers(finder_options, logging=real_logging):
    """Finds all the desktop browsers available on this machine."""
    if not CanFindAvailableBrowsers(logging=logging):
        logging.info('No adb command found. ' +
                     'Will not try searching for Android browsers.')
        return []

    device = None
    if finder_options.android_device:
        devices = [finder_options.android_device]
    else:
        devices = adb_commands.GetAttachedDevices()

    if len(devices) == 0:
        logging.info('No android devices found.')
        return []

    if len(devices) > 1:
        logging.warn(
            'Multiple devices attached. Please specify one of the following:\n'
            + '\n'.join(['  --device=%s' % d for d in devices]))
        return []

    device = devices[0]

    adb = adb_commands.AdbCommands(device=device)

    if sys.platform.startswith('linux'):
        # Host side workaround for crbug.com/268450 (adb instability)
        # The adb server has a race which is mitigated by binding to a single core.
        import psutil  # pylint: disable=F0401
        pids = [p.pid for p in psutil.process_iter() if 'adb' in p.name]
        with open(os.devnull, 'w') as devnull:
            for pid in pids:
                ret = subprocess.call(['taskset', '-p', '-c', '0',
                                       str(pid)],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      stdin=devnull)
                if ret:
                    logging.warn('Failed to taskset %d (%s)', pid, ret)

        if not os.environ.get('BUILDBOT_BUILDERNAME'):
            # Killing adbd before running tests has proven to make them less likely to
            # flake out during the test. We skip this if Telemetry is running under a
            # buildbot because build/android/test_runner.py wrapper already took care
            # of it before starting the shards.
            adb_commands.CleanupLeftoverProcesses()

    packages = adb.RunShellCommand('pm list packages')
    possible_browsers = []

    for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
        [package, backend_settings, local_apk] = package_info
        b = PossibleAndroidBrowser(name, finder_options,
                                   backend_settings(adb, package), local_apk)

        if 'package:' + package in packages or b.HaveLocalAPK():
            possible_browsers.append(b)

    if possible_browsers:
        installed_prebuilt_tools = adb_commands.SetupPrebuiltTools(adb)
        if not installed_prebuilt_tools:
            logging.error(
                'Android device detected, however prebuilt android tools could not '
                'be used. To run on Android you must build them first:\n'
                '  $ ninja -C out/Release android_tools')
            return []

    return possible_browsers
Exemple #7
0
def FindAllAvailableBrowsers(finder_options, logging=real_logging):
    """Finds all the desktop browsers available on this machine."""
    if not CanFindAvailableBrowsers(logging=logging):
        logging.info('No adb command found. ' +
                     'Will not try searching for Android browsers.')
        return []

    device = None
    if finder_options.android_device:
        devices = [finder_options.android_device]
    else:
        devices = adb_commands.GetAttachedDevices()

    if len(devices) == 0:
        logging.info('No android devices found.')
        return []

    if len(devices) > 1:
        logging.warn('Multiple devices attached. ' +
                     'Please specify a device explicitly.')
        return []

    device = devices[0]

    adb = adb_commands.AdbCommands(device=device)

    if sys.platform.startswith('linux'):
        # Host side workaround for crbug.com/268450 (adb instability)
        # The adb server has a race which is mitigated by binding to a single core.
        import psutil  # pylint: disable=F0401
        pids = [p.pid for p in psutil.process_iter() if 'adb' in p.name]
        with open(os.devnull, 'w') as devnull:
            for pid in pids:
                ret = subprocess.call(['taskset', '-p', '-c', '0',
                                       str(pid)],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      stdin=devnull)
                if ret:
                    logging.warn('Failed to taskset %d (%s)', pid, ret)

        # Experimental device side workaround for crbug.com/268450 (adb instability)
        # The /sbin/adbd process on the device appears to hang which causes adb to
        # report that the device is offline. Our working theory is that killing
        # the process and allowing it to be automatically relaunched will allow us
        # to run for longer before it hangs.
        if not finder_options.keep_test_server_ports:
            # This would break forwarder connections, so we cannot do this if
            # instructed to keep server ports open.
            logging.info('Killing adbd on device')
            adb.KillAll('adbd')
            logging.info('Waiting for adbd to restart')
            adb.Adb().Adb().SendCommand('wait-for-device')

    packages = adb.RunShellCommand('pm list packages')
    possible_browsers = []

    for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
        [package, backend_settings, local_apk] = package_info
        b = PossibleAndroidBrowser(name, finder_options,
                                   backend_settings(adb, package), local_apk)

        if 'package:' + package in packages or b.HaveLocalAPK():
            possible_browsers.append(b)

    # See if the "forwarder" is installed -- we need this to host content locally
    # but make it accessible to the device.
    if (len(possible_browsers) and not finder_options.android_rndis
            and not adb_commands.HasForwarder()):
        logging.warn('telemetry detected an android device. However,')
        logging.warn('Chrome\'s port-forwarder app is not available.')
        logging.warn(
            'Falling back to prebuilt binaries, but to build locally: ')
        logging.warn('  ninja -C out/Release forwarder2 md5sum')
        logging.warn('')
        logging.warn('')
        if not adb_commands.SetupPrebuiltTools(device):
            return []
    return possible_browsers
Exemple #8
0
def GetAdb():
    devices = adb_commands.GetAttachedDevices()
    assert len(devices) == 1
    adb = adb_commands.AdbCommands(devices[0])
    adb_commands.SetupPrebuiltTools(adb)
    return adb
Exemple #9
0
def FindAllAvailableBrowsers(finder_options, logging=real_logging):
  """Finds all the desktop browsers available on this machine."""
  if not CanFindAvailableBrowsers(logging=logging):
    logging.info('No adb command found. ' +
                 'Will not try searching for Android browsers.')
    return []

  def _GetDevices():
    if finder_options.android_device:
      return [finder_options.android_device]
    else:
      return adb_commands.GetAttachedDevices()

  devices = _GetDevices()

  if not devices:
    try:
      m = monsoon.Monsoon(wait=False)
      m.SetUsbPassthrough(1)
      m.SetVoltage(3.8)
      m.SetMaxCurrent(8)
      logging.warn("""
Monsoon power monitor detected, but no Android devices.

The Monsoon's power output has been enabled. Please now ensure that:

  1. The Monsoon's front and back USB are connected to the host.
  2. The Device is connected to the Monsoon's main and USB channels.
  3. The Device is turned on.

Waiting for device...
""")
      util.WaitFor(_GetDevices, 600)
      devices = _GetDevices()
      if not devices:
        raise IOError()
    except IOError:
      logging.info('No android devices found.')
      return []

  if len(devices) > 1:
    logging.warn(
        'Multiple devices attached. Please specify one of the following:\n' +
        '\n'.join(['  --device=%s' % d for d in devices]))
    return []

  device = devices[0]

  adb = adb_commands.AdbCommands(device=device)
  # Trying to root the device, if possible.
  if not adb.IsRootEnabled():
    # Ignore result.
    adb.EnableAdbRoot()

  if psutil:
    # Host side workaround for crbug.com/268450 (adb instability).
    # The adb server has a race which is mitigated by binding to a single core.
    for proc in psutil.process_iter():
      try:
        if 'adb' in proc.name:
          if 'cpu_affinity' in dir(proc):
            proc.cpu_affinity([0])      # New versions of psutil.
          elif 'set_cpu_affinity' in dir(proc):
            proc.set_cpu_affinity([0])  # Older versions.
          else:
            logging.warn(
                'Cannot set CPU affinity due to stale psutil version: %s',
                '.'.join(str(x) for x in psutil.version_info))
      except (psutil.NoSuchProcess, psutil.AccessDenied):
        logging.warn('Failed to set adb process CPU affinity')

  if not os.environ.get('BUILDBOT_BUILDERNAME'):
    # Killing adbd before running tests has proven to make them less likely to
    # flake out during the test. We skip this if Telemetry is running under a
    # buildbot because build/android/test_runner.py wrapper already took care
    # of it before starting the shards.
    adb.RestartAdbdOnDevice()

  packages = adb.RunShellCommand('pm list packages')
  possible_browsers = []

  for name, package_info in CHROME_PACKAGE_NAMES.iteritems():
    [package, backend_settings, local_apk] = package_info
    b = PossibleAndroidBrowser(
        name,
        finder_options,
        backend_settings(adb, package),
        local_apk)

    if 'package:' + package in packages or b.HaveLocalAPK():
      possible_browsers.append(b)

  if possible_browsers:
    installed_prebuilt_tools = adb_commands.SetupPrebuiltTools(adb)
    if not installed_prebuilt_tools:
      logging.error(
          'Android device detected, however prebuilt android tools could not '
          'be used. To run on Android you must build them first:\n'
          '  $ ninja -C out/Release android_tools')
      return []

  return possible_browsers
Exemple #10
0
 def _SetupAdbCommands(self):
   serial = adb_commands.GetAttachedDevices()[0]
   self.adb = adb_commands.AdbCommands(device=serial)
   self.device = self.adb.device()
Exemple #11
0
 def __init__(self, application, database):
   self._serial = adb_commands.GetAttachedDevices()[0]
   self._adb = adb_commands.AdbCommands(device=self._serial)
   self._device = self._adb.device()
   self._db = '/data/data/%s/databases/%s' % (application, database)