ninjalog_uploader.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/env python3
  2. # Copyright 2018 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 is script to upload ninja_log from googler.
  7. Server side implementation is in
  8. https://cs.chromium.org/chromium/infra/go/src/infra/appengine/chromium_build_stats/
  9. Uploaded ninjalog is stored in BigQuery table having following schema.
  10. https://cs.chromium.org/chromium/infra/go/src/infra/appengine/chromium_build_stats/ninjaproto/ninjalog.proto
  11. The log will be used to analyze user side build performance.
  12. """
  13. import argparse
  14. import gzip
  15. import io
  16. import json
  17. import logging
  18. import multiprocessing
  19. import os
  20. import platform
  21. import subprocess
  22. import sys
  23. import time
  24. from third_party.six.moves.urllib import request
  25. # These build configs affect build performance.
  26. ALLOWLISTED_CONFIGS = ('symbol_level', 'use_goma', 'is_debug',
  27. 'is_component_build', 'enable_nacl', 'host_os',
  28. 'host_cpu', 'target_os', 'target_cpu',
  29. 'blink_symbol_level', 'is_java_debug',
  30. 'treat_warnings_as_errors', 'disable_android_lint',
  31. 'use_errorprone_java_compiler', 'incremental_install',
  32. 'android_static_analysis')
  33. def IsGoogler():
  34. """Check whether this user is Googler or not."""
  35. p = subprocess.run('goma_auth info',
  36. stdout=subprocess.PIPE,
  37. stderr=subprocess.PIPE,
  38. universal_newlines=True,
  39. shell=True)
  40. if p.returncode != 0:
  41. return False
  42. lines = p.stdout.splitlines()
  43. if len(lines) == 0:
  44. return False
  45. l = lines[0]
  46. # |l| will be like 'Login as <user>@google.com' for googler using goma.
  47. return l.startswith('Login as ') and l.endswith('@google.com')
  48. def ParseGNArgs(gn_args):
  49. """Parse gn_args as json and return config dictionary."""
  50. configs = json.loads(gn_args)
  51. build_configs = {}
  52. for config in configs:
  53. key = config["name"]
  54. if key not in ALLOWLISTED_CONFIGS:
  55. continue
  56. if 'current' in config:
  57. build_configs[key] = config['current']['value']
  58. else:
  59. build_configs[key] = config['default']['value']
  60. return build_configs
  61. def GetBuildTargetFromCommandLine(cmdline):
  62. """Get build targets from commandline."""
  63. # Skip argv0, argv1: ['/path/to/python3', '/path/to/depot_tools/ninja.py']
  64. idx = 2
  65. # Skipping all args that involve these flags, and taking all remaining args
  66. # as targets.
  67. onearg_flags = ('-C', '-d', '-f', '-j', '-k', '-l', '-p', '-t', '-w')
  68. zeroarg_flags = ('--version', '-n', '-v')
  69. targets = []
  70. while idx < len(cmdline):
  71. arg = cmdline[idx]
  72. if arg in onearg_flags:
  73. idx += 2
  74. continue
  75. if (arg[:2] in onearg_flags or arg in zeroarg_flags):
  76. idx += 1
  77. continue
  78. # A target doesn't start with '-'.
  79. if arg.startswith('-'):
  80. idx += 1
  81. continue
  82. # Avoid uploading absolute paths accidentally. e.g. b/270907050
  83. if os.path.isabs(arg):
  84. idx += 1
  85. continue
  86. targets.append(arg)
  87. idx += 1
  88. return targets
  89. def GetJflag(cmdline):
  90. """Parse cmdline to get flag value for -j"""
  91. for i in range(len(cmdline)):
  92. if (cmdline[i] == '-j' and i + 1 < len(cmdline)
  93. and cmdline[i + 1].isdigit()):
  94. return int(cmdline[i + 1])
  95. if (cmdline[i].startswith('-j') and cmdline[i][len('-j'):].isdigit()):
  96. return int(cmdline[i][len('-j'):])
  97. def GetMetadata(cmdline, ninjalog):
  98. """Get metadata for uploaded ninjalog.
  99. Returned metadata has schema defined in
  100. https://cs.chromium.org?q="type+Metadata+struct+%7B"+file:%5Einfra/go/src/infra/appengine/chromium_build_stats/ninjalog/
  101. TODO(tikuta): Collect GOMA_* env var.
  102. """
  103. build_dir = os.path.dirname(ninjalog)
  104. build_configs = {}
  105. try:
  106. args = ['gn', 'args', build_dir, '--list', '--short', '--json']
  107. if sys.platform == 'win32':
  108. # gn in PATH is bat file in windows environment (except cygwin).
  109. args = ['cmd', '/c'] + args
  110. gn_args = subprocess.check_output(args)
  111. build_configs = ParseGNArgs(gn_args)
  112. except subprocess.CalledProcessError as e:
  113. logging.error("Failed to call gn %s", e)
  114. build_configs = {}
  115. # Stringify config.
  116. for k in build_configs:
  117. build_configs[k] = str(build_configs[k])
  118. metadata = {
  119. 'platform': platform.system(),
  120. 'cpu_core': multiprocessing.cpu_count(),
  121. 'build_configs': build_configs,
  122. 'targets': GetBuildTargetFromCommandLine(cmdline),
  123. }
  124. jflag = GetJflag(cmdline)
  125. if jflag is not None:
  126. metadata['jobs'] = jflag
  127. return metadata
  128. def GetNinjalog(cmdline):
  129. """GetNinjalog returns the path to ninjalog from cmdline."""
  130. # ninjalog is in current working directory by default.
  131. ninjalog_dir = '.'
  132. i = 0
  133. while i < len(cmdline):
  134. cmd = cmdline[i]
  135. i += 1
  136. if cmd == '-C' and i < len(cmdline):
  137. ninjalog_dir = cmdline[i]
  138. i += 1
  139. continue
  140. if cmd.startswith('-C') and len(cmd) > len('-C'):
  141. ninjalog_dir = cmd[len('-C'):]
  142. return os.path.join(ninjalog_dir, '.ninja_log')
  143. def main():
  144. parser = argparse.ArgumentParser()
  145. parser.add_argument('--server',
  146. default='chromium-build-stats.appspot.com',
  147. help='server to upload ninjalog file.')
  148. parser.add_argument('--ninjalog', help='ninjalog file to upload.')
  149. parser.add_argument('--verbose',
  150. action='store_true',
  151. help='Enable verbose logging.')
  152. parser.add_argument('--cmdline',
  153. required=True,
  154. nargs=argparse.REMAINDER,
  155. help='command line args passed to ninja.')
  156. args = parser.parse_args()
  157. if args.verbose:
  158. logging.basicConfig(level=logging.INFO)
  159. else:
  160. # Disable logging.
  161. logging.disable(logging.CRITICAL)
  162. if not IsGoogler():
  163. return 0
  164. ninjalog = args.ninjalog or GetNinjalog(args.cmdline)
  165. if not os.path.isfile(ninjalog):
  166. logging.warning("ninjalog is not found in %s", ninjalog)
  167. return 1
  168. # We assume that each ninja invocation interval takes at least 2 seconds.
  169. # This is not to have duplicate entry in server when current build is no-op.
  170. if os.stat(ninjalog).st_mtime < time.time() - 2:
  171. logging.info("ninjalog is not updated recently %s", ninjalog)
  172. return 0
  173. output = io.BytesIO()
  174. with open(ninjalog) as f:
  175. with gzip.GzipFile(fileobj=output, mode='wb') as g:
  176. g.write(f.read().encode())
  177. g.write(b'# end of ninja log\n')
  178. metadata = GetMetadata(args.cmdline, ninjalog)
  179. logging.info('send metadata: %s', json.dumps(metadata))
  180. g.write(json.dumps(metadata).encode())
  181. resp = request.urlopen(
  182. request.Request('https://' + args.server + '/upload_ninja_log/',
  183. data=output.getvalue(),
  184. headers={'Content-Encoding': 'gzip'}))
  185. if resp.status != 200:
  186. logging.warning("unexpected status code for response: %s", resp.status)
  187. return 1
  188. logging.info('response header: %s', resp.headers)
  189. logging.info('response content: %s', resp.read())
  190. return 0
  191. if __name__ == '__main__':
  192. sys.exit(main())