reclient_helper.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 atexit
  9. import contextlib
  10. import datetime
  11. import hashlib
  12. import os
  13. import shutil
  14. import socket
  15. import subprocess
  16. import sys
  17. import time
  18. import uuid
  19. import gclient_paths
  20. import ninja
  21. import siso
  22. THIS_DIR = os.path.dirname(__file__)
  23. RECLIENT_LOG_CLEANUP = os.path.join(THIS_DIR, 'reclient_log_cleanup.py')
  24. def find_reclient_bin_dir():
  25. tools_path = gclient_paths.GetBuildtoolsPath()
  26. if not tools_path:
  27. return None
  28. reclient_bin_dir = os.path.join(tools_path, 'reclient')
  29. if os.path.isdir(reclient_bin_dir):
  30. return reclient_bin_dir
  31. return None
  32. def find_reclient_cfg():
  33. tools_path = gclient_paths.GetBuildtoolsPath()
  34. if not tools_path:
  35. return None
  36. reclient_cfg = os.path.join(tools_path, 'reclient_cfgs', 'reproxy.cfg')
  37. if os.path.isfile(reclient_cfg):
  38. return reclient_cfg
  39. return None
  40. def run(cmd_args):
  41. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  42. print(' '.join(cmd_args))
  43. return subprocess.call(cmd_args)
  44. def start_reproxy(reclient_cfg, reclient_bin_dir):
  45. return run([
  46. os.path.join(reclient_bin_dir,
  47. 'bootstrap' + gclient_paths.GetExeSuffix()),
  48. '--re_proxy=' + os.path.join(reclient_bin_dir,
  49. 'reproxy' + gclient_paths.GetExeSuffix()),
  50. '--cfg=' + reclient_cfg
  51. ])
  52. def stop_reproxy(reclient_cfg, reclient_bin_dir):
  53. return run([
  54. os.path.join(reclient_bin_dir,
  55. 'bootstrap' + gclient_paths.GetExeSuffix()), '--shutdown',
  56. '--cfg=' + reclient_cfg
  57. ])
  58. def find_ninja_out_dir(args):
  59. # Ninja uses getopt_long, which allows to intermix non-option arguments.
  60. # To leave non supported parameters untouched, we do not use getopt.
  61. for index, arg in enumerate(args[1:]):
  62. if arg == '-C':
  63. # + 1 to get the next argument and +1 because we trimmed off args[0]
  64. return args[index + 2]
  65. if arg.startswith('-C'):
  66. # Support -Cout/Default
  67. return arg[2:]
  68. return '.'
  69. def find_cache_dir(tmp_dir):
  70. """Helper to find the correct cache directory for a build.
  71. tmp_dir should be a build specific temp directory within the out directory.
  72. If this is called from within a gclient checkout, the cache dir will be:
  73. <gclient_root>/.reproxy_cache/md5(tmp_dir)/
  74. If this is not called from within a gclient checkout, the cache dir will be:
  75. tmp_dir/cache
  76. """
  77. gclient_root = gclient_paths.FindGclientRoot(os.getcwd())
  78. if gclient_root:
  79. return os.path.join(gclient_root, '.reproxy_cache',
  80. hashlib.md5(tmp_dir.encode()).hexdigest())
  81. return os.path.join(tmp_dir, 'cache')
  82. def auth_cache_status():
  83. cred_file = os.path.join(os.environ["RBE_cache_dir"], "reproxy.creds")
  84. if not os.path.isfile(cred_file):
  85. return "missing", "UNSPECIFIED"
  86. try:
  87. with open(cred_file) as f:
  88. status = "valid"
  89. mechanism = "UNSPECIFIED"
  90. for line in f.readlines():
  91. if "seconds:" in line:
  92. exp = int(line.strip()[len("seconds:"):].strip())
  93. if exp < (time.time() + 5 * 60):
  94. status = "expired"
  95. elif "mechanism:" in line:
  96. mechanism = line.strip()[len("mechanism:"):].strip()
  97. return status, mechanism
  98. except OSError:
  99. return "missing", "UNSPECIFIED"
  100. def get_hostname():
  101. hostname = socket.gethostname()
  102. # In case that returned an address, make a best effort attempt to get
  103. # the hostname and ignore any errors.
  104. try:
  105. return socket.gethostbyaddr(hostname)[0]
  106. except Exception:
  107. return hostname
  108. def set_reproxy_metrics_flags(tool):
  109. """Helper to setup metrics collection flags for reproxy.
  110. The following env vars are set if not already set:
  111. RBE_metrics_project=chromium-reclient-metrics
  112. RBE_invocation_id=$AUTONINJA_BUILD_ID
  113. RBE_metrics_table=rbe_metrics.builds
  114. RBE_metrics_labels=\
  115. source=developer,\
  116. tool={tool},\
  117. creds_cache_status={auth_status},\
  118. creds_cache_mechanism={auth_mechanism},\
  119. host={host}
  120. RBE_metrics_prefix=go.chromium.org
  121. """
  122. autoninja_id = os.environ.get("AUTONINJA_BUILD_ID")
  123. if autoninja_id is not None:
  124. os.environ.setdefault("RBE_invocation_id", autoninja_id)
  125. os.environ.setdefault("RBE_metrics_project", "chromium-reclient-metrics")
  126. os.environ.setdefault("RBE_metrics_table", "rbe_metrics.builds")
  127. labels = "source=developer,tool=" + tool
  128. auth_status, auth_mechanism = auth_cache_status()
  129. labels += ",creds_cache_status=" + auth_status
  130. labels += ",creds_cache_mechanism=" + auth_mechanism
  131. labels += ",host=" + get_hostname()
  132. os.environ.setdefault("RBE_metrics_labels", labels)
  133. os.environ.setdefault("RBE_metrics_prefix", "go.chromium.org")
  134. def remove_mdproxy_from_path():
  135. os.environ["PATH"] = os.pathsep.join(
  136. d for d in os.environ.get("PATH", "").split(os.pathsep)
  137. if "mdproxy" not in d)
  138. # Mockable datetime.datetime.utcnow for testing.
  139. def datetime_now():
  140. return datetime.datetime.utcnow()
  141. # Deletes the tree at dir if it exists.
  142. def rmtree_if_exists(rm_dir):
  143. if os.path.exists(rm_dir) and os.path.isdir(rm_dir):
  144. shutil.rmtree(rm_dir, ignore_errors=True)
  145. def set_reproxy_path_flags(out_dir, make_dirs=True):
  146. """Helper to setup the logs and cache directories for reclient.
  147. Creates the following directory structure if make_dirs is true:
  148. If in a gclient checkout
  149. out_dir/
  150. .reproxy_tmp/
  151. logs/
  152. <gclient_root>
  153. .reproxy_cache/
  154. md5(out_dir/.reproxy_tmp)/
  155. If not in a gclient checkout
  156. out_dir/
  157. .reproxy_tmp/
  158. logs/
  159. cache/
  160. The following env vars are set if not already set:
  161. RBE_output_dir=out_dir/.reproxy_tmp/logs
  162. RBE_proxy_log_dir=out_dir/.reproxy_tmp/logs
  163. RBE_log_dir=out_dir/.reproxy_tmp/logs
  164. RBE_cache_dir=out_dir/.reproxy_tmp/cache
  165. *Nix Only:
  166. RBE_server_address=unix://out_dir/.reproxy_tmp/reproxy.sock
  167. Windows Only:
  168. RBE_server_address=pipe://md5(out_dir/.reproxy_tmp)/reproxy.pipe
  169. """
  170. os.environ.setdefault("AUTONINJA_BUILD_ID", str(uuid.uuid4()))
  171. run_sub_dir = datetime_now().strftime(
  172. '%Y%m%dT%H%M%S.%f') + "_" + os.environ["AUTONINJA_BUILD_ID"]
  173. tmp_dir = os.path.abspath(os.path.join(out_dir, '.reproxy_tmp'))
  174. log_dir = os.path.join(tmp_dir, 'logs')
  175. run_log_dir = os.path.join(log_dir, run_sub_dir)
  176. racing_dir = os.path.join(tmp_dir, 'racing')
  177. run_racing_dir = os.path.join(racing_dir, run_sub_dir)
  178. cache_dir = find_cache_dir(tmp_dir)
  179. atexit.register(rmtree_if_exists, run_racing_dir)
  180. if make_dirs:
  181. if os.path.isfile(os.path.join(log_dir, "rbe_metrics.txt")):
  182. try:
  183. # Delete entire log dir if it is in the old format
  184. # which had no subdirectories for each build.
  185. shutil.rmtree(log_dir)
  186. except OSError:
  187. print(
  188. "Couldn't clear logs because reproxy did "
  189. "not shutdown after the last build",
  190. file=sys.stderr)
  191. os.makedirs(tmp_dir, exist_ok=True)
  192. os.makedirs(log_dir, exist_ok=True)
  193. os.makedirs(run_log_dir, exist_ok=True)
  194. os.makedirs(cache_dir, exist_ok=True)
  195. os.makedirs(racing_dir, exist_ok=True)
  196. os.makedirs(run_racing_dir, exist_ok=True)
  197. old_log_dirs = [
  198. d for d in os.listdir(log_dir)
  199. if os.path.isdir(os.path.join(log_dir, d))
  200. ]
  201. if len(old_log_dirs) > 5:
  202. old_log_dirs.sort(key=lambda dir: dir.split("_"), reverse=True)
  203. for d in old_log_dirs[5:]:
  204. shutil.rmtree(os.path.join(log_dir, d))
  205. os.environ.setdefault("RBE_output_dir", run_log_dir)
  206. os.environ.setdefault("RBE_proxy_log_dir", run_log_dir)
  207. os.environ.setdefault("RBE_log_dir", run_log_dir)
  208. os.environ.setdefault("RBE_cache_dir", cache_dir)
  209. os.environ.setdefault("RBE_racing_tmp_dir", run_racing_dir)
  210. if sys.platform.startswith('win'):
  211. pipe_dir = hashlib.sha256(run_log_dir.encode()).hexdigest()
  212. os.environ.setdefault("RBE_server_address",
  213. "pipe://%s/reproxy.pipe" % pipe_dir)
  214. else:
  215. # unix domain socket has path length limit, so use fixed size path here.
  216. # ref: https://www.man7.org/linux/man-pages/man7/unix.7.html
  217. os.environ.setdefault(
  218. "RBE_server_address", "unix:///tmp/reproxy_%s.sock" %
  219. hashlib.sha256(run_log_dir.encode()).hexdigest())
  220. def set_racing_defaults():
  221. os.environ.setdefault("RBE_local_resource_fraction", "0.2")
  222. os.environ.setdefault("RBE_racing_bias", "0.95")
  223. def set_mac_defaults():
  224. # Reduce the cas concurrency on macs. Lower value doesn't impact
  225. # performance when on high-speed connection, but does show improvements
  226. # on easily congested networks.
  227. os.environ.setdefault("RBE_cas_concurrency", "100")
  228. # Enable the deps cache on macs. Mac needs a larger deps cache as it
  229. # seems to have larger dependency sets per action.
  230. os.environ.setdefault("RBE_enable_deps_cache", "true")
  231. os.environ.setdefault("RBE_deps_cache_max_mb", "1024")
  232. def set_win_defaults():
  233. # Enable the deps cache on windows. This makes a notable improvement
  234. # in performance at the cost of a ~200MB cache file.
  235. os.environ.setdefault("RBE_enable_deps_cache", "true")
  236. # Reduce local resource fraction used to do local compile actions on
  237. # windows, to try and prevent machine saturation.
  238. os.environ.setdefault("RBE_local_resource_fraction", "0.05")
  239. # Set execution strategy to remote_local_fallback while racing performance
  240. # on windows is addressed.
  241. os.environ.setdefault("RBE_exec_strategy", "remote_local_fallback")
  242. # Turn off creds caching for windows, as luci-auth as credshelper shouldn't
  243. # use it.
  244. os.environ.setdefault("RBE_enable_creds_cache", "false")
  245. # Extend timeouts on windows
  246. os.environ.setdefault("RBE_exec_timeout","4m")
  247. os.environ.setdefault("RBE_reclient_timeout","8m")
  248. def workspace_is_cog():
  249. return sys.platform == "linux" and os.path.realpath(
  250. os.getcwd()).startswith("/google/cog")
  251. # pylint: disable=line-too-long
  252. def reclient_setup_docs_url():
  253. if sys.platform == "darwin":
  254. return "https://chromium.googlesource.com/chromium/src/+/main/docs/mac_build_instructions.md#use-reclient"
  255. if sys.platform.startswith("win"):
  256. return "https://chromium.googlesource.com/chromium/src/+/main/docs/windows_build_instructions.md#use-reclient"
  257. return "https://chromium.googlesource.com/chromium/src/+/main/docs/linux/build_instructions.md#use-reclient"
  258. @contextlib.contextmanager
  259. def build_context(argv, tool, should_collect_logs):
  260. # If use_remoteexec is set, but the reclient binaries or configs don't
  261. # exist, display an error message and stop. Otherwise, the build will
  262. # attempt to run with rewrapper wrapping actions, but will fail with
  263. # possible non-obvious problems.
  264. reclient_bin_dir = find_reclient_bin_dir()
  265. reclient_cfg = find_reclient_cfg()
  266. if reclient_bin_dir is None or reclient_cfg is None:
  267. print(
  268. 'Build is configured to use reclient but necessary binaries '
  269. "or config files can't be found.\n"
  270. 'Please check if `"download_remoteexec_cfg": True` custom var is '
  271. 'set in `.gclient`, and run `gclient sync`.',
  272. file=sys.stderr)
  273. yield 1
  274. return
  275. ninja_out = find_ninja_out_dir(argv)
  276. try:
  277. set_reproxy_path_flags(ninja_out)
  278. except OSError as e:
  279. print(f"Error creating reproxy_tmp in output dir: {e}", file=sys.stderr)
  280. yield 1
  281. return
  282. if should_collect_logs:
  283. set_reproxy_metrics_flags(tool)
  284. if os.environ.get('RBE_instance', None):
  285. print('WARNING: Using RBE_instance=%s\n' %
  286. os.environ.get('RBE_instance', ''))
  287. remote_disabled = os.environ.get('RBE_remote_disabled')
  288. if remote_disabled not in ('1', 't', 'T', 'true', 'TRUE', 'True'):
  289. # If we are building inside a Cog workspace, racing is likely not a
  290. # performance improvement, so we disable it by default.
  291. if workspace_is_cog():
  292. os.environ.setdefault("RBE_exec_strategy", "remote_local_fallback")
  293. set_racing_defaults()
  294. if sys.platform == "darwin":
  295. set_mac_defaults()
  296. if sys.platform.startswith("win"):
  297. set_win_defaults()
  298. # TODO(b/292523514) remove this once a fix is landed in reproxy
  299. remove_mdproxy_from_path()
  300. start = time.time()
  301. reproxy_ret_code = start_reproxy(reclient_cfg, reclient_bin_dir)
  302. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  303. elapsed = time.time() - start
  304. print('%1.3fs to start reproxy' % elapsed)
  305. if reproxy_ret_code != 0:
  306. print(f'''Failed to start reproxy!
  307. See above error message for details.
  308. Ensure you have completed the reproxy setup instructions:
  309. {reclient_setup_docs_url()}''',
  310. file=sys.stderr)
  311. yield reproxy_ret_code
  312. return
  313. try:
  314. yield
  315. finally:
  316. start = time.time()
  317. stop_reproxy(reclient_cfg, reclient_bin_dir)
  318. if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
  319. elapsed = time.time() - start
  320. print('%1.3fs to stop reproxy' % elapsed)
  321. def run_ninja(ninja_cmd, should_collect_logs=False):
  322. """Runs Ninja in build_context()."""
  323. # TODO: crbug.com/345113094 - rename the `tool` label to `ninja`.
  324. with build_context(ninja_cmd, "ninja_reclient",
  325. should_collect_logs) as ret_code:
  326. if ret_code:
  327. return ret_code
  328. try:
  329. return ninja.main(ninja_cmd)
  330. except KeyboardInterrupt:
  331. print("Shutting down reproxy...", file=sys.stderr)
  332. return 1
  333. def run_siso(siso_cmd, should_collect_logs=False):
  334. """Runs Siso in build_context()."""
  335. # TODO: crbug.com/345113094 - rename the `autosiso` label to `siso`.
  336. with build_context(siso_cmd, "autosiso", should_collect_logs) as ret_code:
  337. if ret_code:
  338. return ret_code
  339. try:
  340. return siso.main(siso_cmd)
  341. except KeyboardInterrupt:
  342. print("Shutting down reproxy...", file=sys.stderr)
  343. return 1