<commit_before>#!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""A class to keep track of devices across builds and report state."""
import logging
import optparse
import os
import smtplib
import sys
import re

from pylib import android_commands
from pylib import buildbot_report
from pylib import constants
from pylib.cmd_helper import GetCmdOutput


def DeviceInfo(serial):
  """Gathers info on a device via various adb calls.

  Args:
    serial: The serial of the attached device to construct info about.

  Returns:
    Tuple of device type, build id, report as a string, error messages, and
    boolean indicating whether or not device can be used for testing.
  """

  def AdbShellCmd(cmd):
    return GetCmdOutput('adb -s %s shell %s' % (serial, cmd),
                        shell=True).strip()

  device_type = AdbShellCmd('getprop ro.build.product')
  device_build = AdbShellCmd('getprop ro.build.id')
  device_build_type = AdbShellCmd('getprop ro.build.type')
  device_product_name = AdbShellCmd('getprop ro.product.name')

  setup_wizard_disabled = AdbShellCmd(
      'getprop ro.setupwizard.mode') == 'DISABLED'
  battery = AdbShellCmd('dumpsys battery')
  install_output = GetCmdOutput(
    ['%s/build/android/adb_install_apk.py' % constants.DIR_SOURCE_ROOT, '--apk',
     '%s/build/android/CheckInstallApk-debug.apk' % constants.DIR_SOURCE_ROOT])
  install_speed_found = re.findall('(\d+) KB/s', install_output)
  if install_speed_found:
    install_speed = int(install_speed_found[0])
  else:
    install_speed = 'Unknown'
  if 'Error' in battery:
    ac_power = 'Unknown'
    battery_level = 'Unknown'
    battery_temp = 'Unknown'
  else:
    ac_power = re.findall('AC powered: (\w+)', battery)[0]
    battery_level = int(re.findall('level: (\d+)', battery)[0])
    battery_temp = float(re.findall('temperature: (\d+)', battery)[0]) / 10
  report = ['Device %s (%s)' % (serial, device_type),
            '  Build: %s (%s)' % (device_build,
                                  AdbShellCmd('getprop ro.build.fingerprint')),
            '  Battery: %s%%' % battery_level,
            '  Battery temp: %s' % battery_temp,
            '  IMEI slice: %s' % AdbShellCmd('dumpsys iphonesubinfo '
                                             '| grep Device'
                                             "| awk '{print $4}'")[-6:],
            '  Wifi IP: %s' % AdbShellCmd('getprop dhcp.wlan0.ipaddress'),
            '  Install Speed: %s KB/s' % install_speed,
            '']

  errors = []
  if battery_level < 15:
    errors += ['Device critically low in battery. Do not use for testing.']
  if not setup_wizard_disabled and device_build_type != 'user':
    errors += ['Setup wizard not disabled. Was it provisioned correctly?']
  if device_product_name == 'mantaray' and ac_power != 'true':
    errors += ['Mantaray device not connected to AC power.']
  # TODO(navabi): Insert warning once we have a better handle of what install
  # speeds to expect. The following lines were causing too many alerts.
  # if install_speed < 500:
  #   errors += ['Device install speed too low. Do not use for testing.']

  # TODO(navabi): Determine if device status check step should fail on slow
  # install speed. The original CL caused the step to fail but was reverted
  # because it caused too many early failures. Determine if it was just flake.
  # Also, do not fail on 'Unknown' caused by offline device, because other
  # devices can still be used for tests.
  fail_step = (battery_level == 'Unknown' or battery_level >= 15)
  return device_type, device_build, '\n'.join(report), errors, fail_step


def CheckForMissingDevices(options, adb_online_devs):
  """Uses file of previous online devices to detect broken phones.

  Args:
    options: out_dir parameter of options argument is used as the base
             directory to load and update the cache file.
    adb_online_devs: A list of serial numbers of the currently visible
                     and online attached devices.
  """
  # TODO(navabi): remove this once the bug that causes different number
  # of devices to be detected between calls is fixed.
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)

  out_dir = os.path.abspath(options.out_dir)

  def ReadDeviceList(file_name):
    devices_path = os.path.join(out_dir, file_name)
    devices = []
    try:
      with open(devices_path) as f:
        devices = f.read().splitlines()
    except IOError:
      # Ignore error, file might not exist
      pass
    return devices

  def WriteDeviceList(file_name, device_list):<commit_msg>Turn off devices with low battery and don't fail device status step.<commit_after>#!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""A class to keep track of devices across builds and report state."""
import logging
import optparse
import os
import smtplib
import sys
import re

from pylib import android_commands
from pylib import buildbot_report
from pylib import constants
from pylib.cmd_helper import GetCmdOutput


def DeviceInfo(serial):
  """Gathers info on a device via various adb calls.

  Args:
    serial: The serial of the attached device to construct info about.

  Returns:
    Tuple of device type, build id, report as a string, error messages, and
    boolean indicating whether or not device can be used for testing.
  """

  def AdbShellCmd(cmd):
    return GetCmdOutput('adb -s %s shell %s' % (serial, cmd),
                        shell=True).strip()

  device_adb = android_commands.AndroidCommands(serial)

  # TODO(navabi): Replace AdbShellCmd with device_adb.
  device_type = AdbShellCmd('getprop ro.build.product')
  device_build = AdbShellCmd('getprop ro.build.id')
  device_build_type = AdbShellCmd('getprop ro.build.type')
  device_product_name = AdbShellCmd('getprop ro.product.name')

  setup_wizard_disabled = AdbShellCmd(
      'getprop ro.setupwizard.mode') == 'DISABLED'
  battery = AdbShellCmd('dumpsys battery')
  install_output = GetCmdOutput(
    ['%s/build/android/adb_install_apk.py' % constants.DIR_SOURCE_ROOT, '--apk',
     '%s/build/android/CheckInstallApk-debug.apk' % constants.DIR_SOURCE_ROOT])
  install_speed_found = re.findall('(\d+) KB/s', install_output)
  if install_speed_found:
    install_speed = int(install_speed_found[0])
  else:
    install_speed = 'Unknown'
  if 'Error' in battery:
    ac_power = 'Unknown'
    battery_level = 'Unknown'
    battery_temp = 'Unknown'
  else:
    ac_power = re.findall('AC powered: (\w+)', battery)[0]
    battery_level = int(re.findall('level: (\d+)', battery)[0])
    battery_temp = float(re.findall('temperature: (\d+)', battery)[0]) / 10
  report = ['Device %s (%s)' % (serial, device_type),
            '  Build: %s (%s)' % (device_build,
                                  AdbShellCmd('getprop ro.build.fingerprint')),
            '  Battery: %s%%' % battery_level,
            '  Battery temp: %s' % battery_temp,
            '  IMEI slice: %s' % AdbShellCmd('dumpsys iphonesubinfo '
                                             '| grep Device'
                                             "| awk '{print $4}'")[-6:],
            '  Wifi IP: %s' % AdbShellCmd('getprop dhcp.wlan0.ipaddress'),
            '  Install Speed: %s KB/s' % install_speed,
            '']

  errors = []
  if battery_level < 15:
    errors += ['Device critically low in battery. Turning off device.']
  if not setup_wizard_disabled and device_build_type != 'user':
    errors += ['Setup wizard not disabled. Was it provisioned correctly?']
  if device_product_name == 'mantaray' and ac_power != 'true':
    errors += ['Mantaray device not connected to AC power.']
  # TODO(navabi): Insert warning once we have a better handle of what install
  # speeds to expect. The following lines were causing too many alerts.
  # if install_speed < 500:
  #   errors += ['Device install speed too low. Do not use for testing.']

  # Causing the device status check step fail for slow install speed or low
  # battery currently is too disruptive to the bots (especially try bots).
  # Turn off devices with low battery and the step does not fail.
  if battery_level < 15:
    device_adb.EnableAdbRoot()
    AdbShellCmd('reboot -p')
  return device_type, device_build, '\n'.join(report), errors, True


def CheckForMissingDevices(options, adb_online_devs):
  """Uses file of previous online devices to detect broken phones.

  Args:
    options: out_dir parameter of options argument is used as the base
             directory to load and update the cache file.
    adb_online_devs: A list of serial numbers of the currently visible
                     and online attached devices.
  """
  # TODO(navabi): remove this once the bug that causes different number
  # of devices to be detected between calls is fixed.
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)

  out_dir = os.path.abspath(options.out_dir)

  def ReadDeviceList(file_name):
    devices_path = os.path.join(out_dir, file_name)
    devices = []
    try:
      with open(devices_path) as f:
        devices = f.read().splitlines()
    except IOError:
      # Ignore error, file might not exist
      pass
    return devices

  def WriteDeviceList(file_name, device_list):
{'fraction_non_alphanumeric': 0.10045420935882539, 'fraction_numerical': 0.004225203337910637, 'mean_word_length': 3.1363040629095673, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4536769', 'n_tokens_mistral': 2882, 'n_tokens_neox': 2789, 'n_words': 951}