1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
13 import android_commands
17 from pylib import valgrind_tools
20 def _GetProcessStartTime(pid):
21 return psutil.Process(pid).create_time
24 class _FileLock(object):
25 """With statement-aware implementation of a file lock.
27 File locks are needed for cross-process synchronization when the
28 multiprocessing Python module is used.
30 def __init__(self, path):
34 self._fd = os.open(self._path, os.O_RDONLY | os.O_CREAT)
36 raise Exception('Could not open file %s for reading' % self._path)
37 fcntl.flock(self._fd, fcntl.LOCK_EX)
39 def __exit__(self, type, value, traceback):
40 fcntl.flock(self._fd, fcntl.LOCK_UN)
44 class Forwarder(object):
45 """Thread-safe class to manage port forwards from the device to the host."""
47 _DEVICE_FORWARDER_FOLDER = (constants.TEST_EXECUTABLE_DIR +
49 _DEVICE_FORWARDER_PATH = (constants.TEST_EXECUTABLE_DIR +
50 '/forwarder/device_forwarder')
51 _LD_LIBRARY_PATH = 'LD_LIBRARY_PATH=%s' % _DEVICE_FORWARDER_FOLDER
52 _LOCK_PATH = '/tmp/chrome.forwarder.lock'
53 _MULTIPROCESSING_ENV_VAR = 'CHROME_FORWARDER_USE_MULTIPROCESSING'
58 def UseMultiprocessing():
59 """Tells the forwarder that multiprocessing is used."""
60 os.environ[Forwarder._MULTIPROCESSING_ENV_VAR] = '1'
63 def Map(port_pairs, adb, tool=None):
64 """Runs the forwarder.
67 port_pairs: A list of tuples (device_port, host_port) to forward. Note
68 that you can specify 0 as a device_port, in which case a
69 port will by dynamically assigned on the device. You can
70 get the number of the assigned port using the
71 DevicePortForHostPort method.
72 adb: An AndroidCommands instance.
73 tool: Tool class to use to get wrapper, if necessary, for executing the
74 forwarder (see valgrind_tools.py).
77 Exception on failure to forward the port.
80 tool = valgrind_tools.CreateTool(None, adb)
81 with _FileLock(Forwarder._LOCK_PATH):
82 instance = Forwarder._GetInstanceLocked(tool)
83 instance._InitDeviceLocked(adb, tool)
85 device_serial = adb.Adb().GetSerialNumber()
86 redirection_commands = [
87 ['--serial-id=' + device_serial, '--map', str(device),
88 str(host)] for device, host in port_pairs]
89 logging.info('Forwarding using commands: %s', redirection_commands)
91 for redirection_command in redirection_commands:
93 (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
94 [instance._host_forwarder_path] + redirection_command)
97 raise Exception('Unable to start host forwarder. Make sure you have'
98 ' built host_forwarder.')
101 raise Exception('%s exited with %d:\n%s' % (
102 instance._host_forwarder_path, exit_code, '\n'.join(output)))
103 tokens = output.split(':')
105 raise Exception(('Unexpected host forwarder output "%s", ' +
106 'expected "device_port:host_port"') % output)
107 device_port = int(tokens[0])
108 host_port = int(tokens[1])
109 serial_with_port = (device_serial, device_port)
110 instance._device_to_host_port_map[serial_with_port] = host_port
111 instance._host_to_device_port_map[host_port] = serial_with_port
112 logging.info('Forwarding device port: %d to host port: %d.',
113 device_port, host_port)
116 def UnmapDevicePort(device_port, adb):
117 """Unmaps a previously forwarded device port.
120 adb: An AndroidCommands instance.
121 device_port: A previously forwarded port (through Map()).
123 with _FileLock(Forwarder._LOCK_PATH):
124 Forwarder._UnmapDevicePortLocked(device_port, adb)
127 def UnmapAllDevicePorts(adb):
128 """Unmaps all the previously forwarded ports for the provided device.
131 adb: An AndroidCommands instance.
132 port_pairs: A list of tuples (device_port, host_port) to unmap.
134 with _FileLock(Forwarder._LOCK_PATH):
135 port_map = Forwarder._GetInstanceLocked(
136 None)._device_to_host_port_map
137 adb_serial = adb.Adb().GetSerialNumber()
138 for (device_serial, device_port) in port_map.keys():
139 if adb_serial == device_serial:
140 Forwarder._UnmapDevicePortLocked(device_port, adb)
143 def DevicePortForHostPort(host_port):
144 """Returns the device port that corresponds to a given host port."""
145 with _FileLock(Forwarder._LOCK_PATH):
146 (device_serial, device_port) = Forwarder._GetInstanceLocked(
147 None)._host_to_device_port_map.get(host_port)
151 def _GetInstanceLocked(tool):
152 """Returns the singleton instance.
154 Note that the global lock must be acquired before calling this method.
157 tool: Tool class to use to get wrapper, if necessary, for executing the
158 forwarder (see valgrind_tools.py).
160 if not Forwarder._instance:
161 Forwarder._instance = Forwarder(tool)
162 return Forwarder._instance
164 def __init__(self, tool):
165 """Constructs a new instance of Forwarder.
167 Note that Forwarder is a singleton therefore this constructor should be
171 tool: Tool class to use to get wrapper, if necessary, for executing the
172 forwarder (see valgrind_tools.py).
174 assert not Forwarder._instance
176 self._initialized_devices = set()
177 self._device_to_host_port_map = dict()
178 self._host_to_device_port_map = dict()
179 self._host_forwarder_path = os.path.join(
180 constants.GetOutDirectory(), 'host_forwarder')
181 assert os.path.exists(self._host_forwarder_path), 'Please build forwarder2'
182 self._device_forwarder_path_on_host = os.path.join(
183 constants.GetOutDirectory(), 'forwarder_dist')
184 self._InitHostLocked()
187 def _UnmapDevicePortLocked(device_port, adb):
188 """Internal method used by UnmapDevicePort().
190 Note that the global lock must be acquired before calling this method.
192 instance = Forwarder._GetInstanceLocked(None)
193 serial = adb.Adb().GetSerialNumber()
194 serial_with_port = (serial, device_port)
195 if not serial_with_port in instance._device_to_host_port_map:
196 logging.error('Trying to unmap non-forwarded port %d' % device_port)
198 redirection_command = ['--serial-id=' + serial, '--unmap', str(device_port)]
199 (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
200 [instance._host_forwarder_path] + redirection_command)
202 logging.error('%s exited with %d:\n%s' % (
203 instance._host_forwarder_path, exit_code, '\n'.join(output)))
204 host_port = instance._device_to_host_port_map[serial_with_port]
205 del instance._device_to_host_port_map[serial_with_port]
206 del instance._host_to_device_port_map[host_port]
209 def _GetPidForLock():
210 """Returns the PID used for host_forwarder initialization.
212 In case multi-process sharding is used, the PID of the "sharder" is used.
213 The "sharder" is the initial process that forks that is the parent process.
214 By default, multi-processing is not used. In that case the PID of the
215 current process is returned.
217 use_multiprocessing = Forwarder._MULTIPROCESSING_ENV_VAR in os.environ
218 return os.getppid() if use_multiprocessing else os.getpid()
220 def _InitHostLocked(self):
221 """Initializes the host forwarder daemon.
223 Note that the global lock must be acquired before calling this method. This
224 method kills any existing host_forwarder process that could be stale.
226 # See if the host_forwarder daemon was already initialized by a concurrent
227 # process or thread (in case multi-process sharding is not used).
228 pid_for_lock = Forwarder._GetPidForLock()
229 fd = os.open(Forwarder._LOCK_PATH, os.O_RDWR | os.O_CREAT)
230 with os.fdopen(fd, 'r+') as pid_file:
231 pid_with_start_time = pid_file.readline()
232 if pid_with_start_time:
233 (pid, process_start_time) = pid_with_start_time.split(':')
234 if pid == str(pid_for_lock):
235 if process_start_time == str(_GetProcessStartTime(pid_for_lock)):
237 self._KillHostLocked()
240 '%s:%s' % (pid_for_lock, str(_GetProcessStartTime(pid_for_lock))))
242 def _InitDeviceLocked(self, adb, tool):
243 """Initializes the device_forwarder daemon for a specific device (once).
245 Note that the global lock must be acquired before calling this method. This
246 method kills any existing device_forwarder daemon on the device that could
247 be stale, pushes the latest version of the daemon (to the device) and starts
251 adb: An AndroidCommands instance.
252 tool: Tool class to use to get wrapper, if necessary, for executing the
253 forwarder (see valgrind_tools.py).
255 device_serial = adb.Adb().GetSerialNumber()
256 if device_serial in self._initialized_devices:
258 Forwarder._KillDeviceLocked(adb, tool)
260 self._device_forwarder_path_on_host,
261 Forwarder._DEVICE_FORWARDER_FOLDER)
262 (exit_code, output) = adb.GetShellCommandStatusAndOutput(
263 '%s %s %s' % (Forwarder._LD_LIBRARY_PATH, tool.GetUtilWrapper(),
264 Forwarder._DEVICE_FORWARDER_PATH))
267 'Failed to start device forwarder:\n%s' % '\n'.join(output))
268 self._initialized_devices.add(device_serial)
270 def _KillHostLocked(self):
271 """Kills the forwarder process running on the host.
273 Note that the global lock must be acquired before calling this method.
275 logging.info('Killing host_forwarder.')
276 (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
277 [self._host_forwarder_path, '--kill-server'])
279 (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
280 ['pkill', '-9', 'host_forwarder'])
282 raise Exception('%s exited with %d:\n%s' % (
283 self._host_forwarder_path, exit_code, '\n'.join(output)))
286 def _KillDeviceLocked(adb, tool):
287 """Kills the forwarder process running on the device.
289 Note that the global lock must be acquired before calling this method.
292 adb: Instance of AndroidCommands for talking to the device.
293 tool: Wrapper tool (e.g. valgrind) that can be used to execute the device
294 forwarder (see valgrind_tools.py).
296 logging.info('Killing device_forwarder.')
297 if not adb.FileExistsOnDevice(Forwarder._DEVICE_FORWARDER_PATH):
299 (exit_code, output) = adb.GetShellCommandStatusAndOutput(
300 '%s %s --kill-server' % (tool.GetUtilWrapper(),
301 Forwarder._DEVICE_FORWARDER_PATH))
302 # TODO(pliard): Remove the following call to KillAllBlocking() when we are
303 # sure that the old version of device_forwarder (not supporting
304 # 'kill-server') is not running on the bots anymore.
306 processes_killed = adb.KillAllBlocking('device_forwarder', timeout_sec)
307 if not processes_killed:
308 pids = adb.ExtractPid('device_forwarder')
310 raise Exception('Timed out while killing device_forwarder')