blob: 424cebb6420296ffab9fa6e6f8d4500ac3725487 [file] [log] [blame]
Gabriel Charette125f7cc2019-06-20 19:19:35 +00001#!/usr/bin/env vpython
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 Yanagisawa0db62fc2018-11-01 01:09:53 +000024# The -t tools are incompatible with -j
Bruce Dawson1f767e12017-07-07 15:10:37 -070025t_specified = False
Bruce Dawsonebebd952017-05-31 14:24:38 -070026j_specified = False
Bruce Dawson655afeb2020-11-02 23:30:37 +000027offline = False
Bruce Dawsonebebd952017-05-31 14:24:38 -070028output_dir = '.'
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070029input_args = sys.argv
30# On Windows the autoninja.bat script passes along the arguments enclosed in
31# double quotes. This prevents multiple levels of parsing of the special '^'
32# characters needed when compiling a single file but means that this script gets
33# called with a single argument containing all of the actual arguments,
34# separated by spaces. When this case is detected we need to do argument
35# splitting ourselves. This means that arguments containing actual spaces are
36# not supported by autoninja, but that is not a real limitation.
37if (sys.platform.startswith('win') and len(sys.argv) == 2 and
38 input_args[1].count(' ') > 0):
39 input_args = sys.argv[:1] + sys.argv[1].split()
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000040
41# Ninja uses getopt_long, which allow to intermix non-option arguments.
42# To leave non supported parameters untouched, we do not use getopt.
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070043for index, arg in enumerate(input_args[1:]):
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000044 if arg.startswith('-j'):
Bruce Dawsonebebd952017-05-31 14:24:38 -070045 j_specified = True
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000046 if arg.startswith('-t'):
Bruce Dawson1f767e12017-07-07 15:10:37 -070047 t_specified = True
Bruce Dawsonebebd952017-05-31 14:24:38 -070048 if arg == '-C':
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070049 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
50 output_dir = input_args[index + 2]
Bruce Dawson6af3aa82018-10-03 16:39:42 +000051 elif arg.startswith('-C'):
52 # Support -Cout/Default
53 output_dir = arg[2:]
Bruce Dawson655afeb2020-11-02 23:30:37 +000054 elif arg == '-o' or arg == '--offline':
55 offline = True
56 elif arg == '-h':
57 print('autoninja: Use -o/--offline to temporary disable goma.',
58 file=sys.stderr)
59 print(file=sys.stderr)
60
61# Strip -o/--offline so ninja doesn't see them.
62input_args = [ arg for arg in input_args if arg != '-o' and arg != '--offline']
Bruce Dawsonebebd952017-05-31 14:24:38 -070063
Michael Savigny20eda952021-01-20 01:16:27 +000064use_goma = False
65use_rbe = False
66
67# Currently get reclient binary and config dirs relative to output_dir. If
68# they exist and using rbe, then automatically call bootstrap to start
69# reproxy. This works under the current assumption that the output
70# directory is two levels up from chromium/src.
Ola Rozenfeldca63c052021-01-26 16:24:10 +000071reclient_bin_dir = os.path.join(
72 output_dir, '..', '..', 'buildtools', 'reclient')
Michael Savigny20eda952021-01-20 01:16:27 +000073reclient_cfg = os.path.join(
Ola Rozenfeldca63c052021-01-26 16:24:10 +000074 output_dir, '..', '..', 'buildtools', 'reclient_cfgs', 'reproxy.cfg')
Sam Clegg3a96d622019-08-22 21:22:04 +000075
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +000076# Attempt to auto-detect remote build acceleration. We support gn-based
77# builds, where we look for args.gn in the build tree, and cmake-based builds
78# where we look for rules.ninja.
Sam Clegg3a96d622019-08-22 21:22:04 +000079if os.path.exists(os.path.join(output_dir, 'args.gn')):
Gabriel Charette125f7cc2019-06-20 19:19:35 +000080 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
81 for line in file_handle:
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +000082 # Either use_goma or use_rbe activate build acceleration.
Peter McNeeley958dc622020-10-18 17:05:04 +000083 #
84 # This test can match multi-argument lines. Examples of this are:
85 # is_debug=false use_goma=true is_official_build=false
86 # use_goma=false# use_goma=true This comment is ignored
87 #
88 # Anything after a comment is not consider a valid argument.
89 line_without_comment = line.split('#')[0]
Michael Savigny20eda952021-01-20 01:16:27 +000090 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
Peter McNeeley958dc622020-10-18 17:05:04 +000091 line_without_comment):
Michael Savigny20eda952021-01-20 01:16:27 +000092 use_goma = True
93 continue
94 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)',
95 line_without_comment):
96 use_rbe = True
Gabriel Charette125f7cc2019-06-20 19:19:35 +000097 continue
Vitaly Bukab2c18f22020-12-03 23:47:51 +000098else:
99 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):
Michael Savigny20eda952021-01-20 01:16:27 +0000108 use_goma = True
Vitaly Bukab2c18f22020-12-03 23:47:51 +0000109 break
Sam Clegg3a96d622019-08-22 21:22:04 +0000110
Bruce Dawson6a860322019-09-09 18:03:40 +0000111# If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1" (case-insensitive)
112# then gomacc will use the local compiler instead of doing a goma compile. This
113# is convenient if you want to briefly disable goma. It avoids having to rebuild
114# the world when transitioning between goma/non-goma builds. However, it is not
115# as fast as doing a "normal" non-goma build because an extra process is created
116# for each compile step. Checking this environment variable ensures that
117# autoninja uses an appropriate -j value in this situation.
118goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
Bruce Dawson655afeb2020-11-02 23:30:37 +0000119if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
Michael Savigny20eda952021-01-20 01:16:27 +0000120 use_goma = False
Bruce Dawsonebebd952017-05-31 14:24:38 -0700121
Bruce Dawsone952fae2021-02-27 23:33:37 +0000122if use_goma:
123 gomacc_file = 'gomacc.exe' if sys.platform.startswith('win') else 'gomacc'
124 gomacc_path = os.path.join(SCRIPT_DIR, '.cipd_bin', gomacc_file)
125 # Don't invoke gomacc if it doesn't exist.
126 if os.path.exists(gomacc_path):
127 # Check to make sure that goma is running. If not, don't start the build.
128 status = subprocess.call([gomacc_path, 'port'], stdout=subprocess.PIPE,
129 stderr=subprocess.PIPE, shell=False)
130 if status == 1:
131 print('Goma is not running. Use "goma_ctl ensure_start" to start it.',
132 file=sys.stderr)
133 if sys.platform.startswith('win'):
134 # Set an exit code of 1 in the batch file.
Bruce Dawsonc3a48f92021-03-02 23:22:14 +0000135 print('cmd "/c exit 1"')
Bruce Dawsone952fae2021-02-27 23:33:37 +0000136 else:
137 # Set an exit code of 1 by executing 'false' in the bash script.
138 print('false')
139 sys.exit(1)
140
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +0000141# Specify ninja.exe on Windows so that ninja.bat can call autoninja and not
142# be called back.
143ninja_exe = 'ninja.exe' if sys.platform.startswith('win') else 'ninja'
Allen Bauer75fa8552018-11-07 22:43:39 +0000144ninja_exe_path = os.path.join(SCRIPT_DIR, ninja_exe)
145
Peter McNeeley958dc622020-10-18 17:05:04 +0000146# A large build (with or without goma) tends to hog all system resources.
147# Launching the ninja process with 'nice' priorities improves this situation.
148prefix_args = []
149if (sys.platform.startswith('linux')
150 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
151 # nice -10 is process priority 10 lower than default 0
152 # ionice -c 3 is IO priority IDLE
153 prefix_args = ['nice'] + ['-10']
154
155
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +0000156# Use absolute path for ninja path,
157# or fail to execute ninja if depot_tools is not in PATH.
Peter McNeeley958dc622020-10-18 17:05:04 +0000158args = prefix_args + [ninja_exe_path] + input_args[1:]
Bruce Dawsonebebd952017-05-31 14:24:38 -0700159
Bruce Dawsone952fae2021-02-27 23:33:37 +0000160num_cores = multiprocessing.cpu_count()
Bruce Dawson1f767e12017-07-07 15:10:37 -0700161if not j_specified and not t_specified:
Michael Savigny20eda952021-01-20 01:16:27 +0000162 if use_goma or use_rbe:
Bruce Dawsonebebd952017-05-31 14:24:38 -0700163 args.append('-j')
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000164 core_multiplier = int(os.environ.get('NINJA_CORE_MULTIPLIER', '40'))
Takuto Ikuta1206a352019-02-07 22:18:08 +0000165 j_value = num_cores * core_multiplier
166
167 if sys.platform.startswith('win'):
168 # On windows, j value higher than 1000 does not improve build performance.
169 j_value = min(j_value, 1000)
Takuto Ikutada4dbf82019-03-04 03:21:58 +0000170 elif sys.platform == 'darwin':
171 # On Mac, j value higher than 500 causes 'Too many open files' error
172 # (crbug.com/936864).
173 j_value = min(j_value, 500)
Takuto Ikuta1206a352019-02-07 22:18:08 +0000174
175 args.append('%d' % j_value)
Bruce Dawsonebebd952017-05-31 14:24:38 -0700176 else:
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000177 j_value = num_cores
178 # Ninja defaults to |num_cores + 2|
179 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000180 args.append('-j')
181 args.append('%d' % j_value)
Bruce Dawsonebebd952017-05-31 14:24:38 -0700182
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000183# On Windows, fully quote the path so that the command processor doesn't think
184# the whole output is the command.
185# On Linux and Mac, if people put depot_tools in directories with ' ',
186# shell would misunderstand ' ' as a path separation.
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000187# TODO(yyanagisawa): provide proper quoting for Windows.
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000188# see https://cs.chromium.org/chromium/src/tools/mb/mb.py
189for i in range(len(args)):
190 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
191 args[i] = '"%s"' % args[i].replace('"', '\\"')
192
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000193if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
194 args += ['-d', 'stats']
195
Michael Savigny20eda952021-01-20 01:16:27 +0000196# If using rbe and the necessary environment variables are set, also start
197# reproxy (via bootstrap) before running ninja.
Ola Rozenfeldca63c052021-01-26 16:24:10 +0000198if (not offline and use_rbe and os.path.exists(reclient_bin_dir)
Michael Savigny20eda952021-01-20 01:16:27 +0000199 and os.path.exists(reclient_cfg)):
Ola Rozenfeldca63c052021-01-26 16:24:10 +0000200 bootstrap = os.path.join(reclient_bin_dir, 'bootstrap')
Michael Savigny20eda952021-01-20 01:16:27 +0000201 setup_args = [
Ola Rozenfeldca63c052021-01-26 16:24:10 +0000202 bootstrap,
203 '--cfg=' + reclient_cfg,
204 '--re_proxy=' + os.path.join(reclient_bin_dir, 'reproxy')]
Michael Savigny20eda952021-01-20 01:16:27 +0000205
Ola Rozenfeldca63c052021-01-26 16:24:10 +0000206 teardown_args = [bootstrap, '--cfg=' + reclient_cfg, '--shutdown']
Michael Savigny20eda952021-01-20 01:16:27 +0000207
Ola Rozenfeldca63c052021-01-26 16:24:10 +0000208 cmd_sep = '\n' if sys.platform.startswith('win') else '&&'
209 args = setup_args + [cmd_sep] + args + [cmd_sep] + teardown_args
Michael Savigny20eda952021-01-20 01:16:27 +0000210
Bruce Dawson655afeb2020-11-02 23:30:37 +0000211if offline and not sys.platform.startswith('win'):
Michael Savigny684460d2020-12-01 19:39:52 +0000212 # Tell goma or reclient to do local compiles. On Windows these environment
213 # variables are set by the wrapper batch file.
214 print('RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args))
Bruce Dawson655afeb2020-11-02 23:30:37 +0000215else:
216 print(' '.join(args))