blob: 0322ba273991894f75a3b4e070a8311766e6c88e [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
Yoshisato Yanagisawa428143e2021-01-15 10:24:48 +000014# [VPYTHON:BEGIN]
15# wheel: <
16# name: "infra/python/wheels/psutil/${vpython_platform}"
17# version: "version:5.6.2"
18# >
19# [VPYTHON:END]
20
Raul Tambre80ee78e2019-05-06 22:41:05 +000021from __future__ import print_function
22
Bruce Dawsonebebd952017-05-31 14:24:38 -070023import os
Yoshisato Yanagisawa428143e2021-01-15 10:24:48 +000024import psutil
Bruce Dawsonebebd952017-05-31 14:24:38 -070025import re
26import sys
27
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +000028SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
29
Yoshisato Yanagisawa0db62fc2018-11-01 01:09:53 +000030# The -t tools are incompatible with -j
Bruce Dawson1f767e12017-07-07 15:10:37 -070031t_specified = False
Bruce Dawsonebebd952017-05-31 14:24:38 -070032j_specified = False
Bruce Dawson655afeb2020-11-02 23:30:37 +000033offline = False
Bruce Dawsonebebd952017-05-31 14:24:38 -070034output_dir = '.'
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070035input_args = sys.argv
36# On Windows the autoninja.bat script passes along the arguments enclosed in
37# double quotes. This prevents multiple levels of parsing of the special '^'
38# characters needed when compiling a single file but means that this script gets
39# called with a single argument containing all of the actual arguments,
40# separated by spaces. When this case is detected we need to do argument
41# splitting ourselves. This means that arguments containing actual spaces are
42# not supported by autoninja, but that is not a real limitation.
43if (sys.platform.startswith('win') and len(sys.argv) == 2 and
44 input_args[1].count(' ') > 0):
45 input_args = sys.argv[:1] + sys.argv[1].split()
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000046
47# Ninja uses getopt_long, which allow to intermix non-option arguments.
48# To leave non supported parameters untouched, we do not use getopt.
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070049for index, arg in enumerate(input_args[1:]):
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000050 if arg.startswith('-j'):
Bruce Dawsonebebd952017-05-31 14:24:38 -070051 j_specified = True
Yoshisato Yanagisawaf66e5512018-11-15 00:40:39 +000052 if arg.startswith('-t'):
Bruce Dawson1f767e12017-07-07 15:10:37 -070053 t_specified = True
Bruce Dawsonebebd952017-05-31 14:24:38 -070054 if arg == '-C':
Bruce Dawsonf3b4f062017-09-07 17:22:26 -070055 # + 1 to get the next argument and +1 because we trimmed off input_args[0]
56 output_dir = input_args[index + 2]
Bruce Dawson6af3aa82018-10-03 16:39:42 +000057 elif arg.startswith('-C'):
58 # Support -Cout/Default
59 output_dir = arg[2:]
Bruce Dawson655afeb2020-11-02 23:30:37 +000060 elif arg == '-o' or arg == '--offline':
61 offline = True
62 elif arg == '-h':
63 print('autoninja: Use -o/--offline to temporary disable goma.',
64 file=sys.stderr)
65 print(file=sys.stderr)
66
67# Strip -o/--offline so ninja doesn't see them.
68input_args = [ arg for arg in input_args if arg != '-o' and arg != '--offline']
Bruce Dawsonebebd952017-05-31 14:24:38 -070069
Michael Savigny20eda952021-01-20 01:16:27 +000070use_goma = False
71use_rbe = False
72
73# Currently get reclient binary and config dirs relative to output_dir. If
74# they exist and using rbe, then automatically call bootstrap to start
75# reproxy. This works under the current assumption that the output
76# directory is two levels up from chromium/src.
77reclient_bin_dir = os.path.join(output_dir, "../../buildtools/reclient")
78reclient_cfg = os.path.join(
79 output_dir, "../../buildtools/reclient_cfgs/reproxy.cfg")
Sam Clegg3a96d622019-08-22 21:22:04 +000080
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +000081# Attempt to auto-detect remote build acceleration. We support gn-based
82# builds, where we look for args.gn in the build tree, and cmake-based builds
83# where we look for rules.ninja.
Sam Clegg3a96d622019-08-22 21:22:04 +000084if os.path.exists(os.path.join(output_dir, 'args.gn')):
Gabriel Charette125f7cc2019-06-20 19:19:35 +000085 with open(os.path.join(output_dir, 'args.gn')) as file_handle:
86 for line in file_handle:
Simeon Anfinrud5dba9c92020-09-03 20:02:05 +000087 # Either use_goma or use_rbe activate build acceleration.
Peter McNeeley958dc622020-10-18 17:05:04 +000088 #
89 # This test can match multi-argument lines. Examples of this are:
90 # is_debug=false use_goma=true is_official_build=false
91 # use_goma=false# use_goma=true This comment is ignored
92 #
93 # Anything after a comment is not consider a valid argument.
94 line_without_comment = line.split('#')[0]
Michael Savigny20eda952021-01-20 01:16:27 +000095 if re.search(r'(^|\s)(use_goma)\s*=\s*true($|\s)',
Peter McNeeley958dc622020-10-18 17:05:04 +000096 line_without_comment):
Michael Savigny20eda952021-01-20 01:16:27 +000097 use_goma = True
98 continue
99 if re.search(r'(^|\s)(use_rbe)\s*=\s*true($|\s)',
100 line_without_comment):
101 use_rbe = True
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000102 continue
Vitaly Bukab2c18f22020-12-03 23:47:51 +0000103else:
104 for relative_path in [
105 '', # GN keeps them in the root of output_dir
106 'CMakeFiles'
107 ]:
108 path = os.path.join(output_dir, relative_path, 'rules.ninja')
109 if os.path.exists(path):
110 with open(path) as file_handle:
111 for line in file_handle:
112 if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
Michael Savigny20eda952021-01-20 01:16:27 +0000113 use_goma = True
Vitaly Bukab2c18f22020-12-03 23:47:51 +0000114 break
Sam Clegg3a96d622019-08-22 21:22:04 +0000115
Bruce Dawson6a860322019-09-09 18:03:40 +0000116# If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1" (case-insensitive)
117# then gomacc will use the local compiler instead of doing a goma compile. This
118# is convenient if you want to briefly disable goma. It avoids having to rebuild
119# the world when transitioning between goma/non-goma builds. However, it is not
120# as fast as doing a "normal" non-goma build because an extra process is created
121# for each compile step. Checking this environment variable ensures that
122# autoninja uses an appropriate -j value in this situation.
123goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
Bruce Dawson655afeb2020-11-02 23:30:37 +0000124if offline or goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
Michael Savigny20eda952021-01-20 01:16:27 +0000125 use_goma = False
Bruce Dawsonebebd952017-05-31 14:24:38 -0700126
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +0000127# Specify ninja.exe on Windows so that ninja.bat can call autoninja and not
128# be called back.
129ninja_exe = 'ninja.exe' if sys.platform.startswith('win') else 'ninja'
Allen Bauer75fa8552018-11-07 22:43:39 +0000130ninja_exe_path = os.path.join(SCRIPT_DIR, ninja_exe)
131
Peter McNeeley958dc622020-10-18 17:05:04 +0000132# A large build (with or without goma) tends to hog all system resources.
133# Launching the ninja process with 'nice' priorities improves this situation.
134prefix_args = []
135if (sys.platform.startswith('linux')
136 and os.environ.get('NINJA_BUILD_IN_BACKGROUND', '0') == '1'):
137 # nice -10 is process priority 10 lower than default 0
138 # ionice -c 3 is IO priority IDLE
139 prefix_args = ['nice'] + ['-10']
140
141
Yoshisato Yanagisawa4b497072018-11-07 02:52:33 +0000142# Use absolute path for ninja path,
143# or fail to execute ninja if depot_tools is not in PATH.
Peter McNeeley958dc622020-10-18 17:05:04 +0000144args = prefix_args + [ninja_exe_path] + input_args[1:]
Bruce Dawsonebebd952017-05-31 14:24:38 -0700145
Yoshisato Yanagisawa428143e2021-01-15 10:24:48 +0000146num_cores = psutil.cpu_count()
Bruce Dawson1f767e12017-07-07 15:10:37 -0700147if not j_specified and not t_specified:
Michael Savigny20eda952021-01-20 01:16:27 +0000148 if use_goma or use_rbe:
Bruce Dawsonebebd952017-05-31 14:24:38 -0700149 args.append('-j')
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000150 core_multiplier = int(os.environ.get('NINJA_CORE_MULTIPLIER', '40'))
Takuto Ikuta1206a352019-02-07 22:18:08 +0000151 j_value = num_cores * core_multiplier
152
153 if sys.platform.startswith('win'):
154 # On windows, j value higher than 1000 does not improve build performance.
155 j_value = min(j_value, 1000)
Takuto Ikutada4dbf82019-03-04 03:21:58 +0000156 elif sys.platform == 'darwin':
157 # On Mac, j value higher than 500 causes 'Too many open files' error
158 # (crbug.com/936864).
159 j_value = min(j_value, 500)
Takuto Ikuta1206a352019-02-07 22:18:08 +0000160
161 args.append('%d' % j_value)
Bruce Dawsonebebd952017-05-31 14:24:38 -0700162 else:
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000163 j_value = num_cores
164 # Ninja defaults to |num_cores + 2|
165 j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
Gabriel Charette125f7cc2019-06-20 19:19:35 +0000166 args.append('-j')
167 args.append('%d' % j_value)
Bruce Dawsonebebd952017-05-31 14:24:38 -0700168
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000169# On Windows, fully quote the path so that the command processor doesn't think
170# the whole output is the command.
171# On Linux and Mac, if people put depot_tools in directories with ' ',
172# shell would misunderstand ' ' as a path separation.
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000173# TODO(yyanagisawa): provide proper quoting for Windows.
Yoshisato Yanagisawa43a35d22018-11-15 03:00:51 +0000174# see https://cs.chromium.org/chromium/src/tools/mb/mb.py
175for i in range(len(args)):
176 if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
177 args[i] = '"%s"' % args[i].replace('"', '\\"')
178
Bruce Dawsonb3b46a22019-09-06 15:57:52 +0000179if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
180 args += ['-d', 'stats']
181
Michael Savigny20eda952021-01-20 01:16:27 +0000182# If using rbe and the necessary environment variables are set, also start
183# reproxy (via bootstrap) before running ninja.
184if (not offline and use_rbe and os.path.exists(reclient_bin_dir)
185 and os.path.exists(reclient_cfg)):
186 setup_args = [
187 'RBE_cfg=' + reclient_cfg,
188 reclient_bin_dir + '/bootstrap',
189 '--re_proxy=' + reclient_bin_dir + '/reproxy']
190
191 teardown_args = [reclient_bin_dir + '/bootstrap', '--shutdown']
192
193 args = setup_args + ['&&'] + args + ['&&'] + teardown_args
194
Bruce Dawson655afeb2020-11-02 23:30:37 +0000195if offline and not sys.platform.startswith('win'):
Michael Savigny684460d2020-12-01 19:39:52 +0000196 # Tell goma or reclient to do local compiles. On Windows these environment
197 # variables are set by the wrapper batch file.
198 print('RBE_remote_disabled=1 GOMA_DISABLED=1 ' + ' '.join(args))
Bruce Dawson655afeb2020-11-02 23:30:37 +0000199else:
200 print(' '.join(args))
Yoshisato Yanagisawaf79e4322021-01-15 10:24:02 +0000201