blob: ece9126b412c3589307c637c9f27cbc5f5b20eb9 [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
100 if use_siso:
101 ninja_marker = os.path.join(output_dir, '.ninja_deps')
102 if os.path.exists(ninja_marker):
103 return ('echo Run gn clean before switching from ninja to siso in %s' %
104 output_dir)
105 siso = ['autosiso'] if use_remoteexec else ['siso', 'ninja']
106 if sys.platform.startswith('win'):
107 # An explicit 'call' is needed to make sure the invocation of autosiso
108 # returns to autoninja.bat, and the command prompt title gets reset.
109 siso = ['call'] + siso
110 return ' '.join(siso + input_args[1:])
111
112 siso_marker = os.path.join(output_dir, '.siso_deps')
113 if os.path.exists(siso_marker):
114 return ('echo Run gn clean before switching from siso to ninja in %s' %
115 output_dir)
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000116
Bruce Dawsonebebd952017-05-31 14:24:38 -0700117 else:
Takuto Ikuta381db682022-04-27 23:54:02 +0000118 for relative_path in [
119 '', # GN keeps them in the root of output_dir
120 'CMakeFiles'
121 ]:
122 path = os.path.join(output_dir, relative_path, 'rules.ninja')
123 if os.path.exists(path):
124 with open(path) as file_handle:
125 for line in file_handle:
126 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
127 use_goma = True
128 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700129
Bruce Dawson5a4c3502023-08-08 18:14:52 +0000130 # Strip -o/--offline so ninja doesn't see them.
131 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
132
Takuto Ikuta381db682022-04-27 23:54:02 +0000133 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
134 # (case-insensitive) then gomacc will use the local compiler instead of doing
135 # a goma compile. This is convenient if you want to briefly disable goma. It
136 # avoids having to rebuild the world when transitioning between goma/non-goma
137 # builds. However, it is not as fast as doing a "normal" non-goma build
138 # because an extra process is created for each compile step. Checking this
139 # environment variable ensures that autoninja uses an appropriate -j value in
140 # this situation.
141 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
142 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
143 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000144
Takuto Ikuta381db682022-04-27 23:54:02 +0000145 if use_goma:
146 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
147 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
148 gomacc_path = os.path.join(goma_dir, gomacc_file)
149 # Don't invoke gomacc if it doesn't exist.
150 if os.path.exists(gomacc_path):
151 # Check to make sure that goma is running. If not, don't start the build.
152 status = subprocess.call([gomacc_path, 'port'],
153 stdout=subprocess.PIPE,
154 stderr=subprocess.PIPE,
155 shell=False)
156 if status == 1:
Michael Spangf4670892022-10-26 17:35:08 +0000157 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
158 file=sys.stderr)
159 if sys.platform.startswith('win'):
160 # Set an exit code of 1 in the batch file.
161 print('cmd "/c exit 1"')
162 else:
163 # Set an exit code of 1 by executing 'false' in the bash script.
164 print('false')
165 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000166
Takuto Ikuta381db682022-04-27 23:54:02 +0000167 # A large build (with or without goma) tends to hog all system resources.
168 # Launching the ninja process with 'nice' priorities improves this situation.
169 prefix_args = []
170 if (sys.platform.startswith('linux')
171 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
172 # nice -10 is process priority 10 lower than default 0
173 # ionice -c 3 is IO priority IDLE
174 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000175
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000176 # On macOS, the default limit of open file descriptors is too low (256).
177 # This causes a large j value to result in 'Too many open files' errors.
178 # Check whether the limit can be raised to a large enough value. If yes,
179 # use `ulimit -n .... &&` as a prefix to increase the limit when running
180 # ninja.
181 if sys.platform == 'darwin':
182 wanted_limit = 200000 # Large enough to avoid any risk of exhaustion.
183 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
184 if fileno_limit <= wanted_limit:
185 try:
186 resource.setrlimit(resource.RLIMIT_NOFILE, (wanted_limit, hard_limit))
187 except Exception as _:
188 pass
189 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
190 if fileno_limit >= wanted_limit:
191 prefix_args = ['ulimit', '-n', f'{wanted_limit}', '&&']
192
193
Junji Watanabead452a72022-11-30 02:39:48 +0000194 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
195 # PATH.
196 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
Ben Segalleb2866e2023-01-20 20:14:44 +0000197 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
198 # starting and stopping reproxy.
199 if not offline and use_remoteexec:
200 ninja_path = os.path.join(SCRIPT_DIR, 'ninja_reclient.py')
Junji Watanabead452a72022-11-30 02:39:48 +0000201 args = prefix_args + [sys.executable, ninja_path] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000202
Takuto Ikuta381db682022-04-27 23:54:02 +0000203 num_cores = multiprocessing.cpu_count()
204 if not j_specified and not t_specified:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000205 if use_goma or use_remoteexec or use_rbe:
Takuto Ikuta381db682022-04-27 23:54:02 +0000206 args.append('-j')
Takuto Ikuta6a1494e2022-05-06 01:22:16 +0000207 default_core_multiplier = 80
208 if platform.machine() in ('x86_64', 'AMD64'):
209 # Assume simultaneous multithreading and therefore half as many cores as
210 # logical processors.
211 num_cores //= 2
212
213 core_multiplier = int(
214 os.environ.get('NINJA_CORE_MULTIPLIER', default_core_multiplier))
Takuto Ikuta381db682022-04-27 23:54:02 +0000215 j_value = num_cores * core_multiplier
216
Aleksey Khoroshilov1bc3cd22022-05-09 19:49:42 +0000217 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
218 j_value = min(j_value, core_limit)
219
Takuto Ikuta381db682022-04-27 23:54:02 +0000220 if sys.platform.startswith('win'):
221 # On windows, j value higher than 1000 does not improve build
222 # performance.
223 j_value = min(j_value, 1000)
Sylvain Defresnecb2cef92022-05-10 08:57:20 +0000224 elif sys.platform == 'darwin':
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000225 # If the number of open file descriptors is large enough (or it can be
226 # raised to a large enough value), then set j value to 1000. This limit
227 # comes from ninja which is limited to at most FD_SETSIZE (1024) open
228 # file descriptors (using 1000 leave a bit of head room).
229 #
230 # If the number of open file descriptors cannot be raised, then use a
231 # j value of 200 which is the maximum value that reliably work with
232 # the default limit of 256.
233 if fileno_limit >= wanted_limit:
234 j_value = min(j_value, 1000)
Sylvain Defresne4d992432023-07-26 23:09:06 +0000235 else:
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000236 j_value = min(j_value, 200)
Takuto Ikuta381db682022-04-27 23:54:02 +0000237
238 args.append('%d' % j_value)
239 else:
240 j_value = num_cores
241 # Ninja defaults to |num_cores + 2|
242 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
243 args.append('-j')
244 args.append('%d' % j_value)
245
246 # On Windows, fully quote the path so that the command processor doesn't think
247 # the whole output is the command.
248 # On Linux and Mac, if people put depot_tools in directories with ' ',
249 # shell would misunderstand ' ' as a path separation.
250 # TODO(yyanagisawa): provide proper quoting for Windows.
251 # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
252 for i in range(len(args)):
253 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
254 args[i] = '"%s"' % args[i].replace('"', '\\"')
255
256 if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
257 args += ['-d', 'stats']
258
Takuto Ikuta381db682022-04-27 23:54:02 +0000259 if offline and not sys.platform.startswith('win'):
260 # Tell goma or reclient to do local compiles. On Windows these environment
261 # variables are set by the wrapper batch file.
262 return 'RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)
263
264 return ' '.join(args)
265
266
267if __name__ == '__main__':
268 print(main(sys.argv))