autoninja.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. #!/usr/bin/env vpython
  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 using goma. If so it runs with a large -j value, and
  8. otherwise it chooses a small one. This auto-adjustment makes using goma simpler
  9. and safer, and avoids errors that can cause slow goma builds or swap-storms
  10. on non-goma builds.
  11. """
  12. # [VPYTHON:BEGIN]
  13. # wheel: <
  14. # name: "infra/python/wheels/psutil/${vpython_platform}"
  15. # version: "version:5.6.2"
  16. # >
  17. # [VPYTHON:END]
  18. from __future__ import print_function
  19. import os
  20. import psutil
  21. import re
  22. import sys
  23. SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
  24. # The -t tools are incompatible with -j
  25. t_specified = False
  26. j_specified = False
  27. output_dir = '.'
  28. input_args = sys.argv
  29. # On Windows the autoninja.bat script passes along the arguments enclosed in
  30. # double quotes. This prevents multiple levels of parsing of the special '^'
  31. # characters needed when compiling a single file but means that this script gets
  32. # called with a single argument containing all of the actual arguments,
  33. # separated by spaces. When this case is detected we need to do argument
  34. # splitting ourselves. This means that arguments containing actual spaces are
  35. # not supported by autoninja, but that is not a real limitation.
  36. if (sys.platform.startswith('win') and len(sys.argv) == 2 and
  37. input_args[1].count(' ') > 0):
  38. input_args = sys.argv[:1] + sys.argv[1].split()
  39. # Ninja uses getopt_long, which allow to intermix non-option arguments.
  40. # To leave non supported parameters untouched, we do not use getopt.
  41. for index, arg in enumerate(input_args[1:]):
  42. if arg.startswith('-j'):
  43. j_specified = True
  44. if arg.startswith('-t'):
  45. t_specified = True
  46. if arg == '-C':
  47. # + 1 to get the next argument and +1 because we trimmed off input_args[0]
  48. output_dir = input_args[index + 2]
  49. elif arg.startswith('-C'):
  50. # Support -Cout/Default
  51. output_dir = arg[2:]
  52. use_goma = False
  53. use_jumbo_build = False
  54. # Attempt to auto-detect goma usage. We support gn-based builds, where we
  55. # look for args.gn in the build tree, and cmake-based builds where we look for
  56. # rules.ninja.
  57. if os.path.exists(os.path.join(output_dir, 'args.gn')):
  58. with open(os.path.join(output_dir, 'args.gn')) as file_handle:
  59. for line in file_handle:
  60. # This regex pattern copied from create_installer_archive.py
  61. if re.match(r'^\s*use_goma\s*=\s*true(\s*$|\s*#.*$)', line):
  62. use_goma = True
  63. continue
  64. match_use_jumbo_build = re.match(
  65. r'^\s*use_jumbo_build\s*=\s*true(\s*$|\s*#.*$)', line)
  66. if match_use_jumbo_build:
  67. use_jumbo_build = True
  68. continue
  69. elif os.path.exists(os.path.join(output_dir, 'rules.ninja')):
  70. with open(os.path.join(output_dir, 'rules.ninja')) as file_handle:
  71. for line in file_handle:
  72. if re.match(r'^\s*command\s*=\s*\S+gomacc', line):
  73. use_goma = True
  74. break
  75. # If GOMA_DISABLED is set to "true", "t", "yes", "y", or "1" (case-insensitive)
  76. # then gomacc will use the local compiler instead of doing a goma compile. This
  77. # is convenient if you want to briefly disable goma. It avoids having to rebuild
  78. # the world when transitioning between goma/non-goma builds. However, it is not
  79. # as fast as doing a "normal" non-goma build because an extra process is created
  80. # for each compile step. Checking this environment variable ensures that
  81. # autoninja uses an appropriate -j value in this situation.
  82. goma_disabled_env = os.environ.get('GOMA_DISABLED', '0').lower()
  83. if goma_disabled_env in ['true', 't', 'yes', 'y', '1']:
  84. use_goma = False
  85. # Specify ninja.exe on Windows so that ninja.bat can call autoninja and not
  86. # be called back.
  87. ninja_exe = 'ninja.exe' if sys.platform.startswith('win') else 'ninja'
  88. ninja_exe_path = os.path.join(SCRIPT_DIR, ninja_exe)
  89. # Use absolute path for ninja path,
  90. # or fail to execute ninja if depot_tools is not in PATH.
  91. args = [ninja_exe_path] + input_args[1:]
  92. num_cores = psutil.cpu_count()
  93. if not j_specified and not t_specified:
  94. if use_goma:
  95. args.append('-j')
  96. core_multiplier = int(os.environ.get('NINJA_CORE_MULTIPLIER', '40'))
  97. j_value = num_cores * core_multiplier
  98. if sys.platform.startswith('win'):
  99. # On windows, j value higher than 1000 does not improve build performance.
  100. j_value = min(j_value, 1000)
  101. elif sys.platform == 'darwin':
  102. # On Mac, j value higher than 500 causes 'Too many open files' error
  103. # (crbug.com/936864).
  104. j_value = min(j_value, 500)
  105. args.append('%d' % j_value)
  106. else:
  107. j_value = num_cores
  108. # Ninja defaults to |num_cores + 2|
  109. j_value += int(os.environ.get('NINJA_CORE_ADDITION', '2'))
  110. if use_jumbo_build:
  111. # Compiling a jumbo .o can easily use 1-2GB of memory. Leaving 2GB per
  112. # process avoids memory swap/compression storms when also considering
  113. # already in-use memory.
  114. physical_ram = psutil.virtual_memory().total
  115. GB = 1024 * 1024 * 1024
  116. j_value = min(j_value, physical_ram / (2 * GB))
  117. args.append('-j')
  118. args.append('%d' % j_value)
  119. # On Windows, fully quote the path so that the command processor doesn't think
  120. # the whole output is the command.
  121. # On Linux and Mac, if people put depot_tools in directories with ' ',
  122. # shell would misunderstand ' ' as a path separation.
  123. # TODO(yyanagisawa): provide proper quating for Windows.
  124. # see https://cs.chromium.org/chromium/src/tools/mb/mb.py
  125. for i in range(len(args)):
  126. if (i == 0 and sys.platform.startswith('win')) or ' ' in args[i]:
  127. args[i] = '"%s"' % args[i].replace('"', '\\"')
  128. if os.environ.get('NINJA_SUMMARIZE_BUILD', '0') == '1':
  129. args += ['-d', 'stats']
  130. print(' '.join(args))