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.
5 # pylint: disable=W0212
12 from pylib
import cmd_helper
13 from pylib
import constants
14 from pylib
import valgrind_tools
16 # TODO(jbudorick) Remove once telemetry gets switched over.
17 import pylib
.android_commands
18 import pylib
.device
.device_utils
21 def _GetProcessStartTime(pid
):
22 return psutil
.Process(pid
).create_time
25 class _FileLock(object):
26 """With statement-aware implementation of a file lock.
28 File locks are needed for cross-process synchronization when the
29 multiprocessing Python module is used.
31 def __init__(self
, path
):
36 self
._fd
= os
.open(self
._path
, os
.O_RDONLY | os
.O_CREAT
)
38 raise Exception('Could not open file %s for reading' % self
._path
)
39 fcntl
.flock(self
._fd
, fcntl
.LOCK_EX
)
41 def __exit__(self
, _exception_type
, _exception_value
, traceback
):
42 fcntl
.flock(self
._fd
, fcntl
.LOCK_UN
)
46 class Forwarder(object):
47 """Thread-safe class to manage port forwards from the device to the host."""
49 _DEVICE_FORWARDER_FOLDER
= (constants
.TEST_EXECUTABLE_DIR
+
51 _DEVICE_FORWARDER_PATH
= (constants
.TEST_EXECUTABLE_DIR
+
52 '/forwarder/device_forwarder')
53 _LOCK_PATH
= '/tmp/chrome.forwarder.lock'
54 # Defined in host_forwarder_main.cc
55 _HOST_FORWARDER_LOG
= '/tmp/host_forwarder_log'
60 def Map(port_pairs
, device
, tool
=None):
61 """Runs the forwarder.
64 port_pairs: A list of tuples (device_port, host_port) to forward. Note
65 that you can specify 0 as a device_port, in which case a
66 port will by dynamically assigned on the device. You can
67 get the number of the assigned port using the
68 DevicePortForHostPort method.
69 device: A DeviceUtils instance.
70 tool: Tool class to use to get wrapper, if necessary, for executing the
71 forwarder (see valgrind_tools.py).
74 Exception on failure to forward the port.
76 # TODO(jbudorick) Remove once telemetry gets switched over.
77 if isinstance(device
, pylib
.android_commands
.AndroidCommands
):
78 device
= pylib
.device
.device_utils
.DeviceUtils(device
)
80 tool
= valgrind_tools
.CreateTool(None, device
)
81 with
_FileLock(Forwarder
._LOCK
_PATH
):
82 instance
= Forwarder
._GetInstanceLocked
(tool
)
83 instance
._InitDeviceLocked
(device
, tool
)
85 device_serial
= str(device
)
86 redirection_commands
= [
87 ['--adb=' + constants
.GetAdbPath(),
88 '--serial-id=' + device_serial
,
89 '--map', str(device_port
), str(host_port
)]
90 for device_port
, host_port
in port_pairs
]
91 logging
.info('Forwarding using commands: %s', redirection_commands
)
93 for redirection_command
in redirection_commands
:
95 (exit_code
, output
) = cmd_helper
.GetCmdStatusAndOutput(
96 [instance
._host
_forwarder
_path
] + redirection_command
)
99 raise Exception('Unable to start host forwarder. Make sure you have'
100 ' built host_forwarder.')
103 Forwarder
._KillDeviceLocked
(device
, tool
)
104 raise Exception('%s exited with %d:\n%s' % (
105 instance
._host
_forwarder
_path
, exit_code
, '\n'.join(output
)))
106 tokens
= output
.split(':')
108 raise Exception('Unexpected host forwarder output "%s", '
109 'expected "device_port:host_port"' % output
)
110 device_port
= int(tokens
[0])
111 host_port
= int(tokens
[1])
112 serial_with_port
= (device_serial
, device_port
)
113 instance
._device
_to
_host
_port
_map
[serial_with_port
] = host_port
114 instance
._host
_to
_device
_port
_map
[host_port
] = serial_with_port
115 logging
.info('Forwarding device port: %d to host port: %d.',
116 device_port
, host_port
)
119 def UnmapDevicePort(device_port
, device
):
120 """Unmaps a previously forwarded device port.
123 device: A DeviceUtils instance.
124 device_port: A previously forwarded port (through Map()).
126 # TODO(jbudorick) Remove once telemetry gets switched over.
127 if isinstance(device
, pylib
.android_commands
.AndroidCommands
):
128 device
= pylib
.device
.device_utils
.DeviceUtils(device
)
129 with
_FileLock(Forwarder
._LOCK
_PATH
):
130 Forwarder
._UnmapDevicePortLocked
(device_port
, device
)
133 def UnmapAllDevicePorts(device
):
134 """Unmaps all the previously forwarded ports for the provided device.
137 device: A DeviceUtils instance.
138 port_pairs: A list of tuples (device_port, host_port) to unmap.
140 # TODO(jbudorick) Remove once telemetry gets switched over.
141 if isinstance(device
, pylib
.android_commands
.AndroidCommands
):
142 device
= pylib
.device
.device_utils
.DeviceUtils(device
)
143 with
_FileLock(Forwarder
._LOCK
_PATH
):
144 if not Forwarder
._instance
:
146 adb_serial
= str(device
)
147 if adb_serial
not in Forwarder
._instance
._initialized
_devices
:
149 port_map
= Forwarder
._GetInstanceLocked
(
150 None)._device
_to
_host
_port
_map
151 for (device_serial
, device_port
) in port_map
.keys():
152 if adb_serial
== device_serial
:
153 Forwarder
._UnmapDevicePortLocked
(device_port
, device
)
154 # There are no more ports mapped, kill the device_forwarder.
155 tool
= valgrind_tools
.CreateTool(None, device
)
156 Forwarder
._KillDeviceLocked
(device
, tool
)
159 def DevicePortForHostPort(host_port
):
160 """Returns the device port that corresponds to a given host port."""
161 with
_FileLock(Forwarder
._LOCK
_PATH
):
162 (_device_serial
, device_port
) = Forwarder
._GetInstanceLocked
(
163 None)._host
_to
_device
_port
_map
.get(host_port
)
168 if os
.path
.exists(Forwarder
._HOST
_FORWARDER
_LOG
):
169 os
.unlink(Forwarder
._HOST
_FORWARDER
_LOG
)
173 if not os
.path
.exists(Forwarder
._HOST
_FORWARDER
_LOG
):
175 with
file(Forwarder
._HOST
_FORWARDER
_LOG
, 'r') as f
:
179 def _GetInstanceLocked(tool
):
180 """Returns the singleton instance.
182 Note that the global lock must be acquired before calling this method.
185 tool: Tool class to use to get wrapper, if necessary, for executing the
186 forwarder (see valgrind_tools.py).
188 if not Forwarder
._instance
:
189 Forwarder
._instance
= Forwarder(tool
)
190 return Forwarder
._instance
192 def __init__(self
, tool
):
193 """Constructs a new instance of Forwarder.
195 Note that Forwarder is a singleton therefore this constructor should be
199 tool: Tool class to use to get wrapper, if necessary, for executing the
200 forwarder (see valgrind_tools.py).
202 assert not Forwarder
._instance
204 self
._initialized
_devices
= set()
205 self
._device
_to
_host
_port
_map
= dict()
206 self
._host
_to
_device
_port
_map
= dict()
207 self
._host
_forwarder
_path
= os
.path
.join(
208 constants
.GetOutDirectory(), 'host_forwarder')
209 assert os
.path
.exists(self
._host
_forwarder
_path
), 'Please build forwarder2'
210 self
._device
_forwarder
_path
_on
_host
= os
.path
.join(
211 constants
.GetOutDirectory(), 'forwarder_dist')
212 self
._InitHostLocked
()
215 def _UnmapDevicePortLocked(device_port
, device
):
216 """Internal method used by UnmapDevicePort().
218 Note that the global lock must be acquired before calling this method.
220 instance
= Forwarder
._GetInstanceLocked
(None)
222 serial_with_port
= (serial
, device_port
)
223 if not serial_with_port
in instance
._device
_to
_host
_port
_map
:
224 logging
.error('Trying to unmap non-forwarded port %d' % device_port
)
226 redirection_command
= ['--adb=' + constants
.GetAdbPath(),
227 '--serial-id=' + serial
,
228 '--unmap', str(device_port
)]
229 (exit_code
, output
) = cmd_helper
.GetCmdStatusAndOutput(
230 [instance
._host
_forwarder
_path
] + redirection_command
)
232 logging
.error('%s exited with %d:\n%s' % (
233 instance
._host
_forwarder
_path
, exit_code
, '\n'.join(output
)))
234 host_port
= instance
._device
_to
_host
_port
_map
[serial_with_port
]
235 del instance
._device
_to
_host
_port
_map
[serial_with_port
]
236 del instance
._host
_to
_device
_port
_map
[host_port
]
239 def _GetPidForLock():
240 """Returns the PID used for host_forwarder initialization.
242 The PID of the "sharder" is used to handle multiprocessing. The "sharder"
243 is the initial process that forks that is the parent process.
247 def _InitHostLocked(self
):
248 """Initializes the host forwarder daemon.
250 Note that the global lock must be acquired before calling this method. This
251 method kills any existing host_forwarder process that could be stale.
253 # See if the host_forwarder daemon was already initialized by a concurrent
254 # process or thread (in case multi-process sharding is not used).
255 pid_for_lock
= Forwarder
._GetPidForLock
()
256 fd
= os
.open(Forwarder
._LOCK
_PATH
, os
.O_RDWR | os
.O_CREAT
)
257 with os
.fdopen(fd
, 'r+') as pid_file
:
258 pid_with_start_time
= pid_file
.readline()
259 if pid_with_start_time
:
260 (pid
, process_start_time
) = pid_with_start_time
.split(':')
261 if pid
== str(pid_for_lock
):
262 if process_start_time
== str(_GetProcessStartTime(pid_for_lock
)):
264 self
._KillHostLocked
()
267 '%s:%s' % (pid_for_lock
, str(_GetProcessStartTime(pid_for_lock
))))
270 def _InitDeviceLocked(self
, device
, tool
):
271 """Initializes the device_forwarder daemon for a specific device (once).
273 Note that the global lock must be acquired before calling this method. This
274 method kills any existing device_forwarder daemon on the device that could
275 be stale, pushes the latest version of the daemon (to the device) and starts
279 device: A DeviceUtils instance.
280 tool: Tool class to use to get wrapper, if necessary, for executing the
281 forwarder (see valgrind_tools.py).
283 device_serial
= str(device
)
284 if device_serial
in self
._initialized
_devices
:
286 Forwarder
._KillDeviceLocked
(device
, tool
)
287 device
.PushChangedFiles([(
288 self
._device
_forwarder
_path
_on
_host
,
289 Forwarder
._DEVICE
_FORWARDER
_FOLDER
)])
290 cmd
= '%s %s' % (tool
.GetUtilWrapper(), Forwarder
._DEVICE
_FORWARDER
_PATH
)
291 device
.RunShellCommand(
292 cmd
, env
={'LD_LIBRARY_PATH': Forwarder
._DEVICE
_FORWARDER
_FOLDER
})
293 self
._initialized
_devices
.add(device_serial
)
295 def _KillHostLocked(self
):
296 """Kills the forwarder process running on the host.
298 Note that the global lock must be acquired before calling this method.
300 logging
.info('Killing host_forwarder.')
301 (exit_code
, output
) = cmd_helper
.GetCmdStatusAndOutput(
302 [self
._host
_forwarder
_path
, '--kill-server'])
304 (exit_code
, output
) = cmd_helper
.GetCmdStatusAndOutput(
305 ['pkill', '-9', 'host_forwarder'])
307 raise Exception('%s exited with %d:\n%s' % (
308 self
._host
_forwarder
_path
, exit_code
, '\n'.join(output
)))
311 def _KillDeviceLocked(device
, tool
):
312 """Kills the forwarder process running on the device.
314 Note that the global lock must be acquired before calling this method.
317 device: Instance of DeviceUtils for talking to the device.
318 tool: Wrapper tool (e.g. valgrind) that can be used to execute the device
319 forwarder (see valgrind_tools.py).
321 logging
.info('Killing device_forwarder.')
322 Forwarder
._instance
._initialized
_devices
.discard(str(device
))
323 if not device
.FileExists(Forwarder
._DEVICE
_FORWARDER
_PATH
):
326 cmd
= '%s %s --kill-server' % (tool
.GetUtilWrapper(),
327 Forwarder
._DEVICE
_FORWARDER
_PATH
)
328 device
.RunShellCommand(
329 cmd
, env
={'LD_LIBRARY_PATH': Forwarder
._DEVICE
_FORWARDER
_FOLDER
})