Home | History | Annotate | Download | only in android
      1 #!/usr/bin/env python
      2 #
      3 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
      4 # Use of this source code is governed by a BSD-style license that can be
      5 # found in the LICENSE file.
      6 
      7 """Provisions Android devices with settings required for bots.
      8 
      9 Usage:
     10   ./provision_devices.py [-d <device serial number>]
     11 """
     12 
     13 import logging
     14 import optparse
     15 import os
     16 import re
     17 import subprocess
     18 import sys
     19 import time
     20 
     21 from pylib import android_commands
     22 from pylib import constants
     23 from pylib import device_settings
     24 from pylib.device import device_utils
     25 
     26 sys.path.append(os.path.join(constants.DIR_SOURCE_ROOT,
     27                              'third_party', 'android_testrunner'))
     28 import errors
     29 
     30 def KillHostHeartbeat():
     31   ps = subprocess.Popen(['ps', 'aux'], stdout = subprocess.PIPE)
     32   stdout, _ = ps.communicate()
     33   matches = re.findall('\\n.*host_heartbeat.*', stdout)
     34   for match in matches:
     35     print 'An instance of host heart beart running... will kill'
     36     pid = re.findall('(\d+)', match)[1]
     37     subprocess.call(['kill', str(pid)])
     38 
     39 
     40 def LaunchHostHeartbeat():
     41   # Kill if existing host_heartbeat
     42   KillHostHeartbeat()
     43   # Launch a new host_heartbeat
     44   print 'Spawning host heartbeat...'
     45   subprocess.Popen([os.path.join(constants.DIR_SOURCE_ROOT,
     46                                  'build/android/host_heartbeat.py')])
     47 
     48 
     49 def PushAndLaunchAdbReboot(devices, target):
     50   """Pushes and launches the adb_reboot binary on the device.
     51 
     52   Arguments:
     53     devices: The list of serial numbers of the device to which the
     54              adb_reboot binary should be pushed.
     55     target : The build target (example, Debug or Release) which helps in
     56              locating the adb_reboot binary.
     57   """
     58   for device_serial in devices:
     59     print 'Will push and launch adb_reboot on %s' % device_serial
     60     device = device_utils.DeviceUtils(device_serial)
     61     # Kill if adb_reboot is already running.
     62     device.old_interface.KillAllBlocking('adb_reboot', 2)
     63     # Push adb_reboot
     64     print '  Pushing adb_reboot ...'
     65     adb_reboot = os.path.join(constants.DIR_SOURCE_ROOT,
     66                               'out/%s/adb_reboot' % target)
     67     device.old_interface.PushIfNeeded(adb_reboot, '/data/local/tmp/')
     68     # Launch adb_reboot
     69     print '  Launching adb_reboot ...'
     70     device.old_interface.GetAndroidToolStatusAndOutput(
     71         '/data/local/tmp/adb_reboot')
     72   LaunchHostHeartbeat()
     73 
     74 
     75 def _ConfigureLocalProperties(device):
     76   """Set standard readonly testing device properties prior to reboot."""
     77   local_props = [
     78       'ro.monkey=1',
     79       'ro.test_harness=1',
     80       'ro.audio.silent=1',
     81       'ro.setupwizard.mode=DISABLED',
     82       ]
     83   device.old_interface.SetProtectedFileContents(
     84       constants.DEVICE_LOCAL_PROPERTIES_PATH,
     85       '\n'.join(local_props))
     86   # Android will not respect the local props file if it is world writable.
     87   device.RunShellCommand(
     88       'chmod 644 %s' % constants.DEVICE_LOCAL_PROPERTIES_PATH,
     89       root=True)
     90 
     91   # LOCAL_PROPERTIES_PATH = '/data/local.prop'
     92 
     93 
     94 def WipeDeviceData(device):
     95   """Wipes data from device, keeping only the adb_keys for authorization.
     96 
     97   After wiping data on a device that has been authorized, adb can still
     98   communicate with the device, but after reboot the device will need to be
     99   re-authorized because the adb keys file is stored in /data/misc/adb/.
    100   Thus, adb_keys file is rewritten so the device does not need to be
    101   re-authorized.
    102 
    103   Arguments:
    104     device: the device to wipe
    105   """
    106   device_authorized = device.old_interface.FileExistsOnDevice(
    107       constants.ADB_KEYS_FILE)
    108   if device_authorized:
    109     adb_keys = device.RunShellCommand('cat %s' % constants.ADB_KEYS_FILE,
    110                                       root=True)
    111   device.RunShellCommand('wipe data', root=True)
    112   if device_authorized:
    113     path_list = constants.ADB_KEYS_FILE.split('/')
    114     dir_path = '/'.join(path_list[:len(path_list)-1])
    115     device.RunShellCommand('mkdir -p %s' % dir_path, root=True)
    116     device.RunShellCommand('echo %s > %s' %
    117                            (adb_keys[0], constants.ADB_KEYS_FILE))
    118     for adb_key in adb_keys[1:]:
    119       device.RunShellCommand(
    120         'echo %s >> %s' % (adb_key, constants.ADB_KEYS_FILE))
    121 
    122 
    123 def ProvisionDevices(options):
    124   # TODO(jbudorick): Parallelize provisioning of all attached devices after
    125   # switching from AndroidCommands.
    126   if options.device is not None:
    127     devices = [options.device]
    128   else:
    129     devices = android_commands.GetAttachedDevices()
    130 
    131   # Wipe devices (unless --skip-wipe was specified)
    132   if not options.skip_wipe:
    133     for device_serial in devices:
    134       device = device_utils.DeviceUtils(device_serial)
    135       device.old_interface.EnableAdbRoot()
    136       WipeDeviceData(device)
    137     try:
    138       device_utils.DeviceUtils.parallel(devices).Reboot(True)
    139     except errors.DeviceUnresponsiveError:
    140       pass
    141     for device_serial in devices:
    142       device.WaitUntilFullyBooted(timeout=90)
    143 
    144   # Provision devices
    145   for device_serial in devices:
    146     device = device_utils.DeviceUtils(device_serial)
    147     device.old_interface.EnableAdbRoot()
    148     _ConfigureLocalProperties(device)
    149     device_settings_map = device_settings.DETERMINISTIC_DEVICE_SETTINGS
    150     if options.disable_location:
    151       device_settings_map.update(device_settings.DISABLE_LOCATION_SETTING)
    152     else:
    153       device_settings_map.update(device_settings.ENABLE_LOCATION_SETTING)
    154     device_settings.ConfigureContentSettingsDict(device, device_settings_map)
    155     if 'perf' in os.environ.get('BUILDBOT_BUILDERNAME', '').lower():
    156       # TODO(tonyg): We eventually want network on. However, currently radios
    157       # can cause perfbots to drain faster than they charge.
    158       device_settings.ConfigureContentSettingsDict(
    159           device, device_settings.NETWORK_DISABLED_SETTINGS)
    160       # Some perf bots run benchmarks with USB charging disabled which leads
    161       # to gradual draining of the battery. We must wait for a full charge
    162       # before starting a run in order to keep the devices online.
    163       try:
    164         battery_info = device.old_interface.GetBatteryInfo()
    165       except Exception as e:
    166         battery_info = {}
    167         logging.error('Unable to obtain battery info for %s, %s',
    168                       device_serial, e)
    169 
    170       while int(battery_info.get('level', 100)) < 95:
    171         if not device.old_interface.IsDeviceCharging():
    172           if device.old_interface.CanControlUsbCharging():
    173             device.old_interface.EnableUsbCharging()
    174           else:
    175             logging.error('Device is not charging')
    176             break
    177         logging.info('Waiting for device to charge. Current level=%s',
    178                      battery_info.get('level', 0))
    179         time.sleep(60)
    180         battery_info = device.old_interface.GetBatteryInfo()
    181     device.RunShellCommand('date -u %f' % time.time(), root=True)
    182   try:
    183     device_utils.DeviceUtils.parallel(devices).Reboot(True)
    184   except errors.DeviceUnresponsiveError:
    185     pass
    186   for device_serial in devices:
    187     device = device_utils.DeviceUtils(device_serial)
    188     device.WaitUntilFullyBooted(timeout=90)
    189     (_, props) = device.old_interface.GetShellCommandStatusAndOutput('getprop')
    190     for prop in props:
    191       print prop
    192   if options.auto_reconnect:
    193     PushAndLaunchAdbReboot(devices, options.target)
    194 
    195 
    196 def main(argv):
    197   logging.basicConfig(level=logging.INFO)
    198 
    199   parser = optparse.OptionParser()
    200   parser.add_option('--skip-wipe', action='store_true', default=False,
    201                     help="Don't wipe device data during provisioning.")
    202   parser.add_option('--disable-location', action='store_true', default=False,
    203                     help="Disallow Google location services on devices.")
    204   parser.add_option('-d', '--device',
    205                     help='The serial number of the device to be provisioned')
    206   parser.add_option('-t', '--target', default='Debug', help='The build target')
    207   parser.add_option(
    208       '-r', '--auto-reconnect', action='store_true',
    209       help='Push binary which will reboot the device on adb disconnections.')
    210   options, args = parser.parse_args(argv[1:])
    211   constants.SetBuildType(options.target)
    212 
    213   if args:
    214     print >> sys.stderr, 'Unused args %s' % args
    215     return 1
    216 
    217   ProvisionDevices(options)
    218 
    219 
    220 if __name__ == '__main__':
    221   sys.exit(main(sys.argv))
    222