blob: 6418fccafbd3a43fe20d1fc2c017d3dcf59f9d1e [file] [log] [blame]
Takuto Ikuta237cc462022-01-19 18:04:15 +00001#!/usr/bin/env python3
Bruce Dawsonebebd952017-05-31 14:24:38 -07002# Copyright (c) 2017 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""
7This script (intended to be invoked by autoninja or autoninja.bat) detects
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +00008whether a build is accelerated using a service like goma. If so, it runs with a
9large -j value, and otherwise it chooses a small one. This auto-adjustment
10makes using remote build acceleration simpler and safer, and avoids errors that
11can cause slow goma builds or swap-storms on unaccelerated builds.
Bruce Dawsonebebd952017-05-31 14:24:38 -070012"""
13
Raul Tambre80ee78e2019-05-06 22:41:05 +000014from __future__ import print_function
15
Bruce Dawsone952fae2021-02-27 23:33:37 +000016import multiprocessing
Bruce Dawsonebebd952017-05-31 14:24:38 -070017import os
Takuto Ikuta6a1494e2022-05-06 01:22:16 +000018import platform
Bruce Dawsonebebd952017-05-31 14:24:38 -070019import re
Bruce Dawsone952fae2021-02-27 23:33:37 +000020import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070021import sys
22
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000023SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
24
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000025
Takuto Ikuta381db682022-04-27 23:54:02 +000026def main(args):
27 # The -t tools are incompatible with -j
28 t_specified = False
29 j_specified = False
30 offline = False
31 output_dir = '.'
32 input_args = args
33 # On Windows the autoninja.bat script passes along the arguments enclosed in
34 # double quotes. This prevents multiple levels of parsing of the special '^'
35 # characters needed when compiling a single file but means that this script
36 # gets called with a single argument containing all of the actual arguments,
37 # separated by spaces. When this case is detected we need to do argument
38 # splitting ourselves. This means that arguments containing actual spaces are
39 # not supported by autoninja, but that is not a real limitation.
40 if (sys.platform.startswith('win') and len(args) == 2
41 and input_args[1].count(' ') > 0):
42 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +000043
Takuto Ikuta381db682022-04-27 23:54:02 +000044 # Ninja uses getopt_long, which allow to intermix non-option arguments.
45 # To leave non supported parameters untouched, we do not use getopt.
46 for index, arg in enumerate(input_args[1:]):
47 if arg.startswith('-j'):
48 j_specified = True
49 if arg.startswith('-t'):
50 t_specified = True
51 if arg == '-C':
52 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
53 output_dir = input_args[index + 2]
54 elif arg.startswith('-C'):
55 # Support -Cout/Default
56 output_dir = arg[2:]
57 elif arg in ('-o', '--offline'):
58 offline = True
59 elif arg == '-h':
60 print('autoninja: Use -o/--offline to temporary disable goma.',
Bruce Dawsone952fae2021-02-27 23:33:37 +000061 file=sys.stderr)
Takuto Ikuta381db682022-04-27 23:54:02 +000062 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +000063
Takuto Ikuta381db682022-04-27 23:54:02 +000064 # Strip -o/--offline so ninja doesn't see them.
65 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
Allen Bauer75fa8552018-11-07 22:43:39 +000066
Takuto Ikuta381db682022-04-27 23:54:02 +000067 use_goma = False
68 use_remoteexec = False
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000069 use_rbe = False
Peter McNeeley958dc622020-10-18 17:05:04 +000070
Takuto Ikuta381db682022-04-27 23:54:02 +000071 # Currently get reclient binary and config dirs relative to output_dir. If
72 # they exist and using remoteexec, then automatically call bootstrap to start
73 # reproxy. This works under the current assumption that the output
74 # directory is two levels up from chromium/src.
75 reclient_bin_dir = os.path.join(output_dir, '..', '..', 'buildtools',
76 'reclient')
77 reclient_cfg = os.path.join(output_dir, '..', '..', 'buildtools',
78 'reclient_cfgs', 'reproxy.cfg')
Peter McNeeley958dc622020-10-18 17:05:04 +000079
Takuto Ikuta381db682022-04-27 23:54:02 +000080 # Attempt to auto-detect remote build acceleration. We support gn-based
81 # builds, where we look for args.gn in the build tree, and cmake-based builds
82 # where we look for rules.ninja.
83 if os.path.exists(os.path.join(output_dir, 'args.gn')):
84 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
85 for line in file_handle:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000086 # use_goma, use_remoteexec, or use_rbe will activate build acceleration.
Takuto Ikuta381db682022-04-27 23:54:02 +000087 #
88 # This test can match multi-argument lines. Examples of this are:
89 # is_debug=false use_goma=true is_official_build=false
90 # use_goma=false# use_goma=true This comment is ignored
91 #
92 # Anything after a comment is not consider a valid argument.
93 line_without_comment = line.split('#')[0]
94 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
95 line_without_comment):
96 use_goma = True
97 continue
Richard Wangbb07d9e2022-07-07 02:28:59 +000098 if re.search(r'(^|\s)(use_remoteexec)\s*=\s*true($|\s)',
Takuto Ikuta381db682022-04-27 23:54:02 +000099 line_without_comment):
100 use_remoteexec = True
101 continue
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000102 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)', line_without_comment):
103 use_rbe = True
104 continue
105
Bruce Dawsonebebd952017-05-31 14:24:38 -0700106 else:
Takuto Ikuta381db682022-04-27 23:54:02 +0000107 for relative_path in [
108 '', # GN keeps them in the root of output_dir
109 'CMakeFiles'
110 ]:
111 path = os.path.join(output_dir, relative_path, 'rules.ninja')
112 if os.path.exists(path):
113 with open(path) as file_handle:
114 for line in file_handle:
115 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
116 use_goma = True
117 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700118
Michael Savigny1cf1fb52022-08-18 19:57:21 +0000119 # If use_remoteexec is set, but the reclient binaries or configs don't
120 # exist, display an error message and stop. Otherwise, the build will
121 # attempt to run with rewrapper wrapping actions, but will fail with
122 # possible non-obvious problems.
123 # As of August 2022, dev builds with reclient are not supported, so
124 # indicate that use_goma should be swapped for use_remoteexec. This
125 # message will be changed when dev builds are fully supported.
126 if (not offline and use_remoteexec and (
127 not os.path.exists(reclient_bin_dir) or not os.path.exists(reclient_cfg))
128 ):
Junji Watanabead452a72022-11-30 02:39:48 +0000129 print(("Build is configured to use reclient but necessary binaries "
130 "or config files can't be found. Developer builds with "
131 "reclient are not yet supported. Try regenerating your "
132 "build with use_goma in place of use_remoteexec for now."),
133 file=sys.stderr)
134 if sys.platform.startswith('win'):
135 # Set an exit code of 1 in the batch file.
136 print('cmd "/c exit 1"')
137 else:
138 # Set an exit code of 1 by executing 'false' in the bash script.
139 print('false')
140 sys.exit(1)
Michael Savigny1cf1fb52022-08-18 19:57:21 +0000141
Takuto Ikuta381db682022-04-27 23:54:02 +0000142 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
143 # (case-insensitive) then gomacc will use the local compiler instead of doing
144 # a goma compile. This is convenient if you want to briefly disable goma. It
145 # avoids having to rebuild the world when transitioning between goma/non-goma
146 # builds. However, it is not as fast as doing a "normal" non-goma build
147 # because an extra process is created for each compile step. Checking this
148 # environment variable ensures that autoninja uses an appropriate -j value in
149 # this situation.
150 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
151 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
152 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000153
Takuto Ikuta381db682022-04-27 23:54:02 +0000154 if use_goma:
155 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
156 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
157 gomacc_path = os.path.join(goma_dir, gomacc_file)
158 # Don't invoke gomacc if it doesn't exist.
159 if os.path.exists(gomacc_path):
160 # Check to make sure that goma is running. If not, don't start the build.
161 status = subprocess.call([gomacc_path, 'port'],
162 stdout=subprocess.PIPE,
163 stderr=subprocess.PIPE,
164 shell=False)
165 if status == 1:
Michael Spangf4670892022-10-26 17:35:08 +0000166 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
167 file=sys.stderr)
168 if sys.platform.startswith('win'):
169 # Set an exit code of 1 in the batch file.
170 print('cmd "/c exit 1"')
171 else:
172 # Set an exit code of 1 by executing 'false' in the bash script.
173 print('false')
174 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000175
Takuto Ikuta381db682022-04-27 23:54:02 +0000176 # A large build (with or without goma) tends to hog all system resources.
177 # Launching the ninja process with 'nice' priorities improves this situation.
178 prefix_args = []
179 if (sys.platform.startswith('linux')
180 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
181 # nice -10 is process priority 10 lower than default 0
182 # ionice -c 3 is IO priority IDLE
183 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000184
Junji Watanabead452a72022-11-30 02:39:48 +0000185 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
186 # PATH.
187 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
188 args = prefix_args + [sys.executable, ninja_path] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000189
Takuto Ikuta381db682022-04-27 23:54:02 +0000190 num_cores = multiprocessing.cpu_count()
191 if not j_specified and not t_specified:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000192 if use_goma or use_remoteexec or use_rbe:
Takuto Ikuta381db682022-04-27 23:54:02 +0000193 args.append('-j')
Takuto Ikuta6a1494e2022-05-06 01:22:16 +0000194 default_core_multiplier = 80
195 if platform.machine() in ('x86_64', 'AMD64'):
196 # Assume simultaneous multithreading and therefore half as many cores as
197 # logical processors.
198 num_cores //= 2
199
200 core_multiplier = int(
201 os.environ.get('NINJA_CORE_MULTIPLIER', default_core_multiplier))
Takuto Ikuta381db682022-04-27 23:54:02 +0000202 j_value = num_cores * core_multiplier
203
Aleksey Khoroshilov1bc3cd22022-05-09 19:49:42 +0000204 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
205 j_value = min(j_value, core_limit)
206
Takuto Ikuta381db682022-04-27 23:54:02 +0000207 if sys.platform.startswith('win'):
208 # On windows, j value higher than 1000 does not improve build
209 # performance.
210 j_value = min(j_value, 1000)
Sylvain Defresnecb2cef92022-05-10 08:57:20 +0000211 elif sys.platform == 'darwin':
212 # On macOS, j value higher than 800 causes 'Too many open files' error
213 # (crbug.com/936864).
214 j_value = min(j_value, 800)
Takuto Ikuta381db682022-04-27 23:54:02 +0000215
216 args.append('%d' % j_value)
217 else:
218 j_value = num_cores
219 # Ninja defaults to |num_cores + 2|
220 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
221 args.append('-j')
222 args.append('%d' % j_value)
223
224 # On Windows, fully quote the path so that the command processor doesn't think
225 # the whole output is the command.
226 # On Linux and Mac, if people put depot_tools in directories with ' ',
227 # shell would misunderstand ' ' as a path separation.
228 # TODO(yyanagisawa): provide proper quoting for Windows.
229 # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
230 for i in range(len(args)):
231 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
232 args[i] = '"%s"' % args[i].replace('"', '\\"')
233
234 if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
235 args += ['-d', 'stats']
236
237 # If using remoteexec and the necessary environment variables are set,
238 # also start reproxy (via bootstrap) before running ninja.
239 if (not offline and use_remoteexec and os.path.exists(reclient_bin_dir)
240 and os.path.exists(reclient_cfg)):
241 bootstrap = os.path.join(reclient_bin_dir, 'bootstrap')
242 setup_args = [
243 bootstrap, '--cfg=' + reclient_cfg,
244 '--re_proxy=' + os.path.join(reclient_bin_dir, 'reproxy')
245 ]
246
247 teardown_args = [bootstrap, '--cfg=' + reclient_cfg, '--shutdown']
248
249 cmd_sep = '\n' if sys.platform.startswith('win') else '&&'
Ben Segall7954ed72023-01-19 22:35:56 +0000250 cmd_always_sep = '\n' if sys.platform.startswith('win') else '; '
251 args = setup_args + [cmd_sep] + args + [cmd_always_sep] + teardown_args
Takuto Ikuta381db682022-04-27 23:54:02 +0000252
253 if offline and not sys.platform.startswith('win'):
254 # Tell goma or reclient to do local compiles. On Windows these environment
255 # variables are set by the wrapper batch file.
256 return 'RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)
257
258 return ' '.join(args)
259
260
261if __name__ == '__main__':
262 print(main(sys.argv))