blob: 1570d4953856439bfc0e5c251c26fddd6e915df3 [file] [log] [blame]
Junji Watanabe607284d2023-04-20 03:14:52 +00001# 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
5the reclient lifecycle safely. It will automatically start
6reproxy before running ninja and stop reproxy when build stops
7for any reason e.g. build completion, keyboard interrupt etc."""
8
9import contextlib
10import hashlib
11import os
12import subprocess
13import sys
14
15import gclient_paths
16
17
18def find_reclient_bin_dir():
19 tools_path = gclient_paths.GetBuildtoolsPath()
20 if not tools_path:
21 return None
22
23 reclient_bin_dir = os.path.join(tools_path, 'reclient')
24 if os.path.isdir(reclient_bin_dir):
25 return reclient_bin_dir
26 return None
27
28
29def find_reclient_cfg():
30 tools_path = gclient_paths.GetBuildtoolsPath()
31 if not tools_path:
32 return None
33
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
39
40def run(cmd_args):
41 if os.environ.get('NINJA_SUMMARIZE_BUILD') == '1':
42 print(' '.join(cmd_args))
43 return subprocess.call(cmd_args)
44
45
46def start_reproxy(reclient_cfg, reclient_bin_dir):
47 return run([
48 os.path.join(reclient_bin_dir, 'bootstrap'),
49 '--re_proxy=' + os.path.join(reclient_bin_dir, 'reproxy'),
50 '--cfg=' + reclient_cfg
51 ])
52
53
54def stop_reproxy(reclient_cfg, reclient_bin_dir):
55 return run([
56 os.path.join(reclient_bin_dir, 'bootstrap'), '--shutdown',
57 '--cfg=' + reclient_cfg
58 ])
59
60
61def find_ninja_out_dir(args):
62 # Ninja uses getopt_long, which allows to intermix non-option arguments.
63 # To leave non supported parameters untouched, we do not use getopt.
64 for index, arg in enumerate(args[1:]):
65 if arg == '-C':
66 # + 1 to get the next argument and +1 because we trimmed off args[0]
67 return args[index + 2]
68 if arg.startswith('-C'):
69 # Support -Cout/Default
70 return arg[2:]
71 return '.'
72
73
Ben Segall7a0fe8b2023-04-24 20:36:55 +000074def find_cache_dir(tmp_dir):
75 """Helper to find the correct cache directory for a build.
76
77 tmp_dir should be a build specific temp directory within the out directory.
78
79 If this is called from within a gclient checkout, the cache dir will be:
80 <gclient_root>/.reproxy_cache/md5(tmp_dir)/
81 If this is not called from within a gclient checkout, the cache dir will be:
82 tmp_dir/cache
83 """
84 gclient_root = gclient_paths.FindGclientRoot(os.getcwd())
85 if gclient_root:
86 return os.path.join(gclient_root, '.reproxy_cache',
87 hashlib.md5(tmp_dir.encode()).hexdigest())
88 return os.path.join(tmp_dir, 'cache')
89
90
Junji Watanabe607284d2023-04-20 03:14:52 +000091def set_reproxy_path_flags(out_dir, make_dirs=True):
92 """Helper to setup the logs and cache directories for reclient.
93
94 Creates the following directory structure if make_dirs is true:
Ben Segall7a0fe8b2023-04-24 20:36:55 +000095 If in a gclient checkout
96 out_dir/
97 .reproxy_tmp/
98 logs/
99 <gclient_root>
100 .reproxy_cache/
101 md5(out_dir/.reproxy_tmp)/
102
103 If not in a gclient checkout
Junji Watanabe607284d2023-04-20 03:14:52 +0000104 out_dir/
105 .reproxy_tmp/
106 logs/
107 cache/
108
109 The following env vars are set if not already set:
110 RBE_output_dir=out_dir/.reproxy_tmp/logs
111 RBE_proxy_log_dir=out_dir/.reproxy_tmp/logs
112 RBE_log_dir=out_dir/.reproxy_tmp/logs
113 RBE_cache_dir=out_dir/.reproxy_tmp/cache
114 *Nix Only:
115 RBE_server_address=unix://out_dir/.reproxy_tmp/reproxy.sock
116 Windows Only:
117 RBE_server_address=pipe://md5(out_dir/.reproxy_tmp)/reproxy.pipe
118 """
119 tmp_dir = os.path.abspath(os.path.join(out_dir, '.reproxy_tmp'))
120 log_dir = os.path.join(tmp_dir, 'logs')
Ben Segall7a0fe8b2023-04-24 20:36:55 +0000121 cache_dir = find_cache_dir(tmp_dir)
Junji Watanabe607284d2023-04-20 03:14:52 +0000122 if make_dirs:
123 os.makedirs(tmp_dir, exist_ok=True)
124 os.makedirs(log_dir, exist_ok=True)
125 os.makedirs(cache_dir, exist_ok=True)
126 os.environ.setdefault("RBE_output_dir", log_dir)
127 os.environ.setdefault("RBE_proxy_log_dir", log_dir)
128 os.environ.setdefault("RBE_log_dir", log_dir)
129 os.environ.setdefault("RBE_cache_dir", cache_dir)
130 if sys.platform.startswith('win'):
131 pipe_dir = hashlib.md5(tmp_dir.encode()).hexdigest()
132 os.environ.setdefault("RBE_server_address",
133 "pipe://%s/reproxy.pipe" % pipe_dir)
134 else:
135 os.environ.setdefault("RBE_server_address",
136 "unix://%s/reproxy.sock" % tmp_dir)
137
138
139@contextlib.contextmanager
140def build_context(argv):
141 # If use_remoteexec is set, but the reclient binaries or configs don't
142 # exist, display an error message and stop. Otherwise, the build will
143 # attempt to run with rewrapper wrapping actions, but will fail with
144 # possible non-obvious problems.
145 reclient_bin_dir = find_reclient_bin_dir()
146 reclient_cfg = find_reclient_cfg()
147 if reclient_bin_dir is None or reclient_cfg is None:
148 print(("Build is configured to use reclient but necessary binaries "
149 "or config files can't be found. Developer builds with "
150 "reclient are not yet supported. Try regenerating your "
151 "build with use_goma in place of use_remoteexec for now."),
152 file=sys.stderr)
153 yield 1
154 return
155 try:
156 set_reproxy_path_flags(find_ninja_out_dir(argv))
157 except OSError:
158 print("Error creating reproxy_tmp in output dir", file=sys.stderr)
159 yield 1
160 return
161 reproxy_ret_code = start_reproxy(reclient_cfg, reclient_bin_dir)
162 if reproxy_ret_code != 0:
163 yield reproxy_ret_code
164 return
165 try:
166 yield
167 finally:
168 print("Shutting down reproxy...", file=sys.stderr)
169 stop_reproxy(reclient_cfg, reclient_bin_dir)