blob: 2ba7c864aa4078c54941f3125d8118e2c78fbda5 [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
18import re
Bruce Dawsone952fae2021-02-27 23:33:37 +000019import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070020import sys
21
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000022SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
23
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000024
Takuto Ikuta381db682022-04-27 23:54:02 +000025def main(args):
26 # The -t tools are incompatible with -j
27 t_specified = False
28 j_specified = False
29 offline = False
30 output_dir = '.'
31 input_args = args
32 # On Windows the autoninja.bat script passes along the arguments enclosed in
33 # double quotes. This prevents multiple levels of parsing of the special '^'
34 # characters needed when compiling a single file but means that this script
35 # gets called with a single argument containing all of the actual arguments,
36 # separated by spaces. When this case is detected we need to do argument
37 # splitting ourselves. This means that arguments containing actual spaces are
38 # not supported by autoninja, but that is not a real limitation.
39 if (sys.platform.startswith('win') and len(args) == 2
40 and input_args[1].count(' ') > 0):
41 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +000042
Takuto Ikuta381db682022-04-27 23:54:02 +000043 # Ninja uses getopt_long, which allow to intermix non-option arguments.
44 # To leave non supported parameters untouched, we do not use getopt.
45 for index, arg in enumerate(input_args[1:]):
46 if arg.startswith('-j'):
47 j_specified = True
48 if arg.startswith('-t'):
49 t_specified = True
50 if arg == '-C':
51 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
52 output_dir = input_args[index + 2]
53 elif arg.startswith('-C'):
54 # Support -Cout/Default
55 output_dir = arg[2:]
56 elif arg in ('-o', '--offline'):
57 offline = True
58 elif arg == '-h':
59 print('autoninja: Use -o/--offline to temporary disable goma.',
Bruce Dawsone952fae2021-02-27 23:33:37 +000060 file=sys.stderr)
Takuto Ikuta381db682022-04-27 23:54:02 +000061 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +000062
Takuto Ikuta381db682022-04-27 23:54:02 +000063 # Strip -o/--offline so ninja doesn't see them.
64 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
Allen Bauer75fa8552018-11-07 22:43:39 +000065
Takuto Ikuta381db682022-04-27 23:54:02 +000066 use_goma = False
67 use_remoteexec = False
Peter McNeeley958dc622020-10-18 17:05:04 +000068
Takuto Ikuta381db682022-04-27 23:54:02 +000069 # Currently get reclient binary and config dirs relative to output_dir. If
70 # they exist and using remoteexec, then automatically call bootstrap to start
71 # reproxy. This works under the current assumption that the output
72 # directory is two levels up from chromium/src.
73 reclient_bin_dir = os.path.join(output_dir, '..', '..', 'buildtools',
74 'reclient')
75 reclient_cfg = os.path.join(output_dir, '..', '..', 'buildtools',
76 'reclient_cfgs', 'reproxy.cfg')
Peter McNeeley958dc622020-10-18 17:05:04 +000077
Takuto Ikuta381db682022-04-27 23:54:02 +000078 # Attempt to auto-detect remote build acceleration. We support gn-based
79 # builds, where we look for args.gn in the build tree, and cmake-based builds
80 # where we look for rules.ninja.
81 if os.path.exists(os.path.join(output_dir, 'args.gn')):
82 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
83 for line in file_handle:
84 # Either use_goma, use_remoteexec or use_rbe (in deprecation)
85 # activate build acceleration.
86 #
87 # This test can match multi-argument lines. Examples of this are:
88 # is_debug=false use_goma=true is_official_build=false
89 # use_goma=false# use_goma=true This comment is ignored
90 #
91 # Anything after a comment is not consider a valid argument.
92 line_without_comment = line.split('#')[0]
93 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
94 line_without_comment):
95 use_goma = True
96 continue
97 if re.search(r'(^|\s)(use_rbe|use_remoteexec)\s*=\s*true($|\s)',
98 line_without_comment):
99 use_remoteexec = True
100 continue
Bruce Dawsonebebd952017-05-31 14:24:38 -0700101 else:
Takuto Ikuta381db682022-04-27 23:54:02 +0000102 for relative_path in [
103 '', # GN keeps them in the root of output_dir
104 'CMakeFiles'
105 ]:
106 path = os.path.join(output_dir, relative_path, 'rules.ninja')
107 if os.path.exists(path):
108 with open(path) as file_handle:
109 for line in file_handle:
110 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
111 use_goma = True
112 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700113
Takuto Ikuta381db682022-04-27 23:54:02 +0000114 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
115 # (case-insensitive) then gomacc will use the local compiler instead of doing
116 # a goma compile. This is convenient if you want to briefly disable goma. It
117 # avoids having to rebuild the world when transitioning between goma/non-goma
118 # builds. However, it is not as fast as doing a "normal" non-goma build
119 # because an extra process is created for each compile step. Checking this
120 # environment variable ensures that autoninja uses an appropriate -j value in
121 # this situation.
122 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
123 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
124 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000125
Takuto Ikuta381db682022-04-27 23:54:02 +0000126 if use_goma:
127 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
128 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
129 gomacc_path = os.path.join(goma_dir, gomacc_file)
130 # Don't invoke gomacc if it doesn't exist.
131 if os.path.exists(gomacc_path):
132 # Check to make sure that goma is running. If not, don't start the build.
133 status = subprocess.call([gomacc_path, 'port'],
134 stdout=subprocess.PIPE,
135 stderr=subprocess.PIPE,
136 shell=False)
137 if status == 1:
138 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
139 file=sys.stderr)
140 if sys.platform.startswith('win'):
141 # Set an exit code of 1 in the batch file.
142 print('cmd "/c exit 1"')
143 else:
144 # Set an exit code of 1 by executing 'false' in the bash script.
145 print('false')
146 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000147
Takuto Ikuta381db682022-04-27 23:54:02 +0000148 # Specify ninja.exe on Windows so that ninja.bat can call autoninja and not
149 # be called back.
150 ninja_exe = 'ninja.exe' if sys.platform.startswith('win') else 'ninja'
151 ninja_exe_path = os.path.join(SCRIPT_DIR, ninja_exe)
Michael Savigny20eda952021-01-20 01:16:27 +0000152
Takuto Ikuta381db682022-04-27 23:54:02 +0000153 # A large build (with or without goma) tends to hog all system resources.
154 # Launching the ninja process with 'nice' priorities improves this situation.
155 prefix_args = []
156 if (sys.platform.startswith('linux')
157 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
158 # nice -10 is process priority 10 lower than default 0
159 # ionice -c 3 is IO priority IDLE
160 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000161
Takuto Ikuta381db682022-04-27 23:54:02 +0000162 # Use absolute path for ninja path,
163 # or fail to execute ninja if depot_tools is not in PATH.
164 args = prefix_args + [ninja_exe_path] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000165
Takuto Ikuta381db682022-04-27 23:54:02 +0000166 num_cores = multiprocessing.cpu_count()
167 if not j_specified and not t_specified:
168 if use_goma or use_remoteexec:
169 args.append('-j')
170 core_multiplier = int(os.environ.get('NINJA_CORE_MULTIPLIER', '40'))
171 j_value = num_cores * core_multiplier
172
173 if sys.platform.startswith('win'):
174 # On windows, j value higher than 1000 does not improve build
175 # performance.
176 j_value = min(j_value, 1000)
177 elif sys.platform == 'darwin':
178 # On Mac, j value higher than 500 causes 'Too many open files' error
179 # (crbug.com/936864).
180 j_value = min(j_value, 500)
181
182 args.append('%d' % j_value)
183 else:
184 j_value = num_cores
185 # Ninja defaults to |num_cores + 2|
186 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
187 args.append('-j')
188 args.append('%d' % j_value)
189
190 # On Windows, fully quote the path so that the command processor doesn't think
191 # the whole output is the command.
192 # On Linux and Mac, if people put depot_tools in directories with ' ',
193 # shell would misunderstand ' ' as a path separation.
194 # TODO(yyanagisawa): provide proper quoting for Windows.
195 # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
196 for i in range(len(args)):
197 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
198 args[i] = '"%s"' % args[i].replace('"', '\\"')
199
200 if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
201 args += ['-d', 'stats']
202
203 # If using remoteexec and the necessary environment variables are set,
204 # also start reproxy (via bootstrap) before running ninja.
205 if (not offline and use_remoteexec and os.path.exists(reclient_bin_dir)
206 and os.path.exists(reclient_cfg)):
207 bootstrap = os.path.join(reclient_bin_dir, 'bootstrap')
208 setup_args = [
209 bootstrap, '--cfg=' + reclient_cfg,
210 '--re_proxy=' + os.path.join(reclient_bin_dir, 'reproxy')
211 ]
212
213 teardown_args = [bootstrap, '--cfg=' + reclient_cfg, '--shutdown']
214
215 cmd_sep = '\n' if sys.platform.startswith('win') else '&&'
216 args = setup_args + [cmd_sep] + args + [cmd_sep] + teardown_args
217
218 if offline and not sys.platform.startswith('win'):
219 # Tell goma or reclient to do local compiles. On Windows these environment
220 # variables are set by the wrapper batch file.
221 return 'RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)
222
223 return ' '.join(args)
224
225
226if __name__ == '__main__':
227 print(main(sys.argv))