blob: 1dbd38ec6c634a86a5440fe0a844f41a07dc7229 [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 # Strip -o/--offline so ninja doesn't see them.
66 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
Allen Bauer75fa8552018-11-07 22:43:39 +000067
Takuto Ikuta381db682022-04-27 23:54:02 +000068 use_goma = False
69 use_remoteexec = False
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000070 use_rbe = False
Peter McNeeley958dc622020-10-18 17:05:04 +000071
Takuto Ikuta381db682022-04-27 23:54:02 +000072 # Attempt to auto-detect remote build acceleration. We support gn-based
73 # builds, where we look for args.gn in the build tree, and cmake-based builds
74 # where we look for rules.ninja.
75 if os.path.exists(os.path.join(output_dir, 'args.gn')):
76 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
77 for line in file_handle:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000078 # use_goma, use_remoteexec, or use_rbe will activate build acceleration.
Takuto Ikuta381db682022-04-27 23:54:02 +000079 #
80 # This test can match multi-argument lines. Examples of this are:
81 # is_debug=false use_goma=true is_official_build=false
82 # use_goma=false# use_goma=true This comment is ignored
83 #
84 # Anything after a comment is not consider a valid argument.
85 line_without_comment = line.split('#')[0]
86 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
87 line_without_comment):
88 use_goma = True
89 continue
Richard Wangbb07d9e2022-07-07 02:28:59 +000090 if re.search(r'(^|\s)(use_remoteexec)\s*=\s*true($|\s)',
Takuto Ikuta381db682022-04-27 23:54:02 +000091 line_without_comment):
92 use_remoteexec = True
93 continue
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000094 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)', line_without_comment):
95 use_rbe = True
96 continue
97
Bruce Dawsonebebd952017-05-31 14:24:38 -070098 else:
Takuto Ikuta381db682022-04-27 23:54:02 +000099 for relative_path in [
100 '', # GN keeps them in the root of output_dir
101 'CMakeFiles'
102 ]:
103 path = os.path.join(output_dir, relative_path, 'rules.ninja')
104 if os.path.exists(path):
105 with open(path) as file_handle:
106 for line in file_handle:
107 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
108 use_goma = True
109 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700110
Takuto Ikuta381db682022-04-27 23:54:02 +0000111 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
112 # (case-insensitive) then gomacc will use the local compiler instead of doing
113 # a goma compile. This is convenient if you want to briefly disable goma. It
114 # avoids having to rebuild the world when transitioning between goma/non-goma
115 # builds. However, it is not as fast as doing a "normal" non-goma build
116 # because an extra process is created for each compile step. Checking this
117 # environment variable ensures that autoninja uses an appropriate -j value in
118 # this situation.
119 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
120 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
121 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000122
Takuto Ikuta381db682022-04-27 23:54:02 +0000123 if use_goma:
124 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
125 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
126 gomacc_path = os.path.join(goma_dir, gomacc_file)
127 # Don't invoke gomacc if it doesn't exist.
128 if os.path.exists(gomacc_path):
129 # Check to make sure that goma is running. If not, don't start the build.
130 status = subprocess.call([gomacc_path, 'port'],
131 stdout=subprocess.PIPE,
132 stderr=subprocess.PIPE,
133 shell=False)
134 if status == 1:
Michael Spangf4670892022-10-26 17:35:08 +0000135 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
136 file=sys.stderr)
137 if sys.platform.startswith('win'):
138 # Set an exit code of 1 in the batch file.
139 print('cmd "/c exit 1"')
140 else:
141 # Set an exit code of 1 by executing 'false' in the bash script.
142 print('false')
143 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000144
Takuto Ikuta381db682022-04-27 23:54:02 +0000145 # A large build (with or without goma) tends to hog all system resources.
146 # Launching the ninja process with 'nice' priorities improves this situation.
147 prefix_args = []
148 if (sys.platform.startswith('linux')
149 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
150 # nice -10 is process priority 10 lower than default 0
151 # ionice -c 3 is IO priority IDLE
152 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000153
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000154 # On macOS, the default limit of open file descriptors is too low (256).
155 # This causes a large j value to result in 'Too many open files' errors.
156 # Check whether the limit can be raised to a large enough value. If yes,
157 # use `ulimit -n .... &&` as a prefix to increase the limit when running
158 # ninja.
159 if sys.platform == 'darwin':
160 wanted_limit = 200000 # Large enough to avoid any risk of exhaustion.
161 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
162 if fileno_limit <= wanted_limit:
163 try:
164 resource.setrlimit(resource.RLIMIT_NOFILE, (wanted_limit, hard_limit))
165 except Exception as _:
166 pass
167 fileno_limit, hard_limit = resource.getrlimit(resource.RLIMIT_NOFILE)
168 if fileno_limit >= wanted_limit:
169 prefix_args = ['ulimit', '-n', f'{wanted_limit}', '&&']
170
171
Junji Watanabead452a72022-11-30 02:39:48 +0000172 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
173 # PATH.
174 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
Ben Segalleb2866e2023-01-20 20:14:44 +0000175 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
176 # starting and stopping reproxy.
177 if not offline and use_remoteexec:
178 ninja_path = os.path.join(SCRIPT_DIR, 'ninja_reclient.py')
Junji Watanabead452a72022-11-30 02:39:48 +0000179 args = prefix_args + [sys.executable, ninja_path] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000180
Takuto Ikuta381db682022-04-27 23:54:02 +0000181 num_cores = multiprocessing.cpu_count()
182 if not j_specified and not t_specified:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000183 if use_goma or use_remoteexec or use_rbe:
Takuto Ikuta381db682022-04-27 23:54:02 +0000184 args.append('-j')
Takuto Ikuta6a1494e2022-05-06 01:22:16 +0000185 default_core_multiplier = 80
186 if platform.machine() in ('x86_64', 'AMD64'):
187 # Assume simultaneous multithreading and therefore half as many cores as
188 # logical processors.
189 num_cores //= 2
190
191 core_multiplier = int(
192 os.environ.get('NINJA_CORE_MULTIPLIER', default_core_multiplier))
Takuto Ikuta381db682022-04-27 23:54:02 +0000193 j_value = num_cores * core_multiplier
194
Aleksey Khoroshilov1bc3cd22022-05-09 19:49:42 +0000195 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
196 j_value = min(j_value, core_limit)
197
Takuto Ikuta381db682022-04-27 23:54:02 +0000198 if sys.platform.startswith('win'):
199 # On windows, j value higher than 1000 does not improve build
200 # performance.
201 j_value = min(j_value, 1000)
Sylvain Defresnecb2cef92022-05-10 08:57:20 +0000202 elif sys.platform == 'darwin':
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000203 # If the number of open file descriptors is large enough (or it can be
204 # raised to a large enough value), then set j value to 1000. This limit
205 # comes from ninja which is limited to at most FD_SETSIZE (1024) open
206 # file descriptors (using 1000 leave a bit of head room).
207 #
208 # If the number of open file descriptors cannot be raised, then use a
209 # j value of 200 which is the maximum value that reliably work with
210 # the default limit of 256.
211 if fileno_limit >= wanted_limit:
212 j_value = min(j_value, 1000)
Sylvain Defresne4d992432023-07-26 23:09:06 +0000213 else:
Sylvain Defresne7b4ecc72023-07-27 16:24:54 +0000214 j_value = min(j_value, 200)
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
Takuto Ikuta381db682022-04-27 23:54:02 +0000237 if offline and not sys.platform.startswith('win'):
238 # Tell goma or reclient to do local compiles. On Windows these environment
239 # variables are set by the wrapper batch file.
240 return 'RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)
241
242 return ' '.join(args)
243
244
245if __name__ == '__main__':
246 print(main(sys.argv))