def testRestartServerAlreadyRunning(self): if cmd_helper.RunCmd(['pgrep', 'adb']) != 0: device_utils.RestartServer() code, original_pid = cmd_helper.GetCmdStatusAndOutput(['pgrep', 'adb']) self.assertEqual(0, code) device_utils.RestartServer() code, new_pid = cmd_helper.GetCmdStatusAndOutput(['pgrep', 'adb']) self.assertEqual(0, code) self.assertNotEqual(original_pid, new_pid)
def _KillHostLocked(self): """Kills the forwarder process running on the host. Note that the global lock must be acquired before calling this method. """ logging.info('Killing host_forwarder.') (exit_code, output) = cmd_helper.GetCmdStatusAndOutput( [self._host_forwarder_path, '--kill-server']) if exit_code != 0: (exit_code, output) = cmd_helper.GetCmdStatusAndOutput( ['pkill', '-9', 'host_forwarder']) if exit_code != 0: raise Exception('%s exited with %d:\n%s' % ( self._host_forwarder_path, exit_code, '\n'.join(output)))
def _UnmapDevicePortLocked(device_port, device): """Internal method used by UnmapDevicePort(). Note that the global lock must be acquired before calling this method. """ instance = Forwarder._GetInstanceLocked(None) serial = str(device) serial_with_port = (serial, device_port) if not serial_with_port in instance._device_to_host_port_map: logging.error('Trying to unmap non-forwarded port %d' % device_port) return redirection_command = [ '--adb=' + constants.GetAdbPath(), '--serial-id=' + serial, '--unmap', str(device_port) ] logging.info('Undo forwarding using command: %s', redirection_command) (exit_code, output ) = cmd_helper.GetCmdStatusAndOutput([instance._host_forwarder_path] + redirection_command) if exit_code != 0: logging.error( '%s exited with %d:\n%s' % (instance._host_forwarder_path, exit_code, '\n'.join(output))) host_port = instance._device_to_host_port_map[serial_with_port] del instance._device_to_host_port_map[serial_with_port] del instance._host_to_device_port_map[host_port]
def CheckSDKPlatform(api_level=DEFAULT_ANDROID_API_LEVEL): """Check if the "SDK Platform" for the specified API level is installed. This is necessary in order for the emulator to run when the target is specified. Args: api_level: the Android API level to check; defaults to the latest API. Returns: True if the platform is already installed. """ android_binary = os.path.join(constants.EMULATOR_SDK_ROOT, 'sdk', 'tools', 'android') pattern = re.compile('id: [0-9]+ or "android-%d"' % api_level) try: exit_code, stdout = cmd_helper.GetCmdStatusAndOutput( [android_binary, 'list']) if exit_code != 0: raise Exception('\'android list\' command failed') for line in stdout.split('\n'): if pattern.match(line): return True return False except OSError: logging.exception('Unable to execute \'android list\'') return False
def Map(port_pairs, device, tool=None): """Runs the forwarder. Args: port_pairs: A list of tuples (device_port, host_port) to forward. Note that you can specify 0 as a device_port, in which case a port will by dynamically assigned on the device. You can get the number of the assigned port using the DevicePortForHostPort method. device: A DeviceUtils instance. tool: Tool class to use to get wrapper, if necessary, for executing the forwarder (see valgrind_tools.py). Raises: Exception on failure to forward the port. """ # TODO(jbudorick) Remove once telemetry gets switched over. if isinstance(device, pylib.android_commands.AndroidCommands): device = pylib.device.device_utils.DeviceUtils(device) if not tool: tool = valgrind_tools.CreateTool(None, device) with _FileLock(Forwarder._LOCK_PATH): instance = Forwarder._GetInstanceLocked(tool) instance._InitDeviceLocked(device, tool) device_serial = device.old_interface.Adb().GetSerialNumber() redirection_commands = [[ '--serial-id=' + device_serial, '--map', str(device), str(host) ] for device, host in port_pairs] logging.info('Forwarding using commands: %s', redirection_commands) for redirection_command in redirection_commands: try: (exit_code, output) = cmd_helper.GetCmdStatusAndOutput( [instance._host_forwarder_path] + redirection_command) except OSError as e: if e.errno == 2: raise Exception( 'Unable to start host forwarder. Make sure you have' ' built host_forwarder.') else: raise if exit_code != 0: raise Exception('%s exited with %d:\n%s' % (instance._host_forwarder_path, exit_code, '\n'.join(output))) tokens = output.split(':') if len(tokens) != 2: raise Exception( ('Unexpected host forwarder output "%s", ' + 'expected "device_port:host_port"') % output) device_port = int(tokens[0]) host_port = int(tokens[1]) serial_with_port = (device_serial, device_port) instance._device_to_host_port_map[serial_with_port] = host_port instance._host_to_device_port_map[host_port] = serial_with_port logging.info('Forwarding device port: %d to host port: %d.', device_port, host_port)
def RunCmd(): exit_code, output = cmd_helper.GetCmdStatusAndOutput(cmd) if exit_code != 0: raise CommandFailedError( cmd, 'returned non-zero exit code %s, output: %s' % (exit_code, output)) # This catches some errors, including when the device drops offline; # unfortunately adb is very inconsistent with error reporting so many # command failures present differently. if check_error and output[:len('error:')] == 'error:': raise CommandFailedError(arg_list, output) return output
def _RunAaptCmd(args): """Runs an aapt command. Args: args: A list of arguments for aapt. Returns: The output of the command. """ cmd = [_AAPT_PATH] + args status, output = cmd_helper.GetCmdStatusAndOutput(cmd) if status != 0: raise Exception('Failed running aapt command: "%s" with output "%s".' % (' '.join(cmd), output)) return output
def _RunSplitSelectCmd(args): """Runs a split-select command. Args: args: A list of arguments for split-select. Returns: The output of the command. """ cmd = [_SPLIT_SELECT_PATH] + args status, output = cmd_helper.GetCmdStatusAndOutput(cmd) if status != 0: raise Exception('Failed running command "%s" with output "%s".' % (' '.join(cmd), output)) return output
def GetSDKPlatform(api_level=DEFAULT_ANDROID_API_LEVEL): """Update the SDK to include the platform specified. Args: api_level: the Android API level to download """ android_binary = os.path.join(constants.EMULATOR_SDK_ROOT, 'sdk', 'tools', 'android') pattern = re.compile( '\s*([0-9]+)- SDK Platform Android [\.,0-9]+, API %d.*' % api_level) # Example: # 2- SDK Platform Android 4.3, API 18, revision 2 exit_code, stdout = cmd_helper.GetCmdStatusAndOutput( [android_binary, 'list', 'sdk']) if exit_code != 0: raise Exception('\'android list sdk\' command return %d' % exit_code) for line in stdout.split('\n'): match = pattern.match(line) if match: index = match.group(1) print('package %s corresponds to platform level %d' % (index, api_level)) # update sdk --no-ui --filter $INDEX update_command = [ android_binary, 'update', 'sdk', '--no-ui', '--filter', index ] update_command_str = ' '.join(update_command) logging.info('running update command: %s' % update_command_str) update_process = pexpect.spawn(update_command_str) # TODO(andrewhayden): Do we need to bug the user about this? if update_process.expect('Do you accept the license') != 0: raise Exception('License agreement check failed') update_process.sendline('y') if update_process.expect('Done. 1 package installed.') == 0: print('Successfully installed platform for API level %d' % api_level) return else: raise Exception('Failed to install platform update') raise Exception('Could not find android-%d update for the SDK!' % api_level)
def Map(port_pairs, device, tool=None): """Runs the forwarder. Args: port_pairs: A list of tuples (device_port, host_port) to forward. Note that you can specify 0 as a device_port, in which case a port will by dynamically assigned on the device. You can get the number of the assigned port using the DevicePortForHostPort method. device: A DeviceUtils instance. tool: Tool class to use to get wrapper, if necessary, for executing the forwarder (see valgrind_tools.py). Raises: Exception on failure to forward the port. """ if not tool: tool = valgrind_tools.CreateTool(None, device) with _FileLock(Forwarder._LOCK_PATH): instance = Forwarder._GetInstanceLocked(tool) instance._InitDeviceLocked(device, tool) device_serial = str(device) redirection_commands = [[ '--adb=' + constants.GetAdbPath(), '--serial-id=' + device_serial, '--map', str(device_port), str(host_port) ] for device_port, host_port in port_pairs] logging.info('Forwarding using commands: %s', redirection_commands) for redirection_command in redirection_commands: try: (exit_code, output) = cmd_helper.GetCmdStatusAndOutput( [instance._host_forwarder_path] + redirection_command) except OSError as e: if e.errno == 2: raise Exception( 'Unable to start host forwarder. Make sure you have' ' built host_forwarder.') else: raise if exit_code != 0: Forwarder._KillDeviceLocked(device, tool) # Log alive forwarders ps_out = device.RunShellCommand(['ps']) logging.info('Currently running device_forwarders:') for line in ps_out: if 'device_forwarder' in line: logging.info(' %s', line) raise Exception('%s exited with %d:\n%s' % (instance._host_forwarder_path, exit_code, '\n'.join(output))) tokens = output.split(':') if len(tokens) != 2: raise Exception('Unexpected host forwarder output "%s", ' 'expected "device_port:host_port"' % output) device_port = int(tokens[0]) host_port = int(tokens[1]) serial_with_port = (device_serial, device_port) instance._device_to_host_port_map[serial_with_port] = host_port instance._host_to_device_port_map[host_port] = serial_with_port logging.info('Forwarding device port: %d to host port: %d.', device_port, host_port)
def IsServerOnline(cls): status, output = cmd_helper.GetCmdStatusAndOutput(['pgrep', 'adb']) output = [int(x) for x in output.split()] logging.info('PIDs for adb found: %r', output) return status == 0