Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / tools / telemetry / telemetry / core / util.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 import inspect
5 import logging
6 import os
7 import socket
8 import sys
9 import time
10
11
12 class TimeoutException(Exception):
13   pass
14
15
16 def GetBaseDir():
17   main_module = sys.modules['__main__']
18   if hasattr(main_module, '__file__'):
19     return os.path.dirname(os.path.abspath(main_module.__file__))
20   else:
21     return os.getcwd()
22
23
24 def GetTelemetryDir():
25   return os.path.normpath(os.path.join(
26       __file__, os.pardir, os.pardir, os.pardir))
27
28
29 def GetUnittestDataDir():
30   return os.path.join(GetTelemetryDir(), 'unittest_data')
31
32
33 def GetChromiumSrcDir():
34   return os.path.normpath(os.path.join(GetTelemetryDir(), os.pardir, os.pardir))
35
36
37 def AddDirToPythonPath(*path_parts):
38   path = os.path.abspath(os.path.join(*path_parts))
39   if os.path.isdir(path) and path not in sys.path:
40     sys.path.append(path)
41
42
43 def WaitFor(condition, timeout):
44   """Waits for up to |timeout| secs for the function |condition| to return True.
45
46   Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
47
48   Returns:
49     Result of |condition| function (if present).
50   """
51   min_poll_interval =   0.1
52   max_poll_interval =   5
53   output_interval   = 300
54
55   def GetConditionString():
56     if condition.__name__ == '<lambda>':
57       try:
58         return inspect.getsource(condition).strip()
59       except IOError:
60         pass
61     return condition.__name__
62
63   start_time = time.time()
64   last_output_time = start_time
65   while True:
66     res = condition()
67     if res:
68       return res
69     now = time.time()
70     elapsed_time = now - start_time
71     last_output_elapsed_time = now - last_output_time
72     if elapsed_time > timeout:
73       raise TimeoutException('Timed out while waiting %ds for %s.' %
74                              (timeout, GetConditionString()))
75     if last_output_elapsed_time > output_interval:
76       logging.info('Continuing to wait %ds for %s. Elapsed: %ds.',
77                    timeout, GetConditionString(), elapsed_time)
78       last_output_time = time.time()
79     poll_interval = min(max(elapsed_time / 10., min_poll_interval),
80                         max_poll_interval)
81     time.sleep(poll_interval)
82
83
84 def FindElementAndPerformAction(tab, text, callback_code):
85   """JavaScript snippet for finding an element with a given text on a page."""
86   code = """
87       (function() {
88         var callback_function = """ + callback_code + """;
89         function _findElement(element, text) {
90           if (element.innerHTML == text) {
91             callback_function
92             return element;
93           }
94           for (var i in element.childNodes) {
95             var found = _findElement(element.childNodes[i], text);
96             if (found)
97               return found;
98           }
99           return null;
100         }
101         var _element = _findElement(document, \"""" + text + """\");
102         return callback_function(_element);
103       })();"""
104   return tab.EvaluateJavaScript(code)
105
106
107 class PortPair(object):
108   def __init__(self, local_port, remote_port):
109     self.local_port = local_port
110     self.remote_port = remote_port
111
112
113 def GetUnreservedAvailableLocalPort():
114   """Returns an available port on the system.
115
116   WARNING: This method does not reserve the port it returns, so it may be used
117   by something else before you get to use it. This can lead to flake.
118   """
119   tmp = socket.socket()
120   tmp.bind(('', 0))
121   port = tmp.getsockname()[1]
122   tmp.close()
123
124   return port
125
126
127 def CloseConnections(tab):
128   """Closes all TCP sockets held open by the browser."""
129   try:
130     tab.ExecuteJavaScript("""window.chrome && chrome.benchmarking &&
131                              chrome.benchmarking.closeConnections()""")
132   except Exception:
133     pass
134
135
136 def GetBuildDirectories():
137   """Yields all combination of Chromium build output directories."""
138   build_dirs = ['build',
139                 os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
140                 'xcodebuild']
141
142   build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64']
143
144   for build_dir in build_dirs:
145     for build_type in build_types:
146       yield build_dir, build_type
147
148 def FindSupportBinary(binary_name, executable=True):
149   """Returns the path to the given binary name."""
150   # TODO(tonyg/dtu): This should support finding binaries in cloud storage.
151   command = None
152   command_mtime = 0
153   required_mode = os.R_OK
154   if executable:
155     required_mode = os.X_OK
156
157   chrome_root = GetChromiumSrcDir()
158   for build_dir, build_type in GetBuildDirectories():
159     candidate = os.path.join(chrome_root, build_dir, build_type, binary_name)
160     if os.path.isfile(candidate) and os.access(candidate, required_mode):
161       candidate_mtime = os.stat(candidate).st_mtime
162       if candidate_mtime > command_mtime:
163         command = candidate
164         command_mtime = candidate_mtime
165
166   return command