def FinishProvisioning(device, options):
  # The lockscreen can't be disabled on user builds, so send a keyevent
  # to unlock it.
  if device.IsUserBuild():
    device.SendKeyEvent(keyevent.KEYCODE_MENU)

  if options.min_battery_level is not None:
    try:
      battery = battery_utils.BatteryUtils(device)
      battery.ChargeDeviceToLevel(options.min_battery_level)
    except device_errors.CommandFailedError:
      logging.exception('Unable to charge device to specified level.')

  if options.max_battery_temp is not None:
    try:
      battery = battery_utils.BatteryUtils(device)
      battery.LetBatteryCoolToTemperature(options.max_battery_temp)
    except device_errors.CommandFailedError:
      logging.exception('Unable to let battery cool to specified temperature.')

  def _set_and_verify_date():
    if device.build_version_sdk >= version_codes.MARSHMALLOW:
      date_format = '%m%d%H%M%Y.%S'
      set_date_command = ['date']
    else:
      date_format = '%Y%m%d.%H%M%S'
      set_date_command = ['date', '-s']
    strgmtime = time.strftime(date_format, time.gmtime())
    set_date_command.append(strgmtime)
    device.RunShellCommand(set_date_command, as_root=True, check_return=True)

    device_time = device.RunShellCommand(
        ['date', '+"%Y%m%d.%H%M%S"'], as_root=True,
        single_line=True).replace('"', '')
    device_time = datetime.datetime.strptime(device_time, "%Y%m%d.%H%M%S")
    correct_time = datetime.datetime.strptime(strgmtime, date_format)
    tdelta = (correct_time - device_time).seconds
    if tdelta <= 1:
      logging.info('Date/time successfully set on %s', device)
      return True
    else:
      logging.error('Date mismatch. Device: %s Correct: %s',
                    device_time.isoformat(), correct_time.isoformat())
      return False

  # Sometimes the date is not set correctly on the devices. Retry on failure.
  if device.IsUserBuild():
    # TODO(bpastene): Figure out how to set the date & time on user builds.
    pass
  else:
    if not timeout_retry.WaitFor(
        _set_and_verify_date, wait_period=1, max_tries=2):
      raise device_errors.CommandFailedError(
          'Failed to set date & time.', device_serial=str(device))

  props = device.RunShellCommand('getprop', check_return=True)
  for prop in props:
    logging.info('  %s', prop)
  if options.auto_reconnect:
    _PushAndLaunchAdbReboot(device, options.target)
def WaitForCharge(device, min_battery_level):
    battery = battery_utils.BatteryUtils(device)
    try:
        battery.ChargeDeviceToLevel(min_battery_level)
    except device_errors.DeviceChargingError:
        device.Reboot()
        battery.ChargeDeviceToLevel(min_battery_level)
    def StartAgentTracing(self, options, _, timeout=None):
        """Starts tracing.

    Args:
        options: Tracing options.

    Raises:
        RuntimeError: If trace already in progress.
    """
        if options.update_map or not path.isfile(options.serial_map):
            battor_device_mapping.GenerateSerialMapFile(
                options.serial_map, options.hub_types)
        self._battor_wrapper = battor_wrapper.BattorWrapper(
            target_platform=options.target,
            android_device=options.device_serial_number,
            battor_path=options.battor_path,
            battor_map_file=options.serial_map)

        dev_utils = device_utils.DeviceUtils(options.device_serial_number)
        self._battery_utils = battery_utils.BatteryUtils(dev_utils)
        self._battery_utils.SetCharging(False)
        atexit.register(_reenable_charging_if_needed, self._battery_utils)
        self._battor_wrapper.StartShell()
        self._battor_wrapper.StartTracing()
        return True
def WaitForBatteryTemperature(device, max_battery_temp):
    try:
        battery = battery_utils.BatteryUtils(device)
        battery.LetBatteryCoolToTemperature(max_battery_temp)
    except device_errors.CommandFailedError:
        logger.exception(
            'Unable to let battery cool to specified temperature.')
 def setUp(self):
   self.adb = device_utils_test._AdbWrapperMock('0123456789abcdef')
   self.device = device_utils.DeviceUtils(
       self.adb, default_timeout=10, default_retries=0)
   self.watchMethodCalls(self.call.adb, ignore=['GetDeviceSerial'])
   self.battery = battery_utils.BatteryUtils(
       self.device, default_timeout=10, default_retries=0)
Exemple #6
0
  def __init__(self, device):
    assert device, (
        'AndroidPlatformBackend can only be initialized from remote device')
    super(AndroidPlatformBackend, self).__init__(device)
    self._device = device_utils.DeviceUtils(device.device_id)
    # Trying to root the device, if possible.
    if not self._device.HasRoot():
      try:
        self._device.EnableRoot()
      except device_errors.CommandFailedError:
        logging.warning('Unable to root %s', str(self._device))
    self._can_elevate_privilege = (
        self._device.HasRoot() or self._device.NeedsSU())
    assert self._can_elevate_privilege, (
        'Android device must have root access to run Telemetry')
    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 = []
    self._device_copy_script = None
    self._power_monitor = (
        android_power_monitor_controller.AndroidPowerMonitorController([
            android_temperature_monitor.AndroidTemperatureMonitor(self._device),
            android_dumpsys_power_monitor.DumpsysPowerMonitor(
                self._battery, self),
            sysfs_power_monitor.SysfsPowerMonitor(self, standalone=True),
            android_fuelgauge_power_monitor.FuelGaugePowerMonitor(
                self._battery),
        ], self._battery))
    self._video_recorder = None
    self._system_ui = None

    _FixPossibleAdbInstability()
Exemple #7
0
 def __init__(
     self, env, test_instance, device, index, tests, retries=3, timeout=None):
   super(DeviceTestShard, self).__init__(
       env, test_instance, tests, retries, timeout)
   self._battery = battery_utils.BatteryUtils(device) if device else None
   self._device = device
   self._index = index
Exemple #8
0
  def __init__(self, device, require_root):
    assert device, (
        'AndroidPlatformBackend can only be initialized from remote device')
    super(AndroidPlatformBackend, self).__init__(device)
    self._device = device_utils.DeviceUtils(device.device_id)
    self._require_root = require_root
    if self._require_root:
      # Trying to root the device, if possible.
      if not self._device.HasRoot():
        try:
          self._device.EnableRoot()
        except device_errors.CommandFailedError:
          logging.warning('Unable to root %s', str(self._device))
      self._can_elevate_privilege = (
          self._device.HasRoot() or self._device.NeedsSU())
      assert self._can_elevate_privilege, (
          'Android device must have root access to run Telemetry')
      self._enable_performance_mode = device.enable_performance_mode
    else:
      self._enable_performance_mode = False
    self._battery = battery_utils.BatteryUtils(self._device)
    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._device_copy_script = None
    self._system_ui = None

    _FixPossibleAdbInstability()
Exemple #9
0
    def __init__(self, device, require_root):
        assert device, (
            'AndroidPlatformBackend can only be initialized from remote device'
        )
        super(AndroidPlatformBackend, self).__init__(device)
        self._device = device_utils.DeviceUtils(device.device_id)
        self._can_elevate_privilege = False
        self._require_root = require_root
        if self._require_root:
            # Trying to root the device, if possible.
            if not self._device.HasRoot():
                try:
                    self._device.EnableRoot()
                except device_errors.CommandFailedError:
                    logging.warning('Unable to root %s', str(self._device))
            self._can_elevate_privilege = (self._device.HasRoot()
                                           or self._device.NeedsSU())
            assert self._can_elevate_privilege, (
                'Android device must have root access to run Telemetry')
        self._battery = battery_utils.BatteryUtils(self._device)
        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._device_copy_script = None
        self._system_ui = None
        self._device_host_clock_offset = None
        self._video_recorder = None

        # TODO(https://crbug.com/1026296): Remove this once --chromium-output-dir
        # has a default value we can use.
        self._build_dir = util.GetUsedBuildDirectory()

        _FixPossibleAdbInstability()
Exemple #10
0
    def StartAgentTracing(self, config, timeout=None):
        """Starts tracing.

    Args:
        config: Tracing config.

    Raises:
        RuntimeError: If trace already in progress.
        AssertionError: If There is no BattOr path given and more
            than one BattOr is attached.
    """
        battor_path = self._FindBattOrPath(config)
        self._battor_wrapper = battor_wrapper.BattOrWrapper(
            target_platform=config.target,
            android_device=config.device_serial_number,
            battor_path=battor_path,
            battor_map_file=config.serial_map)

        dev_utils = device_utils.DeviceUtils(config.device_serial_number)
        self._battery_utils = battery_utils.BatteryUtils(dev_utils)
        self._battery_utils.SetCharging(False)
        atexit.register(_reenable_charging_if_needed, self._battery_utils)
        self._battor_wrapper.StartShell()
        self._battor_wrapper.StartTracing()
        return True
Exemple #11
0
    def __init__(self, device, finder_options):
        assert device, (
            'AndroidPlatformBackend can only be initialized from remote device'
        )
        super(AndroidPlatformBackend, self).__init__(device)
        self._device = device_utils.DeviceUtils(device.device_id)
        installed_prebuilt_tools = _SetupPrebuiltTools(self._device)
        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._device.HasRoot():
            try:
                self._device.EnableRoot()
            except device_errors.CommandFailedError:
                logging.warning('Unable to root %s', str(self._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 Exception:
            logging.exception('New exception caused by DeviceUtils conversion')
            raise
        self._device_copy_script = None
        self._power_monitor = (
            android_power_monitor_controller.AndroidPowerMonitorController([
                android_temperature_monitor.AndroidTemperatureMonitor(
                    self._device),
                monsoon_power_monitor.MonsoonPowerMonitor(self._device, self),
                android_dumpsys_power_monitor.DumpsysPowerMonitor(
                    self._battery, self),
                sysfs_power_monitor.SysfsPowerMonitor(self, standalone=True),
                android_fuelgauge_power_monitor.FuelGaugePowerMonitor(
                    self._battery, self),
            ], self._battery))
        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()
 def __init__(self, platform_backend):
     super(BattOrTracingAgent, self).__init__(platform_backend)
     self._platform_backend = platform_backend
     android_device = (platform_backend.device if
                       platform_backend.GetOSName() == 'android' else None)
     self._battery = (battery_utils.BatteryUtils(platform_backend.device) if
                      platform_backend.GetOSName() == 'android' else None)
     self._battor = battor_wrapper.BattorWrapper(
         platform_backend.GetOSName(), android_device=android_device)
def _BatteryStatus(device, denylist):
  battery_info = {}
  try:
    battery = battery_utils.BatteryUtils(device)
    battery_info = battery.GetBatteryInfo(timeout=5)
    battery_level = int(battery_info.get('level', 100))

    if battery_level < 15:
      logger.error('Critically low battery level (%d)', battery_level)
      battery = battery_utils.BatteryUtils(device)
      if not battery.GetCharging():
        battery.SetCharging(True)
      if denylist:
        denylist.Extend([device.adb.GetDeviceSerial()], reason='low_battery')

  except (device_errors.CommandFailedError,
          device_errors.DeviceUnreachableError):
    logger.exception('Failed to get battery information for %s', str(device))

  return battery_info
def _BatteryStatus(device, blacklist):
  battery_info = {}
  try:
    battery = battery_utils.BatteryUtils(device)
    battery_info = battery.GetBatteryInfo(timeout=5)
    battery_level = int(battery_info.get('level', 100))

    if battery_level < 15:
      logging.error('Critically low battery level (%d)', battery_level)
      battery = battery_utils.BatteryUtils(device)
      if not battery.GetCharging():
        battery.SetCharging(True)
      if blacklist:
        blacklist.Extend([device.adb.GetDeviceSerial()])

  except device_errors.CommandFailedError:
    logging.exception('Failed to get battery information for %s',
                      str(device))

  return battery_info
Exemple #15
0
 def __init__(self, platform_backend):
     super(BattOrTracingAgent, self).__init__(platform_backend)
     self._platform_backend = platform_backend
     android_device = (platform_backend.device if
                       platform_backend.GetOSName() == 'android' else None)
     self._battery = (battery_utils.BatteryUtils(platform_backend.device) if
                      platform_backend.GetOSName() == 'android' else None)
     self._battor = battor_wrapper.BattorWrapper(
         platform_backend.GetOSName(),
         android_device=android_device,
         serial_log_bucket=cloud_storage.TELEMETRY_OUTPUT)
    def usable_devices(self, executive):
        if self._usable_devices:
            return self._usable_devices

        if self._default_devices:
            self._usable_devices = [
                device_utils.DeviceUtils(d)
                for d in self._default_devices]
            return self._usable_devices

        devices = device_utils.DeviceUtils.HealthyDevices()
        self._usable_devices = [
            d for d in devices
            if (battery_utils.BatteryUtils(d).GetBatteryInfo().get('level', 0)
                >= AndroidDevices.MINIMUM_BATTERY_PERCENTAGE
                and d.IsScreenOn())]

        return self._usable_devices
Exemple #17
0
    def testComposition(self, _):
        class P1(power_monitor.PowerMonitor):
            def StartMonitoringPower(self, browser):
                raise NotImplementedError()

            def StopMonitoringPower(self):
                raise NotImplementedError()

        class P2(power_monitor.PowerMonitor):
            def __init__(self, value):
                super(P2, self).__init__()
                self._value = {'P2': value}

            def CanMonitorPower(self):
                return True

            def StartMonitoringPower(self, browser):
                pass

            def StopMonitoringPower(self):
                return self._value

        class P3(power_monitor.PowerMonitor):
            def __init__(self, value):
                super(P3, self).__init__()
                self._value = {'P3': value}

            def CanMonitorPower(self):
                return True

            def StartMonitoringPower(self, browser):
                pass

            def StopMonitoringPower(self):
                return self._value

        battery = battery_utils.BatteryUtils(None)
        controller = power_monitor_controller.PowerMonitorController(
            [P1(), P2(1), P3(2)], battery)
        self.assertEqual(controller.CanMonitorPower(), True)
        controller.StartMonitoringPower(None)
        controller_returns = controller.StopMonitoringPower()
        self.assertEqual(controller_returns['P2'], 1)
        self.assertEqual(controller_returns['P3'], 2)
Exemple #18
0
    def __init__(self, test_options, device, shard_index, max_shard, tests,
                 flaky_tests):
        """A TestRunner instance runs a perf test on a single device.

    Args:
      test_options: A PerfOptions object.
      device: Device to run the tests.
      shard_index: the index of this device.
      max_shards: the maximum shard index.
      tests: a dict mapping test_name to command.
      flaky_tests: a list of flaky test_name.
    """
        super(TestRunner, self).__init__(device, None)
        self._options = test_options
        self._shard_index = shard_index
        self._max_shard = max_shard
        self._tests = tests
        self._flaky_tests = flaky_tests
        self._output_dir = None
        self._device_battery = battery_utils.BatteryUtils(self.device)
Exemple #19
0
def get_device_status_unsafe(device):
  """Polls the given device for various info.

    Returns: A dict of the following format:
    {
      'battery': {
        'level': 100,
        'temperature': 123
      },
      'build': {
        'build.id': 'ABC12D',
        'product.device': 'chickenofthesea'
      },
      'imei': 123456789,
      'mem': {
        'avail': 1000000,
        'total': 1234567,
      },
      'processes': 123,
      'state': 'good',
      'temp': {
        'some_sensor': 30
      },
      'uptime': 1234.56,
    }
  """
  status = collections.defaultdict(dict)

  # Battery
  battery = battery_utils.BatteryUtils(device)
  battery_info = battery.GetBatteryInfo()
  try:
    level = int(battery_info.get('level'))
  except (KeyError, TypeError, ValueError):
    level = None
  if level and level >= 0 and level <= 100:
    status['battery']['level'] = level
  try:
    temperature = int(battery_info.get('temperature'))
  except (KeyError, TypeError, ValueError):
    temperature = None
  if temperature:
    status['battery']['temperature'] = temperature

  # Build
  status['build']['build.id'] = device.build_id
  status['build']['product.device'] = device.build_product

  # Memory
  mem_info = ''
  try:
    mem_info = device.ReadFile('/proc/meminfo')
  except device_errors.AdbShellCommandFailedError:
    logging.exception('Unable to read /proc/meminfo')
  for line in mem_info.splitlines():
    match = MEM_INFO_REGEX.match(line)
    if match:
      try:
        value = int(match.group(1))
      except ValueError:
        continue
      key = line.split(':')[0].strip()
      if 'MemTotal' == key:
        status['mem']['total'] = value
      elif 'MemFree' == key:
        status['mem']['free'] = value

  # Process
  try:
    status['processes'] = len(device.ListProcesses())
  except device_errors.AdbCommandFailedError:
    logging.exception('Unable to count process list.')

  # CPU Temps
  # Find a thermal sensor that matches one in CPU_TEMP_SENSORS and read its
  # temperature.
  files = []
  try:
    files = device.RunShellCommand(
        'grep -lE "%s" /sys/class/thermal/thermal_zone*/type' % '|'.join(
            CPU_TEMP_SENSORS), shell=True, check_return=True)
  except device_errors.AdbShellCommandFailedError:
    logging.exception('Unable to list thermal sensors.')
  for f in files:
    try:
      sensor_name = device.ReadFile(f).strip()
      temp = float(device.ReadFile(f[:-4] + 'temp').strip()) # s/type^/temp
      status['temp'][sensor_name] = temp
    except (device_errors.AdbShellCommandFailedError, ValueError):
      logging.exception('Unable to read thermal sensor %s', f)

  # Uptime
  try:
    uptimes = device.ReadFile('/proc/uptime').split()
    status['uptime'] = float(uptimes[0]) # Take the first field (actual uptime)
  except (device_errors.AdbShellCommandFailedError, ValueError):
    logging.exception('Unable to read /proc/uptime')

  try:
    status['imei'] = device.GetIMEI()
  except device_errors.CommandFailedError:
    logging.exception('Unable to read IMEI')
    status['imei'] = 'unknown'

  status['state'] = 'available'
  return status
Exemple #20
0
 def testReenableCharingIfNeeded(self, mock_battery):
     battery = battery_utils.BatteryUtils(None)
     battery.GetCharging.return_value = False
     power_monitor_controller._ReenableChargingIfNeeded(battery)
 def testInitWithDeviceUtil(self):
     serial = '0fedcba987654321'
     d = device_utils.DeviceUtils(serial)
     b = battery_utils.BatteryUtils(d)
     self.assertEqual(d, b._device)
Exemple #22
0
def FinishProvisioning(device, options):
  # The lockscreen can't be disabled on user builds, so send a keyevent
  # to unlock it.
  if device.IsUserBuild():
    device.SendKeyEvent(keyevent.KEYCODE_MENU)

  if options.min_battery_level is not None:
    battery = battery_utils.BatteryUtils(device)
    try:
      battery.ChargeDeviceToLevel(options.min_battery_level)
    except device_errors.DeviceChargingError:
      device.Reboot()
      battery.ChargeDeviceToLevel(options.min_battery_level)

  if options.max_battery_temp is not None:
    try:
      battery = battery_utils.BatteryUtils(device)
      battery.LetBatteryCoolToTemperature(options.max_battery_temp)
    except device_errors.CommandFailedError:
      logging.exception('Unable to let battery cool to specified temperature.')

  def _set_and_verify_date():
    if device.build_version_sdk >= version_codes.MARSHMALLOW:
      date_format = '%m%d%H%M%Y.%S'
      set_date_command = ['date', '-u']
      get_date_command = ['date', '-u']
    else:
      date_format = '%Y%m%d.%H%M%S'
      set_date_command = ['date', '-s']
      get_date_command = ['date']

    # TODO(jbudorick): This is wrong on pre-M devices -- get/set are
    # dealing in local time, but we're setting based on GMT.
    strgmtime = time.strftime(date_format, time.gmtime())
    set_date_command.append(strgmtime)
    device.RunShellCommand(set_date_command, as_root=True, check_return=True)

    get_date_command.append('+"%Y%m%d.%H%M%S"')
    device_time = device.RunShellCommand(
        get_date_command, as_root=True, single_line=True).replace('"', '')
    device_time = datetime.datetime.strptime(device_time, "%Y%m%d.%H%M%S")
    correct_time = datetime.datetime.strptime(strgmtime, date_format)
    tdelta = (correct_time - device_time).seconds
    if tdelta <= 1:
      logging.info('Date/time successfully set on %s', device)
      return True
    else:
      logging.error('Date mismatch. Device: %s Correct: %s',
                    device_time.isoformat(), correct_time.isoformat())
      return False

  if options.disable_selinux:
    device.RunShellCommand("su -c setenforce 0", as_root=True)
  if options.force_battery_status:
    device.RunShellCommand("dumpsys battery set status 5", as_root=True)
    device.RunShellCommand("dumpsys battery set level 100", as_root=True)

  if options.disable_predictive_keyboard:
    DisablePredictiveKeyboard(device)

  # Sometimes the date is not set correctly on the devices. Retry on failure.
  if device.IsUserBuild():
    # TODO(bpastene): Figure out how to set the date & time on user builds.
    pass
  else:
    # FIXME: Some samsung devices can not set the date and time. so we skip this.
    if False and not timeout_retry.WaitFor(_set_and_verify_date, wait_period=1,
                                 max_tries=2):
      raise device_errors.CommandFailedError(
          'Failed to set date & time.', device_serial=str(device))

  props = device.RunShellCommand('getprop', check_return=True)
  for prop in props:
    logging.info('  %s', prop)
  if options.auto_reconnect:
    _PushAndLaunchAdbReboot(device, options.target)
 def testInitWithMissing_fails(self):
     with self.assertRaises(TypeError):
         battery_utils.BatteryUtils(None)
     with self.assertRaises(TypeError):
         battery_utils.BatteryUtils('')
    presentation.device.RunShellCommand(
        ['chmod', '644', presentation.device.LOCAL_PROPERTIES_PATH],
        as_root=True, check_return=True)
  except device_errors.CommandFailedError:
    logger.exception('Failed to configure local properties.')


def FinishProvisioning(presentation.device):
  # The lockscreen can't be disabled on user builds, so send a keyevent
  # to unlock it.
  if presentation.device.IsUserBuild():
    presentation.device.SendKeyEvent(keyevent.KEYCODE_MENU)


def WaitForCharge(presentation.device, min_battery_level):
  battery = battery_utils.BatteryUtils(presentation.device)
  try:
    battery.ChargeDeviceToLevel(min_battery_level)
  except device_errors.DeviceChargingError:
    presentation.device.Reboot()
    battery.ChargeDeviceToLevel(min_battery_level)


def WaitForTemperature(presentation.device, max_battery_temp):
  try:
    battery = battery_utils.BatteryUtils(presentation.device)
    battery.LetBatteryCoolToTemperature(max_battery_temp)
  except device_errors.CommandFailedError:
    logger.exception('Unable to let battery cool to specified temperature.')