autoninja.py 9.3 KB

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