コード例 #1
0
def configure_wifi_and_airplane_mode(wifi_enabled=False):
  """Configure airplane mode and wifi on device."""
  # Airplane mode should be disabled in all cases. This can get inadvertently
  # turned on via gestures.
  adb.disable_airplane_mode()

  # Need to disable wifi before changing configuration.
  adb.disable_wifi()

  # Check if wifi needs to be enabled. If not, then no need to modify the
  # supplicant file.
  wifi_enabled = wifi_enabled or environment.get_value('WIFI', True)
  if not wifi_enabled:
    # No more work to do, we already disabled it at start.
    return

  if adb.is_gce():
    wifi_ssid = 'VirtWifi'
    wifi_password = ''
  else:
    config = db_config.get()
    if not config.wifi_ssid:
      logs.log('No wifi ssid is set, skipping wifi config.')
      return
    wifi_ssid = config.wifi_ssid
    wifi_password = config.wifi_password or ''

  adb.enable_wifi()

  # Wait 2 seconds to allow the wifi to be enabled.
  time.sleep(2)

  wifi_util_apk_path = os.path.join(
      environment.get_platform_resources_directory(), 'wifi_util.apk')
  if not adb.is_package_installed(WIFI_UTIL_PACKAGE_NAME):
    adb.install_package(wifi_util_apk_path)

  connect_wifi_command = (
      'am instrument -e method connectToNetwork -e ssid {ssid} ')
  if wifi_password:
    connect_wifi_command += '-e psk {password} '
  connect_wifi_command += '-w {call_path}'

  output = adb.run_adb_shell_command(
      connect_wifi_command.format(
          ssid=quote(wifi_ssid),
          password=quote(wifi_password),
          call_path=WIFI_UTIL_CALL_PATH))
  if 'result=true' not in output:
    logs.log_error('Failed to connect to wifi.', output=output)
コード例 #2
0
ファイル: device.py プロジェクト: shu858/clusterfuzz
def wait_for_battery_charge_if_needed():
    """Check device battery and make sure it is charged beyond minimum level and
  temperature thresholds."""
    # Battery levels are not applicable on GCE.
    if adb.is_gce():
        return

    # Make sure device is online.
    adb.wait_for_device()

    # Skip battery check if done recently.
    last_battery_check_time = persistent_cache.get_value(
        LAST_BATTERY_CHECK_TIME_KEY,
        constructor=datetime.datetime.utcfromtimestamp)
    if last_battery_check_time and not dates.time_has_expired(
            last_battery_check_time, seconds=BATTERY_CHECK_INTERVAL):
        return

    # Initialize variables.
    battery_level_threshold = environment.get_value(
        'LOW_BATTERY_LEVEL_THRESHOLD', LOW_BATTERY_LEVEL_THRESHOLD)
    battery_temperature_threshold = environment.get_value(
        'MAX_BATTERY_TEMPERATURE_THRESHOLD', MAX_BATTERY_TEMPERATURE_THRESHOLD)
    device_restarted = False

    while 1:
        battery_information = get_battery_information()
        if battery_information is None:
            logs.log_error(
                'Failed to get battery information, skipping check.')
            return

        battery_level = battery_information['level']
        battery_temperature = battery_information['temperature']
        logs.log(
            'Battery information: level (%d%%), temperature (%.1f celsius).' %
            (battery_level, battery_temperature))
        if (battery_level >= battery_level_threshold
                and battery_temperature <= battery_temperature_threshold):
            persistent_cache.set_value(LAST_BATTERY_CHECK_TIME_KEY,
                                       time.time())
            return

        logs.log('Battery in bad battery state, putting device in sleep mode.')

        if not device_restarted:
            reboot()
            adb.disable_wifi()
            device_restarted = True

        # Change thresholds to expected levels (only if they were below minimum
        # thresholds).
        if battery_level < battery_level_threshold:
            battery_level_threshold = EXPECTED_BATTERY_LEVEL
        if battery_temperature > battery_temperature_threshold:
            battery_temperature_threshold = EXPECTED_BATTERY_TEMPERATURE

        # Stopping shell should help with shutting off a lot of services that would
        # otherwise use up the battery. However, we need to turn it back on to get
        # battery status information. Also, turn off display explicitly (needed for
        # Nexus 9s).
        turn_off_display_if_needed()
        adb.stop_shell()
        time.sleep(BATTERY_CHARGE_INTERVAL)
        adb.start_shell()
コード例 #3
0
ファイル: device.py プロジェクト: shu858/clusterfuzz
def flash_to_latest_build_if_needed():
    """Wipes user data, resetting the device to original factory state."""
    if environment.get_value('LOCAL_DEVELOPMENT'):
        # Don't reimage local development devices.
        return

    run_timeout = environment.get_value('RUN_TIMEOUT')
    if run_timeout:
        # If we have a run timeout, then we are already scheduled to bail out and
        # will be probably get re-imaged. E.g. using frameworks like Tradefed.
        return

    # Check if a flash is needed based on last recorded flash time.
    last_flash_time = persistent_cache.get_value(
        LAST_FLASH_TIME_KEY, constructor=datetime.datetime.utcfromtimestamp)
    needs_flash = last_flash_time is None or dates.time_has_expired(
        last_flash_time, seconds=adb.FLASH_INTERVAL)
    if not needs_flash:
        return

    build_info = {}
    if adb.is_gce():
        adb.recreate_gce_device()
    else:
        # Physical device.
        is_google_device = google_device()
        if is_google_device is None:
            logs.log_error('Unable to query device. Reimaging failed.')
            adb.bad_state_reached()

        elif not is_google_device:
            # We can't reimage these, skip.
            logs.log('Non-Google device found, skipping reimage.')
            return

        else:
            # For Google devices.
            # Check if both |BUILD_BRANCH| and |BUILD_TARGET| environment variables
            # are set. If not, we don't have enough data for reimaging and hence
            # we bail out.
            branch = environment.get_value('BUILD_BRANCH')
            target = environment.get_value('BUILD_TARGET')
            if not target:
                # We default to userdebug configuration.
                build_params = get_build_parameters()
                if build_params:
                    target = build_params.get('target') + '-userdebug'

                    # Cache target in environment. This is also useful for cases when
                    # device is bricked and we don't have this information available.
                    environment.set_value('BUILD_TARGET', target)

            if not branch or not target:
                logs.log_warn(
                    'BUILD_BRANCH and BUILD_TARGET are not set, skipping reimage.'
                )
                return

            # Download the latest build artifact for this branch and target.
            build_info = fetch_artifact.get_latest_artifact_info(
                branch, target)
            if not build_info:
                logs.log_error(
                    'Unable to fetch information on latest build artifact for '
                    'branch %s and target %s.' % (branch, target))
                return

            # Check if our local build matches the latest build. If not, we will
            # download it.
            build_id = build_info['bid']
            target = build_info['target']
            image_directory = environment.get_value('IMAGES_DIR')
            last_build_info = persistent_cache.get_value(LAST_FLASH_BUILD_KEY)
            if not last_build_info or last_build_info['bid'] != build_id:
                # Clean up the images directory first.
                shell.remove_directory(image_directory, recreate=True)

                # We have a new build, download the build artifacts for it.
                for image_regex in FLASH_IMAGE_REGEXES:
                    image_file_path = fetch_artifact.get(
                        build_id, target, image_regex, image_directory)
                    if not image_file_path:
                        logs.log_error(
                            'Failed to download image artifact %s for '
                            'branch %s and target %s.' %
                            (image_file_path, branch, target))
                        return
                    if image_file_path.endswith('.zip'):
                        archive.unpack(image_file_path, image_directory)

            # We do one device flash at a time on one host, otherwise we run into
            # failures and device being stuck in a bad state.
            flash_lock_key_name = 'flash:%s' % socket.gethostname()
            if not locks.acquire_lock(flash_lock_key_name, by_zone=True):
                logs.log_error(
                    'Failed to acquire lock for reimaging, exiting.')
                return

            logs.log('Reimaging started.')
            logs.log('Rebooting into bootloader mode.')
            for _ in xrange(FLASH_RETRIES):
                adb.run_as_root()
                adb.run_adb_command(['reboot-bootloader'])
                time.sleep(FLASH_REBOOT_BOOTLOADER_WAIT)
                adb.run_fastboot_command(['oem', 'off-mode-charge', '0'])
                adb.run_fastboot_command(['-w', 'reboot-bootloader'])

                for partition, partition_image_filename in FLASH_IMAGE_FILES:
                    partition_image_file_path = os.path.join(
                        image_directory, partition_image_filename)
                    adb.run_fastboot_command(
                        ['flash', partition, partition_image_file_path])
                    if partition in ['bootloader', 'radio']:
                        adb.run_fastboot_command(['reboot-bootloader'])
                adb.run_fastboot_command('reboot')
                time.sleep(FLASH_REBOOT_WAIT)

                if adb.get_device_state() == 'device':
                    break
                logs.log_error('Reimaging failed, retrying.')

            locks.release_lock(flash_lock_key_name, by_zone=True)

    if adb.get_device_state() != 'device':
        logs.log_error('Unable to find device. Reimaging failed.')
        adb.bad_state_reached()

    logs.log('Reimaging finished.')

    # Reset all of our persistent keys after wipe.
    persistent_cache.delete_value(BUILD_PROP_MD5_KEY)
    persistent_cache.delete_value(LAST_TEST_ACCOUNT_CHECK_KEY)
    persistent_cache.set_value(LAST_FLASH_BUILD_KEY, build_info)
    persistent_cache.set_value(LAST_FLASH_TIME_KEY, time.time())