Upstream version 5.34.104.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.realpath(main_module.__file__))
20   else:
21     return os.getcwd()
22
23
24 def GetTelemetryDir():
25   return os.path.normpath(os.path.join(
26       os.path.realpath(__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 def GetUnreservedAvailableLocalPort():
108   """Returns an available port on the system.
109
110   WARNING: This method does not reserve the port it returns, so it may be used
111   by something else before you get to use it. This can lead to flake.
112   """
113   tmp = socket.socket()
114   tmp.bind(('', 0))
115   port = tmp.getsockname()[1]
116   tmp.close()
117
118   return port
119
120
121 def CloseConnections(tab):
122   """Closes all TCP sockets held open by the browser."""
123   try:
124     tab.ExecuteJavaScript("""window.chrome && chrome.benchmarking &&
125                              chrome.benchmarking.closeConnections()""")
126   except Exception:
127     pass
128
129
130 def GetBuildDirectories():
131   """Yields all combination of Chromium build output directories."""
132   build_dirs = ['build',
133                 os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
134                 'xcodebuild']
135
136   build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64']
137
138   for build_dir in build_dirs:
139     for build_type in build_types:
140       yield build_dir, build_type
141
142 def FindSupportBinary(binary_name, executable=True):
143   """Returns the path to the given binary name."""
144   # TODO(tonyg/dtu): This should support finding binaries in cloud storage.
145   command = None
146   command_mtime = 0
147   required_mode = os.R_OK
148   if executable:
149     required_mode = os.X_OK
150
151   chrome_root = GetChromiumSrcDir()
152   for build_dir, build_type in GetBuildDirectories():
153     candidate = os.path.join(chrome_root, build_dir, build_type, binary_name)
154     if os.path.isfile(candidate) and os.access(candidate, required_mode):
155       candidate_mtime = os.stat(candidate).st_mtime
156       if candidate_mtime > command_mtime:
157         command = candidate
158         command_mtime = candidate_mtime
159
160   return command