PageRenderTime 83ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/telemetry/telemetry/core/util.py

https://gitlab.com/jonnialva90/iridium-browser
Python | 166 lines | 132 code | 20 blank | 14 comment | 9 complexity | 90e5d8f445076c37921dba599c702dbd MD5 | raw file
  1. # Copyright 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 glob
  5. import imp
  6. import inspect
  7. import logging
  8. import os
  9. import socket
  10. import sys
  11. import time
  12. from telemetry.core import exceptions
  13. def GetBaseDir():
  14. main_module = sys.modules['__main__']
  15. if hasattr(main_module, '__file__'):
  16. return os.path.dirname(os.path.abspath(main_module.__file__))
  17. else:
  18. return os.getcwd()
  19. def GetTelemetryDir():
  20. return os.path.normpath(os.path.join(
  21. __file__, os.pardir, os.pardir, os.pardir))
  22. def GetTelemetryThirdPartyDir():
  23. return os.path.normpath(os.path.join(
  24. __file__, os.pardir, os.pardir, os.pardir, 'third_party'))
  25. def GetUnittestDataDir():
  26. return os.path.join(GetTelemetryDir(),
  27. 'telemetry', 'internal', 'testing')
  28. def GetChromiumSrcDir():
  29. return os.path.normpath(os.path.join(GetTelemetryDir(), os.pardir, os.pardir))
  30. _counter = [0]
  31. def _GetUniqueModuleName():
  32. _counter[0] += 1
  33. return "page_set_module_" + str(_counter[0])
  34. def GetPythonPageSetModule(file_path):
  35. return imp.load_source(_GetUniqueModuleName(), file_path)
  36. def WaitFor(condition, timeout):
  37. """Waits for up to |timeout| secs for the function |condition| to return True.
  38. Polling frequency is (elapsed_time / 10), with a min of .1s and max of 5s.
  39. Returns:
  40. Result of |condition| function (if present).
  41. """
  42. min_poll_interval = 0.1
  43. max_poll_interval = 5
  44. output_interval = 300
  45. def GetConditionString():
  46. if condition.__name__ == '<lambda>':
  47. try:
  48. return inspect.getsource(condition).strip()
  49. except IOError:
  50. pass
  51. return condition.__name__
  52. start_time = time.time()
  53. last_output_time = start_time
  54. while True:
  55. res = condition()
  56. if res:
  57. return res
  58. now = time.time()
  59. elapsed_time = now - start_time
  60. last_output_elapsed_time = now - last_output_time
  61. if elapsed_time > timeout:
  62. raise exceptions.TimeoutException('Timed out while waiting %ds for %s.' %
  63. (timeout, GetConditionString()))
  64. if last_output_elapsed_time > output_interval:
  65. logging.info('Continuing to wait %ds for %s. Elapsed: %ds.',
  66. timeout, GetConditionString(), elapsed_time)
  67. last_output_time = time.time()
  68. poll_interval = min(max(elapsed_time / 10., min_poll_interval),
  69. max_poll_interval)
  70. time.sleep(poll_interval)
  71. class PortKeeper(object):
  72. """Port keeper hold an available port on the system.
  73. Before actually use the port, you must call Release().
  74. """
  75. def __init__(self):
  76. self._temp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  77. self._temp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  78. self._temp_socket.bind(('', 0))
  79. self._port = self._temp_socket.getsockname()[1]
  80. @property
  81. def port(self):
  82. return self._port
  83. def Release(self):
  84. assert self._temp_socket, 'Already released'
  85. self._temp_socket.close()
  86. self._temp_socket = None
  87. def GetUnreservedAvailableLocalPort():
  88. """Returns an available port on the system.
  89. WARNING: This method does not reserve the port it returns, so it may be used
  90. by something else before you get to use it. This can lead to flake.
  91. """
  92. tmp = socket.socket()
  93. tmp.bind(('', 0))
  94. port = tmp.getsockname()[1]
  95. tmp.close()
  96. return port
  97. def GetBuildDirectories():
  98. """Yields all combination of Chromium build output directories."""
  99. build_dirs = ['build',
  100. os.path.basename(os.environ.get('CHROMIUM_OUT_DIR', 'out')),
  101. 'xcodebuild']
  102. build_types = ['Debug', 'Debug_x64', 'Release', 'Release_x64', 'Default']
  103. for build_dir in build_dirs:
  104. for build_type in build_types:
  105. yield build_dir, build_type
  106. def GetSequentialFileName(base_name):
  107. """Returns the next sequential file name based on |base_name| and the
  108. existing files. base_name should not contain extension.
  109. e.g: if base_name is /tmp/test, and /tmp/test_000.json,
  110. /tmp/test_001.mp3 exist, this returns /tmp/test_002. In case no
  111. other sequential file name exist, this will return /tmp/test_000
  112. """
  113. name, ext = os.path.splitext(base_name)
  114. assert ext == '', 'base_name cannot contain file extension.'
  115. index = 0
  116. while True:
  117. output_name = '%s_%03d' % (name, index)
  118. if not glob.glob(output_name + '.*'):
  119. break
  120. index = index + 1
  121. return output_name
  122. def IsRunningOnCrosDevice():
  123. """Returns True if we're on a ChromeOS device."""
  124. lsb_release = '/etc/lsb-release'
  125. if sys.platform.startswith('linux') and os.path.exists(lsb_release):
  126. with open(lsb_release, 'r') as f:
  127. res = f.read()
  128. if res.count('CHROMEOS_RELEASE_NAME'):
  129. return True
  130. return False