blob: d4f8c0c0f268a2f16bccb9c8390cc81ae25fdb5f [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
Bruce Dawsone952fae2021-02-27 23:33:37 +000014import multiprocessing
Bruce Dawsonebebd952017-05-31 14:24:38 -070015import os
Takuto Ikuta6a1494e2022-05-06 01:22:16 +000016import platform
Bruce Dawsonebebd952017-05-31 14:24:38 -070017import re
Bruce Dawsone952fae2021-02-27 23:33:37 +000018import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070019import sys
20
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +000021if sys.platform == 'darwin':
22 import resource
23
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000024SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
25
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000026
Takuto Ikuta381db682022-04-27 23:54:02 +000027def main(args):
28 # The -t tools are incompatible with -j
29 t_specified = False
30 j_specified = False
31 offline = False
32 output_dir = '.'
33 input_args = args
34 # On Windows the autoninja.bat script passes along the arguments enclosed in
35 # double quotes. This prevents multiple levels of parsing of the special '^'
36 # characters needed when compiling a single file but means that this script
37 # gets called with a single argument containing all of the actual arguments,
38 # separated by spaces. When this case is detected we need to do argument
39 # splitting ourselves. This means that arguments containing actual spaces are
40 # not supported by autoninja, but that is not a real limitation.
41 if (sys.platform.startswith('win') and len(args) == 2
42 and input_args[1].count(' ') > 0):
43 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +000044
Takuto Ikuta381db682022-04-27 23:54:02 +000045 # Ninja uses getopt_long, which allow to intermix non-option arguments.
46 # To leave non supported parameters untouched, we do not use getopt.
47 for index, arg in enumerate(input_args[1:]):
48 if arg.startswith('-j'):
49 j_specified = True
50 if arg.startswith('-t'):
51 t_specified = True
52 if arg == '-C':
53 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
54 output_dir = input_args[index + 2]
55 elif arg.startswith('-C'):
56 # Support -Cout/Default
57 output_dir = arg[2:]
58 elif arg in ('-o', '--offline'):
59 offline = True
60 elif arg == '-h':
61 print('autoninja: Use -o/--offline to temporary disable goma.',
Bruce Dawsone952fae2021-02-27 23:33:37 +000062 file=sys.stderr)
Takuto Ikuta381db682022-04-27 23:54:02 +000063 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +000064
Takuto Ikuta381db682022-04-27 23:54:02 +000065 use_goma = False
66 use_remoteexec = False
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000067 use_rbe = False
Bruce Dawson5a4c3502023-08-08 18:14:52 +000068 use_siso = False
Peter McNeeley958dc622020-10-18 17:05:04 +000069
Takuto Ikuta381db682022-04-27 23:54:02 +000070 # Attempt to auto-detect remote build acceleration. We support gn-based
71 # builds, where we look for args.gn in the build tree, and cmake-based builds
72 # where we look for rules.ninja.
73 if os.path.exists(os.path.join(output_dir, 'args.gn')):
74 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
75 for line in file_handle:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000076 # use_goma, use_remoteexec, or use_rbe will activate build acceleration.
Takuto Ikuta381db682022-04-27 23:54:02 +000077 #
78 # This test can match multi-argument lines. Examples of this are:
79 # is_debug=false use_goma=true is_official_build=false
80 # use_goma=false# use_goma=true This comment is ignored
81 #
82 # Anything after a comment is not consider a valid argument.
83 line_without_comment = line.split('#')[0]
84 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
85 line_without_comment):
86 use_goma = True
87 continue
Richard Wangbb07d9e2022-07-07 02:28:59 +000088 if re.search(r'(^|\s)(use_remoteexec)\s*=\s*true($|\s)',
Takuto Ikuta381db682022-04-27 23:54:02 +000089 line_without_comment):
90 use_remoteexec = True
91 continue
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000092 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)', line_without_comment):
93 use_rbe = True
94 continue
Bruce Dawson5a4c3502023-08-08 18:14:52 +000095 if re.search(r'(^|\s)(use_siso)\s*=\s*true($|\s)',
96 line_without_comment):
97 use_siso = True
98 continue
99
Bruce Dawson9c4fbc52023-08-22 15:16:55 +0000100 siso_marker = os.path.join(output_dir, '.siso_deps')
Bruce Dawson5a4c3502023-08-08 18:14:52 +0000101 if use_siso:
Bruce Dawson9c4fbc52023-08-22 15:16:55 +0000102 ninja_marker = os.path.join(output_dir, '.ninja_log')
103 # autosiso generates a .ninja_log file so the mere existence of a
104 # .ninja_log file doesn't imply that a ninja build was done. However if
105 # there is a .ninja_log but no .siso_deps then that implies a ninja build.
106 if os.path.exists(ninja_marker) and not os.path.exists(siso_marker):
Bruce Dawson5a4c3502023-08-08 18:14:52 +0000107 return ('echo Run gn clean before switching from ninja to siso in %s' %
108 output_dir)
109 siso = ['autosiso'] if use_remoteexec else ['siso', 'ninja']
110 if sys.platform.startswith('win'):
111 # An explicit 'call' is needed to make sure the invocation of autosiso
112 # returns to autoninja.bat, and the command prompt title gets reset.
113 siso = ['call'] + siso
114 return ' '.join(siso + input_args[1:])
115
Bruce Dawson5a4c3502023-08-08 18:14:52 +0000116 if os.path.exists(siso_marker):
117 return ('echo Run gn clean before switching from siso to ninja in %s' %
118 output_dir)
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000119
Bruce Dawsonebebd952017-05-31 14:24:38 -0700120 else:
Takuto Ikuta381db682022-04-27 23:54:02 +0000121 for relative_path in [
122 '', # GN keeps them in the root of output_dir
123 'CMakeFiles'
124 ]:
125 path = os.path.join(output_dir, relative_path, 'rules.ninja')
126 if os.path.exists(path):
127 with open(path) as file_handle:
128 for line in file_handle:
129 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
130 use_goma = True
131 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700132
Bruce Dawson5a4c3502023-08-08 18:14:52 +0000133 # Strip -o/--offline so ninja doesn't see them.
134 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
135
Takuto Ikuta381db682022-04-27 23:54:02 +0000136 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
137 # (case-insensitive) then gomacc will use the local compiler instead of doing
138 # a goma compile. This is convenient if you want to briefly disable goma. It
139 # avoids having to rebuild the world when transitioning between goma/non-goma
140 # builds. However, it is not as fast as doing a "normal" non-goma build
141 # because an extra process is created for each compile step. Checking this
142 # environment variable ensures that autoninja uses an appropriate -j value in
143 # this situation.
144 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
145 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
146 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000147
Takuto Ikuta381db682022-04-27 23:54:02 +0000148 if use_goma:
149 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
150 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
151 gomacc_path = os.path.join(goma_dir, gomacc_file)
152 # Don't invoke gomacc if it doesn't exist.
153 if os.path.exists(gomacc_path):
154 # Check to make sure that goma is running. If not, don't start the build.
155 status = subprocess.call([gomacc_path, 'port'],
156 stdout=subprocess.PIPE,
157 stderr=subprocess.PIPE,
158 shell=False)
159 if status == 1:
Michael Spangf4670892022-10-26 17:35:08 +0000160 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
161 file=sys.stderr)
162 if sys.platform.startswith('win'):
163 # Set an exit code of 1 in the batch file.
164 print('cmd "/c exit 1"')
165 else:
166 # Set an exit code of 1 by executing 'false' in the bash script.
167 print('false')
168 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000169
Takuto Ikuta381db682022-04-27 23:54:02 +0000170 # A large build (with or without goma) tends to hog all system resources.
171 # Launching the ninja process with 'nice' priorities improves this situation.
172 prefix_args = []
173 if (sys.platform.startswith('linux')
174 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
175 # nice -10 is process priority 10 lower than default 0
176 # ionice -c 3 is IO priority IDLE
177 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000178
Ben Segall467991e2023-08-09 19:02:09 +0000179 # Tell goma or reclient to do local compiles. On Windows these environment
180 # variables are set by the wrapper batch file.
181 offline_env = ['RBE_remote_disabled=1', 'GOMA_DISABLED=1'
182 ] if offline and not sys.platform.startswith('win') else []
183
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000184 # On macOS, the default limit of open file descriptors is too low (256).
185 # This causes a large j value to result in 'Too many open files' errors.
186 # Check whether the limit can be raised to a large enough value. If yes,
187 # use `ulimit -n .... &&` as a prefix to increase the limit when running
188 # ninja.
189 if sys.platform == 'darwin':
190 wanted_limit = 200000 # Large enough to avoid any risk of exhaustion.
191 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
192 if fileno_limit <= wanted_limit:
193 try:
194 resource.setrlimit(resource.RLIMIT_NOFILE, (wanted_limit, hard_limit))
195 except Exception as _:
196 pass
197 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
198 if fileno_limit >= wanted_limit:
Ben Segall467991e2023-08-09 19:02:09 +0000199 prefix_args = ['ulimit', '-n', f'{wanted_limit}', '&&'] + offline_env
200 offline_env = []
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000201
202
Junji Watanabead452a72022-11-30 02:39:48 +0000203 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
204 # PATH.
205 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
Ben Segalleb2866e2023-01-20 20:14:44 +0000206 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
207 # starting and stopping reproxy.
Ben Segall467991e2023-08-09 19:02:09 +0000208 if use_remoteexec:
Ben Segalleb2866e2023-01-20 20:14:44 +0000209 ninja_path = os.path.join(SCRIPT_DIR, 'ninja_reclient.py')
Ben Segall467991e2023-08-09 19:02:09 +0000210
211 args = offline_env + prefix_args + [sys.executable, ninja_path
212 ] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000213
Takuto Ikuta381db682022-04-27 23:54:02 +0000214 num_cores = multiprocessing.cpu_count()
215 if not j_specified and not t_specified:
Ben Segall467991e2023-08-09 19:02:09 +0000216 if not offline and (use_goma or use_remoteexec or use_rbe):
Takuto Ikuta381db682022-04-27 23:54:02 +0000217 args.append('-j')
Takuto Ikuta6a1494e2022-05-06 01:22:16 +0000218 default_core_multiplier = 80
219 if platform.machine() in ('x86_64', 'AMD64'):
220 # Assume simultaneous multithreading and therefore half as many cores as
221 # logical processors.
222 num_cores //= 2
223
224 core_multiplier = int(
225 os.environ.get('NINJA_CORE_MULTIPLIER', default_core_multiplier))
Takuto Ikuta381db682022-04-27 23:54:02 +0000226 j_value = num_cores * core_multiplier
227
Aleksey Khoroshilov1bc3cd22022-05-09 19:49:42 +0000228 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
229 j_value = min(j_value, core_limit)
230
Takuto Ikuta381db682022-04-27 23:54:02 +0000231 if sys.platform.startswith('win'):
232 # On windows, j value higher than 1000 does not improve build
233 # performance.
234 j_value = min(j_value, 1000)
Sylvain Defresnecb2cef92022-05-10 08:57:20 +0000235 elif sys.platform == 'darwin':
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000236 # If the number of open file descriptors is large enough (or it can be
237 # raised to a large enough value), then set j value to 1000. This limit
238 # comes from ninja which is limited to at most FD_SETSIZE (1024) open
239 # file descriptors (using 1000 leave a bit of head room).
240 #
241 # If the number of open file descriptors cannot be raised, then use a
242 # j value of 200 which is the maximum value that reliably work with
243 # the default limit of 256.
244 if fileno_limit >= wanted_limit:
245 j_value = min(j_value, 1000)
Sylvain Defresne4d992432023-07-26 23:09:06 +0000246 else:
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000247 j_value = min(j_value, 200)
Takuto Ikuta381db682022-04-27 23:54:02 +0000248
249 args.append('%d' % j_value)
250 else:
251 j_value = num_cores
252 # Ninja defaults to |num_cores + 2|
253 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
254 args.append('-j')
255 args.append('%d' % j_value)
256
257 # On Windows, fully quote the path so that the command processor doesn't think
258 # the whole output is the command.
259 # On Linux and Mac, if people put depot_tools in directories with ' ',
260 # shell would misunderstand ' ' as a path separation.
261 # TODO(yyanagisawa): provide proper quoting for Windows.
262 # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
263 for i in range(len(args)):
264 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
265 args[i] = '"%s"' % args[i].replace('"', '\\"')
266
267 if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
268 args += ['-d', 'stats']
269
Takuto Ikuta381db682022-04-27 23:54:02 +0000270 return ' '.join(args)
271
272
273if __name__ == '__main__':
274 print(main(sys.argv))