blob: 3aa0239e63db4b45b3ce066390df86724456b9aa [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 Ikuta4bb3a7d2021-06-09 03:58:27 +000029from third_party.six.moves import http_client
Takuto Ikuta84e43fa2021-01-19 02:51:50 +000030from third_party.six.moves.urllib import error
31from third_party.six.moves.urllib import request
Takuto Ikuta9af233a2018-11-29 03:53:53 +000032
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000033# These build configs affect build performance.
34ALLOWLISTED_CONFIGS = ('symbol_level', 'use_goma', 'is_debug',
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000035 'is_component_build', 'enable_nacl', 'host_os',
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000036 'host_cpu', 'target_os', 'target_cpu',
37 'blink_symbol_level', 'is_java_debug',
38 'treat_warnings_as_errors', 'disable_android_lint',
39 'use_errorprone_java_compiler', 'incremental_install')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000040
Takuto Ikutac8069af2019-01-09 06:24:56 +000041
Takuto Ikuta9af233a2018-11-29 03:53:53 +000042def IsGoogler(server):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000043 """Check whether this script run inside corp network."""
44 try:
Takuto Ikuta84e43fa2021-01-19 02:51:50 +000045 resp = request.urlopen('https://' + server + '/should-upload')
46 return resp.read() == b'Success'
Takuto Ikuta4bb3a7d2021-06-09 03:58:27 +000047 except (error.URLError, http_client.RemoteDisconnected):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000048 return False
49
Takuto Ikuta9af233a2018-11-29 03:53:53 +000050
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000051def ParseGNArgs(gn_args):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000052 """Parse gn_args as json and return config dictionary."""
53 configs = json.loads(gn_args)
54 build_configs = {}
Takuto Ikutac8069af2019-01-09 06:24:56 +000055
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000056 for config in configs:
57 key = config["name"]
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000058 if key not in ALLOWLISTED_CONFIGS:
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000059 continue
60 if 'current' in config:
61 build_configs[key] = config['current']['value']
62 else:
63 build_configs[key] = config['default']['value']
Takuto Ikutac8069af2019-01-09 06:24:56 +000064
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000065 return build_configs
66
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000067
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000068def GetBuildTargetFromCommandLine(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000069 """Get build targets from commandline."""
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000070
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000071 # Skip argv0.
72 idx = 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000073
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000074 # Skipping all args that involve these flags, and taking all remaining args
75 # as targets.
76 onearg_flags = ('-C', '-f', '-j', '-k', '-l', '-d', '-t', '-w')
77 zeroarg_flags = ('--version', '-n', '-v')
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000078
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000079 targets = []
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000080
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000081 while idx < len(cmdline):
82 if cmdline[idx] in onearg_flags:
83 idx += 2
84 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000085
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000086 if (cmdline[idx][:2] in onearg_flags or cmdline[idx] in zeroarg_flags):
87 idx += 1
88 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000089
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000090 targets.append(cmdline[idx])
91 idx += 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000092
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000093 return targets
94
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000095
Takuto Ikutac8069af2019-01-09 06:24:56 +000096def GetJflag(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000097 """Parse cmdline to get flag value for -j"""
Takuto Ikutac8069af2019-01-09 06:24:56 +000098
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000099 for i in range(len(cmdline)):
100 if (cmdline[i] == '-j' and i + 1 < len(cmdline)
101 and cmdline[i + 1].isdigit()):
102 return int(cmdline[i + 1])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000103
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000104 if (cmdline[i].startswith('-j') and cmdline[i][len('-j'):].isdigit()):
105 return int(cmdline[i][len('-j'):])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000106
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000107
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000108def GetMetadata(cmdline, ninjalog):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000109 """Get metadata for uploaded ninjalog.
Takuto Ikutac8069af2019-01-09 06:24:56 +0000110
111 Returned metadata has schema defined in
112 https://cs.chromium.org?q="type+Metadata+struct+%7B"+file:%5Einfra/go/src/infra/appengine/chromium_build_stats/ninjalog/
113
114 TODO(tikuta): Collect GOMA_* env var.
115 """
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000116
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000117 build_dir = os.path.dirname(ninjalog)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000118
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000119 build_configs = {}
120
121 try:
122 args = ['gn', 'args', build_dir, '--list', '--short', '--json']
123 if sys.platform == 'win32':
124 # gn in PATH is bat file in windows environment (except cygwin).
125 args = ['cmd', '/c'] + args
126
127 gn_args = subprocess.check_output(args)
128 build_configs = ParseGNArgs(gn_args)
129 except subprocess.CalledProcessError as e:
130 logging.error("Failed to call gn %s", e)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000131 build_configs = {}
132
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000133 # Stringify config.
134 for k in build_configs:
135 build_configs[k] = str(build_configs[k])
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000136
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000137 metadata = {
138 'platform': platform.system(),
139 'cpu_core': multiprocessing.cpu_count(),
140 'build_configs': build_configs,
141 'targets': GetBuildTargetFromCommandLine(cmdline),
142 }
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000143
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000144 jflag = GetJflag(cmdline)
145 if jflag is not None:
146 metadata['jobs'] = jflag
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000147
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000148 return metadata
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000149
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000150
151def GetNinjalog(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000152 """GetNinjalog returns the path to ninjalog from cmdline."""
153 # ninjalog is in current working directory by default.
154 ninjalog_dir = '.'
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000155
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000156 i = 0
157 while i < len(cmdline):
158 cmd = cmdline[i]
159 i += 1
160 if cmd == '-C' and i < len(cmdline):
161 ninjalog_dir = cmdline[i]
162 i += 1
163 continue
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000164
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000165 if cmd.startswith('-C') and len(cmd) > len('-C'):
166 ninjalog_dir = cmd[len('-C'):]
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000167
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000168 return os.path.join(ninjalog_dir, '.ninja_log')
169
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000170
171def main():
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000172 parser = argparse.ArgumentParser()
173 parser.add_argument('--server',
174 default='chromium-build-stats.appspot.com',
175 help='server to upload ninjalog file.')
176 parser.add_argument('--ninjalog', help='ninjalog file to upload.')
177 parser.add_argument('--verbose',
178 action='store_true',
179 help='Enable verbose logging.')
180 parser.add_argument('--cmdline',
181 required=True,
182 nargs=argparse.REMAINDER,
183 help='command line args passed to ninja.')
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000184
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000185 args = parser.parse_args()
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000186
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000187 if args.verbose:
188 logging.basicConfig(level=logging.INFO)
189 else:
190 # Disable logging.
191 logging.disable(logging.CRITICAL)
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000192
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000193 if not IsGoogler(args.server):
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000194 return 0
195
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000196 ninjalog = args.ninjalog or GetNinjalog(args.cmdline)
197 if not os.path.isfile(ninjalog):
Gavin Make6a62332020-12-04 21:57:10 +0000198 logging.warning("ninjalog is not found in %s", ninjalog)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000199 return 1
200
201 # We assume that each ninja invocation interval takes at least 2 seconds.
202 # This is not to have duplicate entry in server when current build is no-op.
203 if os.stat(ninjalog).st_mtime < time.time() - 2:
204 logging.info("ninjalog is not updated recently %s", ninjalog)
205 return 0
206
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000207 output = io.BytesIO()
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000208
209 with open(ninjalog) as f:
210 with gzip.GzipFile(fileobj=output, mode='wb') as g:
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000211 g.write(f.read().encode())
212 g.write(b'# end of ninja log\n')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000213
214 metadata = GetMetadata(args.cmdline, ninjalog)
215 logging.info('send metadata: %s', json.dumps(metadata))
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000216 g.write(json.dumps(metadata).encode())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000217
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000218 resp = request.urlopen(
219 request.Request('https://' + args.server + '/upload_ninja_log/',
220 data=output.getvalue(),
221 headers={'Content-Encoding': 'gzip'}))
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000222
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000223 if resp.status != 200:
224 logging.warning("unexpected status code for response: %s", resp.status)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000225 return 1
226
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000227 logging.info('response header: %s', resp.headers)
228 logging.info('response content: %s', resp.read())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000229 return 0
230
231
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000232if __name__ == '__main__':
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000233 sys.exit(main())