blob: 6f45af28c8e8cc31be322f13520162e9da64b7fd [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
Takuto Ikuta6a1494e2022-05-06 01:22:16 +000018import platform
Bruce Dawsonebebd952017-05-31 14:24:38 -070019import re
Bruce Dawsone952fae2021-02-27 23:33:37 +000020import subprocess
Bruce Dawsonebebd952017-05-31 14:24:38 -070021import sys
22
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000023SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
24
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000025
Takuto Ikuta381db682022-04-27 23:54:02 +000026def main(args):
27 # The -t tools are incompatible with -j
28 t_specified = False
29 j_specified = False
30 offline = False
31 output_dir = '.'
32 input_args = args
33 # On Windows the autoninja.bat script passes along the arguments enclosed in
34 # double quotes. This prevents multiple levels of parsing of the special '^'
35 # characters needed when compiling a single file but means that this script
36 # gets called with a single argument containing all of the actual arguments,
37 # separated by spaces. When this case is detected we need to do argument
38 # splitting ourselves. This means that arguments containing actual spaces are
39 # not supported by autoninja, but that is not a real limitation.
40 if (sys.platform.startswith('win') and len(args) == 2
41 and input_args[1].count(' ') > 0):
42 input_args = args[:1] + args[1].split()
Bruce Dawson655afeb2020-11-02 23:30:37 +000043
Takuto Ikuta381db682022-04-27 23:54:02 +000044 # Ninja uses getopt_long, which allow to intermix non-option arguments.
45 # To leave non supported parameters untouched, we do not use getopt.
46 for index, arg in enumerate(input_args[1:]):
47 if arg.startswith('-j'):
48 j_specified = True
49 if arg.startswith('-t'):
50 t_specified = True
51 if arg == '-C':
52 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
53 output_dir = input_args[index + 2]
54 elif arg.startswith('-C'):
55 # Support -Cout/Default
56 output_dir = arg[2:]
57 elif arg in ('-o', '--offline'):
58 offline = True
59 elif arg == '-h':
60 print('autoninja: Use -o/--offline to temporary disable goma.',
Bruce Dawsone952fae2021-02-27 23:33:37 +000061 file=sys.stderr)
Takuto Ikuta381db682022-04-27 23:54:02 +000062 print(file=sys.stderr)
Bruce Dawsone952fae2021-02-27 23:33:37 +000063
Takuto Ikuta381db682022-04-27 23:54:02 +000064 # Strip -o/--offline so ninja doesn't see them.
65 input_args = [arg for arg in input_args if arg not in ('-o', '--offline')]
Allen Bauer75fa8552018-11-07 22:43:39 +000066
Takuto Ikuta381db682022-04-27 23:54:02 +000067 use_goma = False
68 use_remoteexec = False
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000069 use_rbe = False
Peter McNeeley958dc622020-10-18 17:05:04 +000070
Takuto Ikuta381db682022-04-27 23:54:02 +000071 # Attempt to auto-detect remote build acceleration. We support gn-based
72 # builds, where we look for args.gn in the build tree, and cmake-based builds
73 # where we look for rules.ninja.
74 if os.path.exists(os.path.join(output_dir, 'args.gn')):
75 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
76 for line in file_handle:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000077 # use_goma, use_remoteexec, or use_rbe will activate build acceleration.
Takuto Ikuta381db682022-04-27 23:54:02 +000078 #
79 # This test can match multi-argument lines. Examples of this are:
80 # is_debug=false use_goma=true is_official_build=false
81 # use_goma=false# use_goma=true This comment is ignored
82 #
83 # Anything after a comment is not consider a valid argument.
84 line_without_comment = line.split('#')[0]
85 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
86 line_without_comment):
87 use_goma = True
88 continue
Richard Wangbb07d9e2022-07-07 02:28:59 +000089 if re.search(r'(^|\s)(use_remoteexec)\s*=\s*true($|\s)',
Takuto Ikuta381db682022-04-27 23:54:02 +000090 line_without_comment):
91 use_remoteexec = True
92 continue
Simeon Anfinrudaec39c32023-01-20 00:37:41 +000093 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)', line_without_comment):
94 use_rbe = True
95 continue
96
Bruce Dawsonebebd952017-05-31 14:24:38 -070097 else:
Takuto Ikuta381db682022-04-27 23:54:02 +000098 for relative_path in [
99 '', # GN keeps them in the root of output_dir
100 'CMakeFiles'
101 ]:
102 path = os.path.join(output_dir, relative_path, 'rules.ninja')
103 if os.path.exists(path):
104 with open(path) as file_handle:
105 for line in file_handle:
106 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
107 use_goma = True
108 break
Bruce Dawsonebebd952017-05-31 14:24:38 -0700109
Takuto Ikuta381db682022-04-27 23:54:02 +0000110 # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1"
111 # (case-insensitive) then gomacc will use the local compiler instead of doing
112 # a goma compile. This is convenient if you want to briefly disable goma. It
113 # avoids having to rebuild the world when transitioning between goma/non-goma
114 # builds. However, it is not as fast as doing a "normal" non-goma build
115 # because an extra process is created for each compile step. Checking this
116 # environment variable ensures that autoninja uses an appropriate -j value in
117 # this situation.
118 goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
119 if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
120 use_goma = False
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000121
Takuto Ikuta381db682022-04-27 23:54:02 +0000122 if use_goma:
123 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
124 goma_dir = os.environ.get('GOMA_DIR', os.path.join(SCRIPT_DIR, '.cipd_bin'))
125 gomacc_path = os.path.join(goma_dir, gomacc_file)
126 # Don't invoke gomacc if it doesn't exist.
127 if os.path.exists(gomacc_path):
128 # Check to make sure that goma is running. If not, don't start the build.
129 status = subprocess.call([gomacc_path, 'port'],
130 stdout=subprocess.PIPE,
131 stderr=subprocess.PIPE,
132 shell=False)
133 if status == 1:
Michael Spangf4670892022-10-26 17:35:08 +0000134 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
135 file=sys.stderr)
136 if sys.platform.startswith('win'):
137 # Set an exit code of 1 in the batch file.
138 print('cmd "/c exit 1"')
139 else:
140 # Set an exit code of 1 by executing 'false' in the bash script.
141 print('false')
142 sys.exit(1)
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000143
Takuto Ikuta381db682022-04-27 23:54:02 +0000144 # A large build (with or without goma) tends to hog all system resources.
145 # Launching the ninja process with 'nice' priorities improves this situation.
146 prefix_args = []
147 if (sys.platform.startswith('linux')
148 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
149 # nice -10 is process priority 10 lower than default 0
150 # ionice -c 3 is IO priority IDLE
151 prefix_args = ['nice'] + ['-10']
Michael Savigny20eda952021-01-20 01:16:27 +0000152
Junji Watanabead452a72022-11-30 02:39:48 +0000153 # Call ninja.py so that it can find ninja binary installed by DEPS or one in
154 # PATH.
155 ninja_path = os.path.join(SCRIPT_DIR, 'ninja.py')
Ben Segalleb2866e2023-01-20 20:14:44 +0000156 # If using remoteexec, use ninja_reclient.py which wraps ninja.py with
157 # starting and stopping reproxy.
158 if not offline and use_remoteexec:
159 ninja_path = os.path.join(SCRIPT_DIR, 'ninja_reclient.py')
Junji Watanabead452a72022-11-30 02:39:48 +0000160 args = prefix_args + [sys.executable, ninja_path] + input_args[1:]
Michael Savigny20eda952021-01-20 01:16:27 +0000161
Takuto Ikuta381db682022-04-27 23:54:02 +0000162 num_cores = multiprocessing.cpu_count()
163 if not j_specified and not t_specified:
Simeon Anfinrudaec39c32023-01-20 00:37:41 +0000164 if use_goma or use_remoteexec or use_rbe:
Takuto Ikuta381db682022-04-27 23:54:02 +0000165 args.append('-j')
Takuto Ikuta6a1494e2022-05-06 01:22:16 +0000166 default_core_multiplier = 80
167 if platform.machine() in ('x86_64', 'AMD64'):
168 # Assume simultaneous multithreading and therefore half as many cores as
169 # logical processors.
170 num_cores //= 2
171
172 core_multiplier = int(
173 os.environ.get('NINJA_CORE_MULTIPLIER', default_core_multiplier))
Takuto Ikuta381db682022-04-27 23:54:02 +0000174 j_value = num_cores * core_multiplier
175
Aleksey Khoroshilov1bc3cd22022-05-09 19:49:42 +0000176 core_limit = int(os.environ.get('NINJA_CORE_LIMIT', j_value))
177 j_value = min(j_value, core_limit)
178
Takuto Ikuta381db682022-04-27 23:54:02 +0000179 if sys.platform.startswith('win'):
180 # On windows, j value higher than 1000 does not improve build
181 # performance.
182 j_value = min(j_value, 1000)
Sylvain Defresnecb2cef92022-05-10 08:57:20 +0000183 elif sys.platform == 'darwin':
184 # On macOS, j value higher than 800 causes 'Too many open files' error
185 # (crbug.com/936864).
186 j_value = min(j_value, 800)
Takuto Ikuta381db682022-04-27 23:54:02 +0000187
188 args.append('%d' % j_value)
189 else:
190 j_value = num_cores
191 # Ninja defaults to |num_cores + 2|
192 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
193 args.append('-j')
194 args.append('%d' % j_value)
195
196 # On Windows, fully quote the path so that the command processor doesn't think
197 # the whole output is the command.
198 # On Linux and Mac, if people put depot_tools in directories with ' ',
199 # shell would misunderstand ' ' as a path separation.
200 # TODO(yyanagisawa): provide proper quoting for Windows.
201 # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
202 for i in range(len(args)):
203 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
204 args[i] = '"%s"' % args[i].replace('"', '\\"')
205
206 if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
207 args += ['-d', 'stats']
208
Takuto Ikuta381db682022-04-27 23:54:02 +0000209 if offline and not sys.platform.startswith('win'):
210 # Tell goma or reclient to do local compiles. On Windows these environment
211 # variables are set by the wrapper batch file.
212 return 'RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args)
213
214 return ' '.join(args)
215
216
217if __name__ == '__main__':
218 print(main(sys.argv))