blob: def28e8301962d35fbcb3bd09e31f15bef117776 [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',
Takuto Ikuta18a28442022-01-24 05:03:38 +000043 stdout=subprocess.PIPE,
Takuto Ikuta98cf9322022-02-01 00:47:31 +000044 stderr=subprocess.PIPE,
Takuto Ikuta18a28442022-01-24 05:03:38 +000045 universal_newlines=True,
Takuto Ikutaa6573312022-01-20 00:24:57 +000046 shell=True)
47 if p.returncode != 0:
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000048 return False
Takuto Ikuta3dc01722022-01-21 00:04:23 +000049 lines = p.stdout.splitlines()
50 if len(lines) == 0:
51 return False
52 l = lines[0]
Takuto Ikutaa6573312022-01-20 00:24:57 +000053 # |l| will be like 'Login as <user>@google.com' for googler using goma.
54 return l.startswith('Login as ') and l.endswith('@google.com')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000055
Takuto Ikuta9af233a2018-11-29 03:53:53 +000056
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000057def ParseGNArgs(gn_args):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000058 """Parse gn_args as json and return config dictionary."""
59 configs = json.loads(gn_args)
60 build_configs = {}
Takuto Ikutac8069af2019-01-09 06:24:56 +000061
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000062 for config in configs:
63 key = config["name"]
Victor Hugo Vianna Silva787f2f02021-11-11 03:27:28 +000064 if key not in ALLOWLISTED_CONFIGS:
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000065 continue
66 if 'current' in config:
67 build_configs[key] = config['current']['value']
68 else:
69 build_configs[key] = config['default']['value']
Takuto Ikutac8069af2019-01-09 06:24:56 +000070
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000071 return build_configs
72
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +000073
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000074def GetBuildTargetFromCommandLine(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000075 """Get build targets from commandline."""
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000076
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000077 # Skip argv0.
78 idx = 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000079
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000080 # Skipping all args that involve these flags, and taking all remaining args
81 # as targets.
82 onearg_flags = ('-C', '-f', '-j', '-k', '-l', '-d', '-t', '-w')
83 zeroarg_flags = ('--version', '-n', '-v')
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000084
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000085 targets = []
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000086
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000087 while idx < len(cmdline):
88 if cmdline[idx] in onearg_flags:
89 idx += 2
90 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000091
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000092 if (cmdline[idx][:2] in onearg_flags or cmdline[idx] in zeroarg_flags):
93 idx += 1
94 continue
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000095
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000096 targets.append(cmdline[idx])
97 idx += 1
Takuto Ikutacf56a4b2018-12-18 05:47:26 +000098
Takuto Ikutaa2e91db2020-06-09 11:21:59 +000099 return targets
100
Takuto Ikutacf56a4b2018-12-18 05:47:26 +0000101
Takuto Ikutac8069af2019-01-09 06:24:56 +0000102def GetJflag(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000103 """Parse cmdline to get flag value for -j"""
Takuto Ikutac8069af2019-01-09 06:24:56 +0000104
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000105 for i in range(len(cmdline)):
106 if (cmdline[i] == '-j' and i + 1 < len(cmdline)
107 and cmdline[i + 1].isdigit()):
108 return int(cmdline[i + 1])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000109
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000110 if (cmdline[i].startswith('-j') and cmdline[i][len('-j'):].isdigit()):
111 return int(cmdline[i][len('-j'):])
Takuto Ikutac8069af2019-01-09 06:24:56 +0000112
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000113
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000114def GetMetadata(cmdline, ninjalog):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000115 """Get metadata for uploaded ninjalog.
Takuto Ikutac8069af2019-01-09 06:24:56 +0000116
117 Returned metadata has schema defined in
118 https://cs.chromium.org?q="type+Metadata+struct+%7B"+file:%5Einfra/go/src/infra/appengine/chromium_build_stats/ninjalog/
119
120 TODO(tikuta): Collect GOMA_* env var.
121 """
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000122
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000123 build_dir = os.path.dirname(ninjalog)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000124
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000125 build_configs = {}
126
127 try:
128 args = ['gn', 'args', build_dir, '--list', '--short', '--json']
129 if sys.platform == 'win32':
130 # gn in PATH is bat file in windows environment (except cygwin).
131 args = ['cmd', '/c'] + args
132
133 gn_args = subprocess.check_output(args)
134 build_configs = ParseGNArgs(gn_args)
135 except subprocess.CalledProcessError as e:
136 logging.error("Failed to call gn %s", e)
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000137 build_configs = {}
138
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000139 # Stringify config.
140 for k in build_configs:
141 build_configs[k] = str(build_configs[k])
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000142
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000143 metadata = {
144 'platform': platform.system(),
145 'cpu_core': multiprocessing.cpu_count(),
146 'build_configs': build_configs,
147 'targets': GetBuildTargetFromCommandLine(cmdline),
148 }
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000149
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000150 jflag = GetJflag(cmdline)
151 if jflag is not None:
152 metadata['jobs'] = jflag
Takuto Ikuta96fdf7c2018-12-03 09:18:39 +0000153
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000154 return metadata
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000155
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000156
157def GetNinjalog(cmdline):
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000158 """GetNinjalog returns the path to ninjalog from cmdline."""
159 # ninjalog is in current working directory by default.
160 ninjalog_dir = '.'
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000161
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000162 i = 0
163 while i < len(cmdline):
164 cmd = cmdline[i]
165 i += 1
166 if cmd == '-C' and i < len(cmdline):
167 ninjalog_dir = cmdline[i]
168 i += 1
169 continue
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000170
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000171 if cmd.startswith('-C') and len(cmd) > len('-C'):
172 ninjalog_dir = cmd[len('-C'):]
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000173
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000174 return os.path.join(ninjalog_dir, '.ninja_log')
175
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000176
177def main():
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000178 parser = argparse.ArgumentParser()
179 parser.add_argument('--server',
180 default='chromium-build-stats.appspot.com',
181 help='server to upload ninjalog file.')
182 parser.add_argument('--ninjalog', help='ninjalog file to upload.')
183 parser.add_argument('--verbose',
184 action='store_true',
185 help='Enable verbose logging.')
186 parser.add_argument('--cmdline',
187 required=True,
188 nargs=argparse.REMAINDER,
189 help='command line args passed to ninja.')
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000190
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000191 args = parser.parse_args()
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000192
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000193 if args.verbose:
194 logging.basicConfig(level=logging.INFO)
195 else:
196 # Disable logging.
197 logging.disable(logging.CRITICAL)
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000198
Takuto Ikutaa6573312022-01-20 00:24:57 +0000199 if not IsGoogler():
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000200 return 0
201
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000202 ninjalog = args.ninjalog or GetNinjalog(args.cmdline)
203 if not os.path.isfile(ninjalog):
Gavin Make6a62332020-12-04 21:57:10 +0000204 logging.warning("ninjalog is not found in %s", ninjalog)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000205 return 1
206
207 # We assume that each ninja invocation interval takes at least 2 seconds.
208 # This is not to have duplicate entry in server when current build is no-op.
209 if os.stat(ninjalog).st_mtime < time.time() - 2:
210 logging.info("ninjalog is not updated recently %s", ninjalog)
211 return 0
212
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000213 output = io.BytesIO()
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000214
215 with open(ninjalog) as f:
216 with gzip.GzipFile(fileobj=output, mode='wb') as g:
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000217 g.write(f.read().encode())
218 g.write(b'# end of ninja log\n')
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000219
220 metadata = GetMetadata(args.cmdline, ninjalog)
221 logging.info('send metadata: %s', json.dumps(metadata))
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000222 g.write(json.dumps(metadata).encode())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000223
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000224 resp = request.urlopen(
225 request.Request('https://' + args.server + '/upload_ninja_log/',
226 data=output.getvalue(),
227 headers={'Content-Encoding': 'gzip'}))
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000228
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000229 if resp.status != 200:
230 logging.warning("unexpected status code for response: %s", resp.status)
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000231 return 1
232
Takuto Ikuta84e43fa2021-01-19 02:51:50 +0000233 logging.info('response header: %s', resp.headers)
234 logging.info('response content: %s', resp.read())
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000235 return 0
236
237
Takuto Ikuta9af233a2018-11-29 03:53:53 +0000238if __name__ == '__main__':
Takuto Ikutaa2e91db2020-06-09 11:21:59 +0000239 sys.exit(main())