- add sources.
[platform/framework/web/crosswalk.git] / src / build / android / pylib / forwarder.py
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.
4
5 import fcntl
6 import logging
7 import os
8 import psutil
9 import re
10 import sys
11 import time
12
13 import android_commands
14 import cmd_helper
15 import constants
16
17 from pylib import valgrind_tools
18
19
20 def _GetProcessStartTime(pid):
21   return psutil.Process(pid).create_time
22
23
24 class _FileLock(object):
25   """With statement-aware implementation of a file lock.
26
27   File locks are needed for cross-process synchronization when the
28   multiprocessing Python module is used.
29   """
30   def __init__(self, path):
31     self._path = path
32
33   def __enter__(self):
34     self._fd = os.open(self._path, os.O_RDONLY | os.O_CREAT)
35     if self._fd < 0:
36       raise Exception('Could not open file %s for reading' % self._path)
37     fcntl.flock(self._fd, fcntl.LOCK_EX)
38
39   def __exit__(self, type, value, traceback):
40     fcntl.flock(self._fd, fcntl.LOCK_UN)
41     os.close(self._fd)
42
43
44 class Forwarder(object):
45   """Thread-safe class to manage port forwards from the device to the host."""
46
47   _DEVICE_FORWARDER_FOLDER = (constants.TEST_EXECUTABLE_DIR +
48                               '/forwarder/')
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'
54
55   _instance = None
56
57   @staticmethod
58   def UseMultiprocessing():
59     """Tells the forwarder that multiprocessing is used."""
60     os.environ[Forwarder._MULTIPROCESSING_ENV_VAR] = '1'
61
62   @staticmethod
63   def Map(port_pairs, adb, tool=None):
64     """Runs the forwarder.
65
66     Args:
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).
75
76     Raises:
77       Exception on failure to forward the port.
78     """
79     if not tool:
80       tool = valgrind_tools.CreateTool(None, adb)
81     with _FileLock(Forwarder._LOCK_PATH):
82       instance = Forwarder._GetInstanceLocked(tool)
83       instance._InitDeviceLocked(adb, tool)
84
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)
90
91       for redirection_command in redirection_commands:
92         try:
93           (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
94               [instance._host_forwarder_path] + redirection_command)
95         except OSError as e:
96           if e.errno == 2:
97             raise Exception('Unable to start host forwarder. Make sure you have'
98                             ' built host_forwarder.')
99           else: raise
100         if exit_code != 0:
101           raise Exception('%s exited with %d:\n%s' % (
102               instance._host_forwarder_path, exit_code, '\n'.join(output)))
103         tokens = output.split(':')
104         if len(tokens) != 2:
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)
114
115   @staticmethod
116   def UnmapDevicePort(device_port, adb):
117     """Unmaps a previously forwarded device port.
118
119     Args:
120       adb: An AndroidCommands instance.
121       device_port: A previously forwarded port (through Map()).
122     """
123     with _FileLock(Forwarder._LOCK_PATH):
124       Forwarder._UnmapDevicePortLocked(device_port, adb)
125
126   @staticmethod
127   def UnmapAllDevicePorts(adb):
128     """Unmaps all the previously forwarded ports for the provided device.
129
130     Args:
131       adb: An AndroidCommands instance.
132       port_pairs: A list of tuples (device_port, host_port) to unmap.
133     """
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)
141
142   @staticmethod
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)
148       return device_port
149
150   @staticmethod
151   def _GetInstanceLocked(tool):
152     """Returns the singleton instance.
153
154     Note that the global lock must be acquired before calling this method.
155
156     Args:
157       tool: Tool class to use to get wrapper, if necessary, for executing the
158             forwarder (see valgrind_tools.py).
159     """
160     if not Forwarder._instance:
161       Forwarder._instance = Forwarder(tool)
162     return Forwarder._instance
163
164   def __init__(self, tool):
165     """Constructs a new instance of Forwarder.
166
167     Note that Forwarder is a singleton therefore this constructor should be
168     called only once.
169
170     Args:
171       tool: Tool class to use to get wrapper, if necessary, for executing the
172             forwarder (see valgrind_tools.py).
173     """
174     assert not Forwarder._instance
175     self._tool = tool
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()
185
186   @staticmethod
187   def _UnmapDevicePortLocked(device_port, adb):
188     """Internal method used by UnmapDevicePort().
189
190     Note that the global lock must be acquired before calling this method.
191     """
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)
197       return
198     redirection_command = ['--serial-id=' + serial, '--unmap', str(device_port)]
199     (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
200         [instance._host_forwarder_path] + redirection_command)
201     if exit_code != 0:
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]
207
208   @staticmethod
209   def _GetPidForLock():
210     """Returns the PID used for host_forwarder initialization.
211
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.
216     """
217     use_multiprocessing = Forwarder._MULTIPROCESSING_ENV_VAR in os.environ
218     return os.getppid() if use_multiprocessing else os.getpid()
219
220   def _InitHostLocked(self):
221     """Initializes the host forwarder daemon.
222
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.
225     """
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)):
236             return
237       self._KillHostLocked()
238       pid_file.seek(0)
239       pid_file.write(
240           '%s:%s' % (pid_for_lock, str(_GetProcessStartTime(pid_for_lock))))
241
242   def _InitDeviceLocked(self, adb, tool):
243     """Initializes the device_forwarder daemon for a specific device (once).
244
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
248     it.
249
250     Args:
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).
254     """
255     device_serial = adb.Adb().GetSerialNumber()
256     if device_serial in self._initialized_devices:
257       return
258     Forwarder._KillDeviceLocked(adb, tool)
259     adb.PushIfNeeded(
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))
265     if exit_code != 0:
266       raise Exception(
267           'Failed to start device forwarder:\n%s' % '\n'.join(output))
268     self._initialized_devices.add(device_serial)
269
270   def _KillHostLocked(self):
271     """Kills the forwarder process running on the host.
272
273     Note that the global lock must be acquired before calling this method.
274     """
275     logging.info('Killing host_forwarder.')
276     (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
277         [self._host_forwarder_path, '--kill-server'])
278     if exit_code != 0:
279       (exit_code, output) = cmd_helper.GetCmdStatusAndOutput(
280           ['pkill', '-9', 'host_forwarder'])
281       if exit_code != 0:
282         raise Exception('%s exited with %d:\n%s' % (
283               self._host_forwarder_path, exit_code, '\n'.join(output)))
284
285   @staticmethod
286   def _KillDeviceLocked(adb, tool):
287     """Kills the forwarder process running on the device.
288
289     Note that the global lock must be acquired before calling this method.
290
291     Args:
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).
295     """
296     logging.info('Killing device_forwarder.')
297     if not adb.FileExistsOnDevice(Forwarder._DEVICE_FORWARDER_PATH):
298       return
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.
305     timeout_sec = 5
306     processes_killed = adb.KillAllBlocking('device_forwarder', timeout_sec)
307     if not processes_killed:
308       pids = adb.ExtractPid('device_forwarder')
309       if pids:
310         raise Exception('Timed out while killing device_forwarder')