blob: 54f258d207fef01ffe94b14fe55469712e89d546 [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
74def set_reproxy_path_flags(out_dir, make_dirs=True):
75 """Helper to setup the logs and cache directories for reclient.
76
77 Creates the following directory structure if make_dirs is true:
78 out_dir/
79 .reproxy_tmp/
80 logs/
81 cache/
82
83 The following env vars are set if not already set:
84 RBE_output_dir=out_dir/.reproxy_tmp/logs
85 RBE_proxy_log_dir=out_dir/.reproxy_tmp/logs
86 RBE_log_dir=out_dir/.reproxy_tmp/logs
87 RBE_cache_dir=out_dir/.reproxy_tmp/cache
88 *Nix Only:
89 RBE_server_address=unix://out_dir/.reproxy_tmp/reproxy.sock
90 Windows Only:
91 RBE_server_address=pipe://md5(out_dir/.reproxy_tmp)/reproxy.pipe
92 """
93 tmp_dir = os.path.abspath(os.path.join(out_dir, '.reproxy_tmp'))
94 log_dir = os.path.join(tmp_dir, 'logs')
95 cache_dir = os.path.join(tmp_dir, 'cache')
96 if make_dirs:
97 os.makedirs(tmp_dir, exist_ok=True)
98 os.makedirs(log_dir, exist_ok=True)
99 os.makedirs(cache_dir, exist_ok=True)
100 os.environ.setdefault("RBE_output_dir", log_dir)
101 os.environ.setdefault("RBE_proxy_log_dir", log_dir)
102 os.environ.setdefault("RBE_log_dir", log_dir)
103 os.environ.setdefault("RBE_cache_dir", cache_dir)
104 if sys.platform.startswith('win'):
105 pipe_dir = hashlib.md5(tmp_dir.encode()).hexdigest()
106 os.environ.setdefault("RBE_server_address",
107 "pipe://%s/reproxy.pipe" % pipe_dir)
108 else:
109 os.environ.setdefault("RBE_server_address",
110 "unix://%s/reproxy.sock" % tmp_dir)
111
112
113@contextlib.contextmanager
114def build_context(argv):
115 # If use_remoteexec is set, but the reclient binaries or configs don't
116 # exist, display an error message and stop. Otherwise, the build will
117 # attempt to run with rewrapper wrapping actions, but will fail with
118 # possible non-obvious problems.
119 reclient_bin_dir = find_reclient_bin_dir()
120 reclient_cfg = find_reclient_cfg()
121 if reclient_bin_dir is None or reclient_cfg is None:
122 print(("Build is configured to use reclient but necessary binaries "
123 "or config files can't be found. Developer builds with "
124 "reclient are not yet supported. Try regenerating your "
125 "build with use_goma in place of use_remoteexec for now."),
126 file=sys.stderr)
127 yield 1
128 return
129 try:
130 set_reproxy_path_flags(find_ninja_out_dir(argv))
131 except OSError:
132 print("Error creating reproxy_tmp in output dir", file=sys.stderr)
133 yield 1
134 return
135 reproxy_ret_code = start_reproxy(reclient_cfg, reclient_bin_dir)
136 if reproxy_ret_code != 0:
137 yield reproxy_ret_code
138 return
139 try:
140 yield
141 finally:
142 print("Shutting down reproxy...", file=sys.stderr)
143 stop_reproxy(reclient_cfg, reclient_bin_dir)