reclient_helper.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # Copyright 2023 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. """This helper provides a build context that handles
  5. the reclient lifecycle safely. It will automatically start
  6. reproxy before running ninja and stop reproxy when build stops
  7. for any reason e.g. build completion, keyboard interrupt etc."""
  8. import contextlib
  9. import datetime
  10. import hashlib
  11. import os
  12. import shutil
  13. import socket
  14. import subprocess
  15. import sys
  16. import time
  17. import uuid
  18. import gclient_paths
  19. import reclient_metrics
  20. THIS_DIR = os.path.dirname(__file__)
  21. RECLIENT_LOG_CLEANUP = os.path.join(THIS_DIR, 'reclient_log_cleanup.py')
  22. def find_reclient_bin_dir():
  23. tools_path = gclient_paths.GetBuildtoolsPath()
  24. if not tools_path:
  25. return None
  26. reclient_bin_dir = os.path.join(tools_path, 'reclient')
  27. if os.path.isdir(reclient_bin_dir):
  28. return reclient_bin_dir
  29. return None
  30. def find_reclient_cfg():
  31. tools_path = gclient_paths.GetBuildtoolsPath()
  32. if not tools_path:
  33. return None
  34. reclient_cfg = os.path.join(tools_path, 'reclient_cfgs', 'reproxy.cfg')
  35. if os.path.isfile(reclient_cfg):
  36. return reclient_cfg
  37. return None
  38. def run(cmd_args):
  39. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  40. print(' '.join(cmd_args))
  41. return subprocess.call(cmd_args)
  42. def start_reproxy(reclient_cfg, reclient_bin_dir):
  43. return run([
  44. os.path.join(reclient_bin_dir,
  45. 'bootstrap' + gclient_paths.GetExeSuffix()),
  46. '--re_proxy=' + os.path.join(reclient_bin_dir,
  47. 'reproxy' + gclient_paths.GetExeSuffix()),
  48. '--cfg=' + reclient_cfg
  49. ])
  50. def stop_reproxy(reclient_cfg, reclient_bin_dir):
  51. return run([
  52. os.path.join(reclient_bin_dir,
  53. 'bootstrap' + gclient_paths.GetExeSuffix()), '--shutdown',
  54. '--cfg=' + reclient_cfg
  55. ])
  56. def find_ninja_out_dir(args):
  57. # Ninja uses getopt_long, which allows to intermix non-option arguments.
  58. # To leave non supported parameters untouched, we do not use getopt.
  59. for index, arg in enumerate(args[1:]):
  60. if arg == '-C':
  61. # + 1 to get the next argument and +1 because we trimmed off args[0]
  62. return args[index + 2]
  63. if arg.startswith('-C'):
  64. # Support -Cout/Default
  65. return arg[2:]
  66. return '.'
  67. def find_cache_dir(tmp_dir):
  68. """Helper to find the correct cache directory for a build.
  69. tmp_dir should be a build specific temp directory within the out directory.
  70. If this is called from within a gclient checkout, the cache dir will be:
  71. <gclient_root>/.reproxy_cache/md5(tmp_dir)/
  72. If this is not called from within a gclient checkout, the cache dir will be:
  73. tmp_dir/cache
  74. """
  75. gclient_root = gclient_paths.FindGclientRoot(os.getcwd())
  76. if gclient_root:
  77. return os.path.join(gclient_root, '.reproxy_cache',
  78. hashlib.md5(tmp_dir.encode()).hexdigest())
  79. return os.path.join(tmp_dir, 'cache')
  80. def auth_cache_status():
  81. cred_file = os.path.join(os.environ["RBE_cache_dir"], "reproxy.creds")
  82. if not os.path.isfile(cred_file):
  83. return "missing", "UNSPECIFIED"
  84. try:
  85. with open(cred_file) as f:
  86. status = "valid"
  87. mechanism = "UNSPECIFIED"
  88. for line in f.readlines():
  89. if "seconds:" in line:
  90. exp = int(line.strip()[len("seconds:"):].strip())
  91. if exp < (time.time() + 5 * 60):
  92. status = "expired"
  93. elif "mechanism:" in line:
  94. mechanism = line.strip()[len("mechanism:"):].strip()
  95. return status, mechanism
  96. except OSError:
  97. return "missing", "UNSPECIFIED"
  98. def get_hostname():
  99. hostname = socket.gethostname()
  100. # In case that returned an address, make a best effort attempt to get
  101. # the hostname and ignore any errors.
  102. try:
  103. return socket.gethostbyaddr(hostname)[0]
  104. except Exception:
  105. return hostname
  106. def set_reproxy_metrics_flags(tool):
  107. """Helper to setup metrics collection flags for reproxy.
  108. The following env vars are set if not already set:
  109. RBE_metrics_project=chromium-reclient-metrics
  110. RBE_invocation_id=$AUTONINJA_BUILD_ID
  111. RBE_metrics_table=rbe_metrics.builds
  112. RBE_metrics_labels=source=developer,tool={tool}
  113. RBE_metrics_prefix=go.chromium.org
  114. """
  115. autoninja_id = os.environ.get("AUTONINJA_BUILD_ID")
  116. if autoninja_id is not None:
  117. os.environ.setdefault("RBE_invocation_id",
  118. "%s/%s" % (get_hostname(), autoninja_id))
  119. os.environ.setdefault("RBE_metrics_project", "chromium-reclient-metrics")
  120. os.environ.setdefault("RBE_metrics_table", "rbe_metrics.builds")
  121. labels = "source=developer,tool=" + tool
  122. auth_status, auth_mechanism = auth_cache_status()
  123. labels += ",creds_cache_status=" + auth_status
  124. labels += ",creds_cache_mechanism=" + auth_mechanism
  125. os.environ.setdefault("RBE_metrics_labels", labels)
  126. os.environ.setdefault("RBE_metrics_prefix", "go.chromium.org")
  127. def remove_mdproxy_from_path():
  128. os.environ["PATH"] = os.pathsep.join(
  129. d for d in os.environ.get("PATH", "").split(os.pathsep)
  130. if "mdproxy" not in d)
  131. # Mockable datetime.datetime.utcnow for testing.
  132. def datetime_now():
  133. return datetime.datetime.utcnow()
  134. def set_reproxy_path_flags(out_dir, make_dirs=True):
  135. """Helper to setup the logs and cache directories for reclient.
  136. Creates the following directory structure if make_dirs is true:
  137. If in a gclient checkout
  138. out_dir/
  139. .reproxy_tmp/
  140. logs/
  141. <gclient_root>
  142. .reproxy_cache/
  143. md5(out_dir/.reproxy_tmp)/
  144. If not in a gclient checkout
  145. out_dir/
  146. .reproxy_tmp/
  147. logs/
  148. cache/
  149. The following env vars are set if not already set:
  150. RBE_output_dir=out_dir/.reproxy_tmp/logs
  151. RBE_proxy_log_dir=out_dir/.reproxy_tmp/logs
  152. RBE_log_dir=out_dir/.reproxy_tmp/logs
  153. RBE_cache_dir=out_dir/.reproxy_tmp/cache
  154. *Nix Only:
  155. RBE_server_address=unix://out_dir/.reproxy_tmp/reproxy.sock
  156. Windows Only:
  157. RBE_server_address=pipe://md5(out_dir/.reproxy_tmp)/reproxy.pipe
  158. """
  159. os.environ.setdefault("AUTONINJA_BUILD_ID", str(uuid.uuid4()))
  160. tmp_dir = os.path.abspath(os.path.join(out_dir, '.reproxy_tmp'))
  161. log_dir = os.path.join(tmp_dir, 'logs')
  162. run_log_dir = os.path.join(
  163. log_dir,
  164. datetime_now().strftime('%Y%m%dT%H%M%S.%f') + "_" +
  165. os.environ["AUTONINJA_BUILD_ID"])
  166. racing_dir = os.path.join(tmp_dir, 'racing')
  167. cache_dir = find_cache_dir(tmp_dir)
  168. if make_dirs:
  169. if os.path.isfile(os.path.join(log_dir, "rbe_metrics.txt")):
  170. try:
  171. # Delete entire log dir if it is in the old format
  172. # which had no subdirectories for each build.
  173. shutil.rmtree(log_dir)
  174. except OSError:
  175. print(
  176. "Couldn't clear logs because reproxy did "
  177. "not shutdown after the last build",
  178. file=sys.stderr)
  179. os.makedirs(tmp_dir, exist_ok=True)
  180. os.makedirs(log_dir, exist_ok=True)
  181. os.makedirs(run_log_dir, exist_ok=True)
  182. os.makedirs(cache_dir, exist_ok=True)
  183. os.makedirs(racing_dir, exist_ok=True)
  184. old_log_dirs = [
  185. d for d in os.listdir(log_dir)
  186. if os.path.isdir(os.path.join(log_dir, d))
  187. ]
  188. if len(old_log_dirs) > 5:
  189. old_log_dirs.sort(key=lambda dir: dir.split("_"), reverse=True)
  190. for d in old_log_dirs[5:]:
  191. shutil.rmtree(os.path.join(log_dir, d))
  192. os.environ.setdefault("RBE_output_dir", run_log_dir)
  193. os.environ.setdefault("RBE_proxy_log_dir", run_log_dir)
  194. os.environ.setdefault("RBE_log_dir", run_log_dir)
  195. os.environ.setdefault("RBE_cache_dir", cache_dir)
  196. os.environ.setdefault("RBE_racing_tmp_dir", racing_dir)
  197. if sys.platform.startswith('win'):
  198. pipe_dir = hashlib.md5(tmp_dir.encode()).hexdigest()
  199. os.environ.setdefault("RBE_server_address",
  200. "pipe://%s/reproxy.pipe" % pipe_dir)
  201. else:
  202. # unix domain socket has path length limit, so use fixed size path here.
  203. # ref: https://www.man7.org/linux/man-pages/man7/unix.7.html
  204. os.environ.setdefault(
  205. "RBE_server_address", "unix:///tmp/reproxy_%s.sock" %
  206. hashlib.sha256(tmp_dir.encode()).hexdigest())
  207. def set_racing_defaults():
  208. os.environ.setdefault("RBE_local_resource_fraction", "0.2")
  209. os.environ.setdefault("RBE_racing_bias", "0.95")
  210. def set_mac_defaults():
  211. # Reduce the cas concurrency on macs. Lower value doesn't impact
  212. # performance when on high-speed connection, but does show improvements
  213. # on easily congested networks.
  214. os.environ.setdefault("RBE_cas_concurrency", "100")
  215. @contextlib.contextmanager
  216. def build_context(argv, tool):
  217. # If use_remoteexec is set, but the reclient binaries or configs don't
  218. # exist, display an error message and stop. Otherwise, the build will
  219. # attempt to run with rewrapper wrapping actions, but will fail with
  220. # possible non-obvious problems.
  221. reclient_bin_dir = find_reclient_bin_dir()
  222. reclient_cfg = find_reclient_cfg()
  223. if reclient_bin_dir is None or reclient_cfg is None:
  224. print(
  225. 'Build is configured to use reclient but necessary binaries '
  226. "or config files can't be found.\n"
  227. 'Please check if `"download_remoteexec_cfg": True` custom var is '
  228. 'set in `.gclient`, and run `gclient sync`.',
  229. file=sys.stderr)
  230. yield 1
  231. return
  232. ninja_out = find_ninja_out_dir(argv)
  233. try:
  234. set_reproxy_path_flags(ninja_out)
  235. except OSError as e:
  236. print(f"Error creating reproxy_tmp in output dir: {e}", file=sys.stderr)
  237. yield 1
  238. return
  239. if reclient_metrics.check_status(ninja_out):
  240. set_reproxy_metrics_flags(tool)
  241. if os.environ.get('RBE_instance', None):
  242. print('WARNING: Using RBE_instance=%s\n' %
  243. os.environ.get('RBE_instance', ''))
  244. remote_disabled = os.environ.get('RBE_remote_disabled')
  245. if remote_disabled not in ('1', 't', 'T', 'true', 'TRUE', 'True'):
  246. set_racing_defaults()
  247. if sys.platform == "darwin":
  248. set_mac_defaults()
  249. # TODO(b/292523514) remove this once a fix is landed in reproxy
  250. remove_mdproxy_from_path()
  251. start = time.time()
  252. reproxy_ret_code = start_reproxy(reclient_cfg, reclient_bin_dir)
  253. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  254. elapsed = time.time() - start
  255. print('%1.3f s to start reproxy' % elapsed)
  256. if reproxy_ret_code != 0:
  257. yield reproxy_ret_code
  258. return
  259. try:
  260. yield
  261. finally:
  262. start = time.time()
  263. stop_reproxy(reclient_cfg, reclient_bin_dir)
  264. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  265. elapsed = time.time() - start
  266. print('%1.3f s to stop reproxy' % elapsed)