blob: 18ca64d3e5a08a07f95e21f6dcd12bb95e92e103 [file] [log] [blame]
Takuto Ikuta84e43fa2021-01-19 02:51:50 +00001#!/usr/bin/env python3
Takuto Ikuta9af233a2018-11-29 03:53:53 +00002# 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.
Takuto Ikuta9af233a2018-11-29 03:53:53 +00005"""
6This is script to upload ninja_log from googler.
7
8Server side implementation is in
9https://cs.chromium.org/chromium/infra/go/src/infra/appengine/chromium_build_stats/
10
11Uploaded ninjalog is stored in BigQuery table having following schema.
12https://cs.chromium.org/chromium/infra/go/src/infra/appengine/chromium_build_stats/ninjaproto/ninjalog.proto
13
14The log will be used to analyze user side build performance.
15"""
16
17import argparse
Takuto Ikuta9af233a2018-11-29 03:53:53 +000018import gzip
Takuto Ikuta84e43fa2021-01-19 02:51:50 +000019import io
Takuto Ikuta9af233a2018-11-29 03:53:53 +000020import json
21import logging
22import multiprocessing
23import os
24import platform
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000025import subprocess
Takuto Ikuta9af233a2018-11-29 03:53:53 +000026import sys
Takuto Ikuta36248fc2019-01-11 03:02:32 +000027import time
Takuto Ikuta9af233a2018-11-29 03:53:53 +000028
Takuto Ikuta84e43fa2021-01-19 02:51:50 +000029from third_party.six.moves.urllib import request
Takuto Ikuta9af233a2018-11-29 03:53:53 +000030
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000031# These build configs affect build performance.
32ALLOWLISTED_CONFIGS = ('symbol_level', 'use_goma', 'is_debug',
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000033 'is_component_build', 'enable_nacl', 'host_os',
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000034 'host_cpu', 'target_os', 'target_cpu',
35 'blink_symbol_level', 'is_java_debug',
36 'treat_warnings_as_errors', 'disable_android_lint',
37 'use_errorprone_java_compiler', 'incremental_install')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000038
Takuto Ikutac8069af2019-01-09 06:24:56 +000039
Takuto Ikutaa6573312022-01-20 00:24:57 +000040def IsGoogler():
41 """Check whether this user is Googler or not."""
42 p = subprocess.run('goma_auth info',
43 capture_output=True,
44 text=True,
45 shell=True)
46 if p.returncode != 0:
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000047 return False
Takuto Ikutaa6573312022-01-20 00:24:57 +000048 l = p.stdout.splitlines()[0]
49 # |l| will be like 'Login as <user>@google.com' for googler using goma.
50 return l.startswith('Login as ') and l.endswith('@google.com')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000051
Takuto Ikuta9af233a2018-11-29 03:53:53 +000052
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000053def ParseGNArgs(gn_args):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000054 """Parse gn_args as json and return config dictionary."""
55 configs = json.loads(gn_args)
56 build_configs = {}
Takuto Ikutac8069af2019-01-09 06:24:56 +000057
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000058 for config in configs:
59 key = config["name"]
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000060 if key not in ALLOWLISTED_CONFIGS:
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000061 continue
62 if 'current' in config:
63 build_configs[key] = config['current']['value']
64 else:
65 build_configs[key] = config['default']['value']
Takuto Ikutac8069af2019-01-09 06:24:56 +000066
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000067 return build_configs
68
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000069
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000070def GetBuildTargetFromCommandLine(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000071 """Get build targets from commandline."""
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000072
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000073 # Skip argv0.
74 idx = 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000075
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000076 # Skipping all args that involve these flags, and taking all remaining args
77 # as targets.
78 onearg_flags = ('-C', '-f', '-j', '-k', '-l', '-d', '-t', '-w')
79 zeroarg_flags = ('--version', '-n', '-v')
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000080
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000081 targets = []
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000082
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000083 while idx < len(cmdline):
84 if cmdline[idx] in onearg_flags:
85 idx += 2
86 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000087
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000088 if (cmdline[idx][:2] in onearg_flags or cmdline[idx] in zeroarg_flags):
89 idx += 1
90 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000091
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000092 targets.append(cmdline[idx])
93 idx += 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000094
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000095 return targets
96
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000097
Takuto Ikutac8069af2019-01-09 06:24:56 +000098def GetJflag(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000099 """Parse cmdline to get flag value for -j"""
Takuto Ikutac8069af2019-01-09 06:24:56 +0000100
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000101 for i in range(len(cmdline)):
102 if (cmdline[i] == '-j' and i + 1 < len(cmdline)
103 and cmdline[i + 1].isdigit()):
104 return int(cmdline[i + 1])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000105
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000106 if (cmdline[i].startswith('-j') and cmdline[i][len('-j'):].isdigit()):
107 return int(cmdline[i][len('-j'):])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000108
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000109
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000110def GetMetadata(cmdline, ninjalog):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000111 """Get metadata for uploaded ninjalog.
Takuto Ikutac8069af2019-01-09 06:24:56 +0000112
113 Returned metadata has schema defined in
114 https://cs.chromium.org?q="type+Metadata+struct+%7B"+file:%5Einfra/go/src/infra/appengine/chromium_build_stats/ninjalog/
115
116 TODO(tikuta): Collect GOMA_* env var.
117 """
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000118
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000119 build_dir = os.path.dirname(ninjalog)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000120
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000121 build_configs = {}
122
123 try:
124 args = ['gn', 'args', build_dir, '--list', '--short', '--json']
125 if sys.platform == 'win32':
126 # gn in PATH is bat file in windows environment (except cygwin).
127 args = ['cmd', '/c'] + args
128
129 gn_args = subprocess.check_output(args)
130 build_configs = ParseGNArgs(gn_args)
131 except subprocess.CalledProcessError as e:
132 logging.error("Failed to call gn %s", e)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000133 build_configs = {}
134
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000135 # Stringify config.
136 for k in build_configs:
137 build_configs[k] = str(build_configs[k])
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000138
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000139 metadata = {
140 'platform': platform.system(),
141 'cpu_core': multiprocessing.cpu_count(),
142 'build_configs': build_configs,
143 'targets': GetBuildTargetFromCommandLine(cmdline),
144 }
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000145
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000146 jflag = GetJflag(cmdline)
147 if jflag is not None:
148 metadata['jobs'] = jflag
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000149
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000150 return metadata
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000151
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000152
153def GetNinjalog(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000154 """GetNinjalog returns the path to ninjalog from cmdline."""
155 # ninjalog is in current working directory by default.
156 ninjalog_dir = '.'
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000157
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000158 i = 0
159 while i < len(cmdline):
160 cmd = cmdline[i]
161 i += 1
162 if cmd == '-C' and i < len(cmdline):
163 ninjalog_dir = cmdline[i]
164 i += 1
165 continue
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000166
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000167 if cmd.startswith('-C') and len(cmd) > len('-C'):
168 ninjalog_dir = cmd[len('-C'):]
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000169
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000170 return os.path.join(ninjalog_dir, '.ninja_log')
171
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000172
173def main():
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000174 parser = argparse.ArgumentParser()
175 parser.add_argument('--server',
176 default='chromium-build-stats.appspot.com',
177 help='server to upload ninjalog file.')
178 parser.add_argument('--ninjalog', help='ninjalog file to upload.')
179 parser.add_argument('--verbose',
180 action='store_true',
181 help='Enable verbose logging.')
182 parser.add_argument('--cmdline',
183 required=True,
184 nargs=argparse.REMAINDER,
185 help='command line args passed to ninja.')
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000186
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000187 args = parser.parse_args()
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000188
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000189 if args.verbose:
190 logging.basicConfig(level=logging.INFO)
191 else:
192 # Disable logging.
193 logging.disable(logging.CRITICAL)
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000194
Takuto Ikutaa6573312022-01-20 00:24:57 +0000195 if not IsGoogler():
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000196 return 0
197
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000198 ninjalog = args.ninjalog or GetNinjalog(args.cmdline)
199 if not os.path.isfile(ninjalog):
Gavin Make6a62332020-12-04 21:57:10 +0000200 logging.warning("ninjalog is not found in %s", ninjalog)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000201 return 1
202
203 # We assume that each ninja invocation interval takes at least 2 seconds.
204 # This is not to have duplicate entry in server when current build is no-op.
205 if os.stat(ninjalog).st_mtime < time.time() - 2:
206 logging.info("ninjalog is not updated recently %s", ninjalog)
207 return 0
208
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000209 output = io.BytesIO()
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000210
211 with open(ninjalog) as f:
212 with gzip.GzipFile(fileobj=output, mode='wb') as g:
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000213 g.write(f.read().encode())
214 g.write(b'# end of ninja log\n')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000215
216 metadata = GetMetadata(args.cmdline, ninjalog)
217 logging.info('send metadata: %s', json.dumps(metadata))
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000218 g.write(json.dumps(metadata).encode())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000219
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000220 resp = request.urlopen(
221 request.Request('https://' + args.server + '/upload_ninja_log/',
222 data=output.getvalue(),
223 headers={'Content-Encoding': 'gzip'}))
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000224
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000225 if resp.status != 200:
226 logging.warning("unexpected status code for response: %s", resp.status)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000227 return 1
228
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000229 logging.info('response header: %s', resp.headers)
230 logging.info('response content: %s', resp.read())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000231 return 0
232
233
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000234if __name__ == '__main__':
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000235 sys.exit(main())