blob: 5691843d4552a46efc50de3cc0752fd3ea42ca2f [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.
Bruce Dawsonebebd952017-05-31 14:24:38 -07005"""
6This script (intended to be invoked by autoninja or autoninja.bat) detects
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +00007whether a build is accelerated using a service like goma. If so, it runs with a
8large -j value, and otherwise it chooses a small one. This auto-adjustment
9makes using remote build acceleration simpler and safer, and avoids errors that
10can cause slow goma builds or swap-storms on unaccelerated builds.
Bruce Dawson30c1cba2023-09-15 18:20:32 +000011
12autoninja tries to detect relevant build settings such as use_remoteexec, and it
13does handle import statements, but it can't handle conditional setting of build
14settings.
Bruce Dawsonebebd952017-05-31 14:24:38 -070015"""
16
Bruce Dawsone952fae2021-02-27 23:33:37 +000017import multiprocessing
Bruce Dawsonebebd952017-05-31 14:24:38 -070018import os
Takuto Ikuta6a1494e2022-05-06 01:22:16 +000019import platform
Bruce Dawsonebebd952017-05-31 14:24:38 -070020import re
Philipp Wollermann0b943402023-10-12 07:13:30 +000021import shlex
Bruce Dawsone952fae2021-02-27 23:33:37 +000022import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070023import sys
24
Philipp Wollermann0b943402023-10-12 07:13:30 +000025import autosiso
26import ninja
27import ninja_reclient
28import siso
29
Henrique Ferreiro8bde1642023-09-14 11:41:19 +000030if sys.platform in ['darwin', 'linux']:
Mike Frysinger124bb8e2023-09-06 05:48:55 +000031 import resource
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +000032
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000033SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
34
Philipp Wollermann0b943402023-10-12 07:13:30 +000035# See [1] and [2] for the painful details of this next section, which handles
36# escaping command lines so that they can be copied and pasted into a cmd
37# window.
38#
39# pylint: disable=line-too-long
40# [1] https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way # noqa
41# [2] https://web.archive.org/web/20150815000000*/https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/set.mspx # noqa
42_UNSAFE_FOR_CMD = set('^<>&|()%')
43_ALL_META_CHARS = _UNSAFE_FOR_CMD.union(set('"'))
44
45
46def _quote_for_cmd(arg):
47 # First, escape the arg so that CommandLineToArgvW will parse it properly.
48 if arg == '' or ' ' in arg or '"' in arg:
49 quote_re = re.compile(r'(\\*)"')
50 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
51
52 # Then check to see if the arg contains any metacharacters other than
53 # double quotes; if it does, quote everything (including the double
54 # quotes) for safety.
55 if any(a in _UNSAFE_FOR_CMD for a in arg):
56 arg = ''.join('^' + a if a in _ALL_META_CHARS else a for a in arg)
57 return arg
58
59
60def _print_cmd(cmd):
61 shell_quoter = shlex.quote
62 if sys.platform.startswith('win'):
63 shell_quoter = _quote_for_cmd
64 print(*[shell_quoter(arg) for arg in cmd], file=sys.stderr)
65
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000066
Bruce Dawson30c1cba2023-09-15 18:20:32 +000067def _gn_lines(output_dir, path):
68 """
69 Generator function that returns args.gn lines one at a time, following
70 import directives as needed.
71 """
72 import_re = re.compile(r'\s*import\("(.*)"\)')
73 with open(path, encoding='utf-8') as f:
74 for line in f:
75 match = import_re.match(line)
76 if match:
Samuel Attard8a259982023-09-18 17:12:55 +000077 raw_import_path = match.groups()[0]
78 if raw_import_path[:2] == "//":
79 import_path = os.path.normpath(
80 os.path.join(output_dir, '..', '..',
81 raw_import_path[2:]))
82 else:
83 import_path = os.path.normpath(
84 os.path.join(os.path.dirname(path), raw_import_path))
Bruce Dawson30c1cba2023-09-15 18:20:32 +000085 for import_line in _gn_lines(output_dir, import_path):
86 yield import_line
87 else:
88 yield line
89
90
Takuto Ikuta381db682022-04-27 23:54:02 +000091def main(args):
Mike Frysinger124bb8e2023-09-06 05:48:55 +000092 # The -t tools are incompatible with -j
93 t_specified = False
94 j_specified = False
95 offline = False
96 output_dir = '.'
97 input_args = args
Philipp Wollermann0b943402023-10-12 07:13:30 +000098 summarize_build = os.environ.get('NINJA_SUMMARIZE_BUILD') == '1'
Mike Frysinger124bb8e2023-09-06 05:48:55 +000099 # On Windows the autoninja.bat script passes along the arguments enclosed in
100 # double quotes. This prevents multiple levels of parsing of the special '^'
101 # characters needed when compiling a single file but means that this script
102 # gets called with a single argument containing all of the actual arguments,
103 # separated by spaces. When this case is detected we need to do argument
104 # splitting ourselves. This means that arguments containing actual spaces
105 # are not supported by autoninja, but that is not a real limitation.
106 if (sys.platform.startswith('win') and len(args) == 2
107 and input_args[1].count(' ') > 0):
108 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +0000109
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000110 # Ninja uses getopt_long, which allow to intermix non-option arguments.
111 # To leave non supported parameters untouched, we do not use getopt.
112 for index, arg in enumerate(input_args[1:]):
113 if arg.startswith('-j'):
114 j_specified = True
115 if arg.startswith('-t'):
116 t_specified = True
117 if arg == '-C':
118 # + 1 to get the next argument and +1 because we trimmed off
119 # input_args[0]
120 output_dir = input_args[index + 2]
121 elif arg.startswith('-C'):
122 # Support -Cout/Default
123 output_dir = arg[2:]
124 elif arg in ('-o', '--offline'):
125 offline = True
126 elif arg == '-h':
127 print('autoninja: Use -o/--offline to temporary disable goma.',
128 file=sys.stderr)
129 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +0000130
Takuto Ikuta381db682022-04-27 23:54:02 +0000131 use_goma = False
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000132 use_remoteexec = False
133 use_rbe = False
134 use_siso = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000135
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000136 # Attempt to auto-detect remote build acceleration. We support gn-based
137 # builds, where we look for args.gn in the build tree, and cmake-based
138 # builds where we look for rules.ninja.
139 if os.path.exists(os.path.join(output_dir, 'args.gn')):
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000140 for line in _gn_lines(output_dir, os.path.join(output_dir, 'args.gn')):
141 # use_goma, use_remoteexec, or use_rbe will activate build
142 # acceleration.
143 #
144 # This test can match multi-argument lines. Examples of this
145 # are: is_debug=false use_goma=true is_official_build=false
146 # use_goma=false# use_goma=true This comment is ignored
147 #
148 # Anything after a comment is not consider a valid argument.
149 line_without_comment = line.split('#')[0]
150 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
151 line_without_comment):
152 use_goma = True
153 continue
154 if re.search(r'(^|\s)(use_remoteexec)\s*=\s*true($|\s)',
155 line_without_comment):
156 use_remoteexec = True
157 continue
158 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)',
159 line_without_comment):
160 use_rbe = True
161 continue
162 if re.search(r'(^|\s)(use_siso)\s*=\s*true($|\s)',
163 line_without_comment):
164 use_siso = True
165 continue
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000166
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000167 siso_marker = os.path.join(output_dir, '.siso_deps')
168 if use_siso:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000169 # autosiso generates a .ninja_log file so the mere existence of a
170 # .ninja_log file doesn't imply that a ninja build was done. However
171 # if there is a .ninja_log but no .siso_deps then that implies a
172 # ninja build.
Junji Watanabec5182992023-10-13 04:52:02 +0000173 ninja_marker = os.path.join(output_dir, '.ninja_log')
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000174 if os.path.exists(ninja_marker) and not os.path.exists(siso_marker):
Philipp Wollermann0b943402023-10-12 07:13:30 +0000175 print('Run gn clean before switching from ninja to siso in %s' %
176 output_dir,
177 file=sys.stderr)
178 return 1
Fumitoshi Ukai406be822023-10-18 04:18:24 +0000179 if use_goma:
180 print('Siso does not support Goma.', file=sys.stderr)
181 print('Do not use use_siso=true and use_goma=true',
182 file=sys.stderr)
183 return 1
Philipp Wollermann0b943402023-10-12 07:13:30 +0000184 if use_remoteexec:
185 return autosiso.main(['autosiso'] + input_args[1:])
Philipp Wollermann17debef2023-11-02 02:03:46 +0000186 return siso.main(['siso', 'ninja', '--offline'] + input_args[1:])
Michael Savigny20eda952021-01-20 01:16:27 +0000187
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000188 if os.path.exists(siso_marker):
Philipp Wollermann0b943402023-10-12 07:13:30 +0000189 print('Run gn clean before switching from siso to ninja in %s' %
190 output_dir,
191 file=sys.stderr)
192 return 1
Ben Segall467991e2023-08-09 19:02:09 +0000193
Takuto Ikuta381db682022-04-27 23:54:02 +0000194 else:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000195 for relative_path in [
196 '', # GN keeps them in the root of output_dir
197 'CMakeFiles'
198 ]:
199 path = os.path.join(output_dir, relative_path, 'rules.ninja')
200 if os.path.exists(path):
Bruce Dawson30c1cba2023-09-15 18:20:32 +0000201 with open(path, encoding='utf-8') as file_handle:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000202 for line in file_handle:
203 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
204 use_goma = True
205 break
Takuto Ikuta381db682022-04-27 23:54:02 +0000206
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000207 # Strip -o/--offline so ninja doesn't see them.
208 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
Takuto Ikuta381db682022-04-27 23:54:02 +0000209
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000210 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
211 # (case-insensitive) then gomacc will use the local compiler instead of
212 # doing a goma compile. This is convenient if you want to briefly disable
213 # goma. It avoids having to rebuild the world when transitioning between
214 # goma/non-goma builds. However, it is not as fast as doing a "normal"
215 # non-goma build because an extra process is created for each compile step.
216 # Checking this environment variable ensures that autoninja uses an
217 # appropriate -j value in this situation.
218 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
219 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
220 use_goma = False
Takuto Ikuta381db682022-04-27 23:54:02 +0000221
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000222 if use_goma:
223 gomacc_file = 'gomacc.exe' if sys.platform.startswith(
224 'win') else 'gomacc'
225 goma_dir = os.environ.get('GOMA_DIR',
226 os.path.join(SCRIPT_DIR, '.cipd_bin'))
227 gomacc_path = os.path.join(goma_dir, gomacc_file)
228 # Don't invoke gomacc if it doesn't exist.
229 if os.path.exists(gomacc_path):
230 # Check to make sure that goma is running. If not, don't start the
231 # build.
232 status = subprocess.call([gomacc_path, 'port'],
233 stdout=subprocess.PIPE,
234 stderr=subprocess.PIPE,
235 shell=False)
236 if status == 1:
237 print(
238 'Goma is not running. Use "goma_ctl ensure_start" to start '
239 'it.',
240 file=sys.stderr)
241 if sys.platform.startswith('win'):
242 # Set an exit code of 1 in the batch file.
243 print('cmd "/c exit 1"')
244 else:
245 # Set an exit code of 1 by executing 'false' in the bash
246 # script.
247 print('false')
248 sys.exit(1)
249
250 # A large build (with or without goma) tends to hog all system resources.
Philipp Wollermann0b943402023-10-12 07:13:30 +0000251 # Depending on the operating system, we might have mechanisms available
252 # to run at a lower priority, which improves this situation.
253 if os.environ.get('NINJA_BUILD_IN_BACKGROUND') == '1':
254 if sys.platform in ['darwin', 'linux']:
255 # nice-level 10 is usually considered a good default for background
256 # tasks. The niceness is inherited by child processes, so we can
257 # just set it here for us and it'll apply to the build tool we
258 # spawn later.
259 os.nice(10)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000260
Philipp Wollermann0b943402023-10-12 07:13:30 +0000261 # Tell goma or reclient to do local compiles.
262 if offline:
263 os.environ['RBE_remote_disabled'] = '1'
264 os.environ['GOMA_DISABLED'] = '1'
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000265
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000266 # On macOS and most Linux distributions, the default limit of open file
267 # descriptors is too low (256 and 1024, respectively).
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000268 # This causes a large j value to result in 'Too many open files' errors.
269 # Check whether the limit can be raised to a large enough value. If yes,
270 # use `ulimit -n .... &&` as a prefix to increase the limit when running
271 # ninja.
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000272 if sys.platform in ['darwin', 'linux']:
273 # Increase the number of allowed open file descriptors to the maximum.
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000274 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000275 if fileno_limit < hard_limit:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000276 try:
277 resource.setrlimit(resource.RLIMIT_NOFILE,
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000278 (hard_limit, hard_limit))
Philipp Wollermann0b943402023-10-12 07:13:30 +0000279 except Exception:
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000280 pass
281 fileno_limit, hard_limit = resource.getrlimit(
282 resource.RLIMIT_NOFILE)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000283
284 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
285 # PATH.
286 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
287 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
288 # starting and stopping reproxy.
289 if use_remoteexec:
290 ninja_path = os.path.join(SCRIPT_DIR, 'ninja_reclient.py')
291
Philipp Wollermann0b943402023-10-12 07:13:30 +0000292 args = [sys.executable, ninja_path] + input_args[1:]
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000293
294 num_cores = multiprocessing.cpu_count()
295 if not j_specified and not t_specified:
296 if not offline and (use_goma or use_remoteexec or use_rbe):
297 args.append('-j')
298 default_core_multiplier = 80
299 if platform.machine() in ('x86_64', 'AMD64'):
300 # Assume simultaneous multithreading and therefore half as many
301 # cores as logical processors.
302 num_cores //= 2
303
304 core_multiplier = int(
305 os.environ.get('NINJA_CORE_MULTIPLIER',
306 default_core_multiplier))
307 j_value = num_cores * core_multiplier
308
309 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
310 j_value = min(j_value, core_limit)
311
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000312 # On Windows, a -j higher than 1000 doesn't improve build times.
Henrique Ferreiro7eb4e482023-09-20 20:25:20 +0000313 # On macOS, ninja is limited to at most FD_SETSIZE (1024) open file
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000314 # descriptors.
Henrique Ferreiro7eb4e482023-09-20 20:25:20 +0000315 if sys.platform in ['darwin', 'win32']:
316 j_value = min(j_value, 1000)
317
318 # Use a j value that reliably works with the open file descriptors
319 # limit.
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000320 if sys.platform in ['darwin', 'linux']:
Henrique Ferreiro8bde1642023-09-14 11:41:19 +0000321 j_value = min(j_value, int(fileno_limit * 0.8))
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000322
323 args.append('%d' % j_value)
324 else:
325 j_value = num_cores
326 # Ninja defaults to |num_cores + 2|
327 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
328 args.append('-j')
329 args.append('%d' % j_value)
330
Philipp Wollermann0b943402023-10-12 07:13:30 +0000331 if summarize_build:
332 # Enable statistics collection in Ninja.
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000333 args += ['-d', 'stats']
Philipp Wollermann0b943402023-10-12 07:13:30 +0000334 # Print the command-line to reassure the user that the right settings
335 # are being used.
336 _print_cmd(args)
Mike Frysinger124bb8e2023-09-06 05:48:55 +0000337
Philipp Wollermann0b943402023-10-12 07:13:30 +0000338 if use_remoteexec:
339 return ninja_reclient.main(args[1:])
340 return ninja.main(args[1:])
Takuto Ikuta381db682022-04-27 23:54:02 +0000341
342
343if __name__ == '__main__':
Philipp Wollermann0b943402023-10-12 07:13:30 +0000344 try:
345 sys.exit(main(sys.argv))
346 except KeyboardInterrupt:
347 sys.exit(1)