summaryrefslogtreecommitdiffstats
path: root/build/android/pylib/forwarder.py
blob: 5bdb1cd4ce92b2598e9cff38295f19fd3950c572 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# 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.

import logging
import os
import re
import sys
import threading
import time

import android_commands
import cmd_helper
import constants

from pylib import pexpect


def _MakeBinaryPath(build_type, binary_name):
  return os.path.join(cmd_helper.OutDirectory.get(), build_type, binary_name)


class Forwarder(object):
  """Thread-safe class to manage port forwards from the device to the host."""

  _DEVICE_FORWARDER_FOLDER = (constants.TEST_EXECUTABLE_DIR +
                              '/forwarder/')
  _DEVICE_FORWARDER_PATH = (constants.TEST_EXECUTABLE_DIR +
                            '/forwarder/device_forwarder')
  _LD_LIBRARY_PATH = 'LD_LIBRARY_PATH=%s' % _DEVICE_FORWARDER_FOLDER

  def __init__(self, adb, 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.
      build_type: 'Release' or 'Debug'.
    """
    assert build_type in ('Release', 'Debug')
    self._adb = adb
    self._device_to_host_port_map = dict()
    self._host_to_device_port_map = dict()
    self._device_initialized = False
    self._host_adb_control_port = 0
    self._lock = threading.Lock()
    self._host_forwarder_path = _MakeBinaryPath(build_type, 'host_forwarder')
    self._device_forwarder_path_on_host = os.path.join(
        cmd_helper.OutDirectory.get(), build_type, 'forwarder_dist')

  def Run(self, port_pairs, tool):
    """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).

    Raises:
      Exception on failure to forward the port.
    """
    with self._lock:
      self._InitDeviceLocked(tool)
      host_name = '127.0.0.1'
      redirection_commands = [
          ['--serial-id=' + self._adb.Adb().GetSerialNumber(), '--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(
              [self._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' % (
              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._device_to_host_port_map[device_port] = host_port
        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 _InitDeviceLocked(self, tool):
    """Initializes the device forwarder process (only once)."""
    if self._device_initialized:
      return
    self._adb.PushIfNeeded(
        self._device_forwarder_path_on_host,
        Forwarder._DEVICE_FORWARDER_FOLDER)
    (exit_code, output) = self._adb.GetShellCommandStatusAndOutput(
        '%s %s %s' % (Forwarder._LD_LIBRARY_PATH, tool.GetUtilWrapper(),
                      Forwarder._DEVICE_FORWARDER_PATH))
    if exit_code != 0:
      raise Exception(
          'Failed to start device forwarder:\n%s' % '\n'.join(output))
    self._device_initialized = True

  def UnmapDevicePort(self, device_port):
    """Unmaps a previously forwarded device port.

    Args:
      device_port: A previously forwarded port (through Run()).
    """
    with self._lock:
      self._UnmapDevicePortInternalLocked(device_port)

  def _UnmapDevicePortInternalLocked(self, device_port):
    if not device_port in self._device_to_host_port_map:
      return
    redirection_command = [
        '--serial-id=' + self._adb.Adb().GetSerialNumber(), '--unmap',
        str(device_port)]
    (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
        [self._host_forwarder_path] + redirection_command)
    if exit_code != 0:
      logging.error('%s exited with %d:\n%s' % (
          self._host_forwarder_path, exit_code, '\n'.join(output)))
    host_port = self._device_to_host_port_map[device_port]
    del self._device_to_host_port_map[device_port]
    del self._host_to_device_port_map[host_port]

  @staticmethod
  def KillHost(build_type='Debug'):
    """Kills the forwarder process running on the host.

    Args:
      build_type: 'Release' or 'Debug' (default='Debug')
    """
    logging.info('Killing host_forwarder.')
    host_forwarder_path = _MakeBinaryPath(build_type, 'host_forwarder')
    if not os.path.exists(host_forwarder_path):
      host_forwarder_path = _MakeBinaryPath(
          'Release' if build_type == 'Debug' else 'Debug', 'host_forwarder')
    assert os.path.exists(host_forwarder_path), 'Please build forwarder2'
    (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
        [host_forwarder_path, '--kill-server'])
    if exit_code != 0:
      (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
          ['pkill', 'host_forwarder'])
      if exit_code != 0:
        raise Exception('%s exited with %d:\n%s' % (
              host_forwarder_path, exit_code, '\n'.join(output)))

  @staticmethod
  def KillDevice(adb, tool):
    """Kills the forwarder process running on the device.

    Args:
      adb: Instance of AndroidCommands for talking to the device.
      tool: Wrapper tool (e.g. valgrind) that can be used to execute the device
            forwarder (see valgrind_tools.py).
    """
    logging.info('Killing device_forwarder.')
    if not adb.FileExistsOnDevice(Forwarder._DEVICE_FORWARDER_PATH):
      return
    (exit_code, output) = adb.GetShellCommandStatusAndOutput(
        '%s %s --kill-server' % (tool.GetUtilWrapper(),
                                 Forwarder._DEVICE_FORWARDER_PATH))
    # TODO(pliard): Remove the following call to KillAllBlocking() when we are
    # sure that the old version of device_forwarder (not supporting
    # 'kill-server') is not running on the bots anymore.
    timeout_sec = 5
    processes_killed = adb.KillAllBlocking('device_forwarder', timeout_sec)
    if not processes_killed:
      pids = adb.ExtractPid('device_forwarder')
      if pids:
        raise Exception('Timed out while killing device_forwarder')

  def DevicePortForHostPort(self, host_port):
    """Returns the device port that corresponds to a given host port."""
    with self._lock:
      return self._host_to_device_port_map.get(host_port)

  def Close(self):
    """Releases the previously forwarded ports."""
    with self._lock:
      for device_port in self._device_to_host_port_map.copy():
        self._UnmapDevicePortInternalLocked(device_port)