Esempio n. 1
0
 def LaunchChromeTestServerSpawner(self):
     """Launches test server spawner."""
     server_ready = False
     error_msgs = []
     # Try 3 times to launch test spawner server.
     for i in xrange(0, 3):
         # Do not allocate port for test server here. We will allocate
         # different port for individual test in TestServerThread.
         self.test_server_spawner_port = ports.AllocateTestServerPort()
         self._spawning_server = SpawningServer(
             self.test_server_spawner_port, self.adb, self.tool,
             self.build_type)
         self._spawning_server.Start()
         server_ready, error_msg = ports.IsHttpServerConnectable(
             '127.0.0.1',
             self.test_server_spawner_port,
             path='/ping',
             expected_read='ready')
         if server_ready:
             break
         else:
             error_msgs.append(error_msg)
         self._spawning_server.Stop()
         # Wait for 2 seconds then restart.
         time.sleep(2)
     if not server_ready:
         logging.error(';'.join(error_msgs))
         raise Exception('Can not start the test spawner server.')
     self._PushTestServerPortInfoToDevice()
     self._spawner_forwarder = Forwarder(
         self.adb,
         [(self.test_server_spawner_port, self.test_server_spawner_port)],
         self.tool, '127.0.0.1', self.build_type)
Esempio n. 2
0
  def Run(self, port_pairs, tool, host_name):
    """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.
      tool: Tool class to use to get wrapper, if necessary, for executing the
            forwarder (see valgrind_tools.py).
      host_name: Address to forward to, must be addressable from the
                 host machine. Usually use loopback '127.0.0.1'.

    Raises:
      Exception on failure to forward the port.
    """
    host_adb_control_port = ports.AllocateTestServerPort()
    if not host_adb_control_port:
      raise Exception('Failed to allocate a TCP port in the host machine.')
    self._adb.PushIfNeeded(
        self._device_forwarder_path, Forwarder._DEVICE_FORWARDER_PATH)
    redirection_commands = [
        '%d:%d:%d:%s' % (host_adb_control_port, device, host,
                         host_name) for device, host in port_pairs]
    logging.info('Command format: <ADB port>:<Device port>' +
                 '[:<Forward to port>:<Forward to address>]')
    logging.info('Forwarding using commands: %s', redirection_commands)
    if cmd_helper.RunCmd(
        ['adb', '-s', self._adb._adb.GetSerialNumber(), 'forward',
         'tcp:%s' % host_adb_control_port,
         'localabstract:%s' % Forwarder._DEVICE_ADB_CONTROL_PORT]) != 0:
      raise Exception('Error while running adb forward.')

    (exit_code, output) = self._adb.GetShellCommandStatusAndOutput(
        '%s %s %s' % (tool.GetUtilWrapper(), Forwarder._DEVICE_FORWARDER_PATH,
                      Forwarder._DEVICE_ADB_CONTROL_PORT))
    if exit_code != 0:
      raise Exception(
          'Failed to start device forwarder:\n%s' % '\n'.join(output))

    for redirection_command in redirection_commands:
      (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
          [self._host_forwarder_path, redirection_command])
      if exit_code != 0:
        raise Exception('%s exited with %d:\n%s' % (
            self._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])
      self._host_to_device_port_map[host_port] = device_port
      logging.info('Forwarding device port: %d to host port: %d.', device_port,
                   host_port)
 def _InitHostLocked(self):
     """Initializes the host forwarder process (only once)."""
     if self._host_adb_control_port:
         return
     self._host_adb_control_port = ports.AllocateTestServerPort()
     if not self._host_adb_control_port:
         raise Exception(
             'Failed to allocate a TCP port in the host machine.')
     if cmd_helper.RunCmd([
             'adb', '-s',
             self._adb._adb.GetSerialNumber(), 'forward',
             'tcp:%s' % self._host_adb_control_port,
             'localabstract:%s' % Forwarder._DEVICE_ADB_CONTROL_PORT
     ]) != 0:
         raise Exception('Error while running adb forward.')
Esempio n. 4
0
  def __init__(self, adb, port_pairs, tool, host_name, build_type):
    """Forwards TCP ports on the device back to the host.

    Works like adb forward, but in reverse.

    Args:
      adb: Instance of AndroidCommands for talking to the device.
      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.
      tool: Tool class to use to get wrapper, if necessary, for executing the
            forwarder (see valgrind_tools.py).
      host_name: Address to forward to, must be addressable from the
                 host machine. Usually use loopback '127.0.0.1'.
      build_type: 'Release' or 'Debug'.

    Raises:
      Exception on failure to forward the port.
    """
    self._adb = adb
    self._host_to_device_port_map = dict()
    self._host_process = None
    self._device_process = None
    self._adb_forward_process = None

    self._host_adb_control_port = ports.AllocateTestServerPort()
    if not self._host_adb_control_port:
      raise Exception('Failed to allocate a TCP port in the host machine.')
    adb.PushIfNeeded(
        os.path.join(constants.CHROME_DIR, 'out', build_type,
                     'device_forwarder'),
        Forwarder._DEVICE_FORWARDER_PATH)
    self._host_forwarder_path = os.path.join(constants.CHROME_DIR,
                                             'out',
                                             build_type,
                                             'host_forwarder')
    forward_string = ['%d:%d:%s' %
                      (device, host, host_name) for device, host in port_pairs]
    logging.info('Forwarding ports: %s', forward_string)
    timeout_sec = 5
    host_pattern = 'host_forwarder.*' + ' '.join(forward_string)
    # TODO(felipeg): Rather than using a blocking kill() here, the device
    # forwarder could try to bind the Unix Domain Socket until it succeeds or
    # while it fails because the socket is already bound (with appropriate
    # timeout handling obviously).
    self._KillHostForwarderBlocking(host_pattern, timeout_sec)
    self._KillDeviceForwarderBlocking(timeout_sec)
    self._adb_forward_process = pexpect.spawn(
        'adb', ['-s',
                adb._adb.GetSerialNumber(),
                'forward',
                'tcp:%s' % self._host_adb_control_port,
                'localabstract:%s' % Forwarder._DEVICE_ADB_CONTROL_PORT])
    self._device_process = pexpect.spawn(
        'adb', ['-s',
                adb._adb.GetSerialNumber(),
                'shell',
                '%s %s -D --adb_sock=%s' % (
                    tool.GetUtilWrapper(),
                    Forwarder._DEVICE_FORWARDER_PATH,
                    Forwarder._DEVICE_ADB_CONTROL_PORT)])

    device_success_re = re.compile('Starting Device Forwarder.')
    device_failure_re = re.compile('.*:ERROR:(.*)')
    index = self._device_process.expect([device_success_re,
                                         device_failure_re,
                                         pexpect.EOF,
                                         pexpect.TIMEOUT],
                                        Forwarder._TIMEOUT_SECS)
    if index == 1:
      # Failure
      error_msg = str(self._device_process.match.group(1))
      logging.error(self._device_process.before)
      self._CloseProcess()
      raise Exception('Failed to start Device Forwarder with Error: %s' %
                      error_msg)
    elif index == 2:
      logging.error(self._device_process.before)
      self._CloseProcess()
      raise Exception('Unexpected EOF while trying to start Device Forwarder.')
    elif index == 3:
      logging.error(self._device_process.before)
      self._CloseProcess()
      raise Exception('Timeout while trying start Device Forwarder')

    self._host_process = pexpect.spawn(self._host_forwarder_path,
                                       ['--adb_port=%s' % (
                                           self._host_adb_control_port)] +
                                       forward_string)

    # Read the output of the command to determine which device ports where
    # forwarded to which host ports (necessary if
    host_success_re = re.compile('Forwarding device port (\d+) to host (\d+):')
    host_failure_re = re.compile('Couldn\'t start forwarder server for port '
                                 'spec: (\d+):(\d+)')
    for pair in port_pairs:
      index = self._host_process.expect([host_success_re,
                                         host_failure_re,
                                         pexpect.EOF,
                                         pexpect.TIMEOUT],
                                        Forwarder._TIMEOUT_SECS)
      if index == 0:
        # Success
        device_port = int(self._host_process.match.group(1))
        host_port = int(self._host_process.match.group(2))
        self._host_to_device_port_map[host_port] = device_port
        logging.info("Forwarding device port: %d to host port: %d." %
                     (device_port, host_port))
      elif index == 1:
        # Failure
        device_port = int(self._host_process.match.group(1))
        host_port = int(self._host_process.match.group(2))
        self._CloseProcess()
        raise Exception('Failed to forward port %d to %d' % (device_port,
                                                             host_port))
      elif index == 2:
        logging.error(self._host_process.before)
        self._CloseProcess()
        raise Exception('Unexpected EOF while trying to forward ports %s' %
                        port_pairs)
      elif index == 3:
        logging.error(self._host_process.before)
        self._CloseProcess()
        raise Exception('Timeout while trying to forward ports %s' % port_pairs)