blob: 7097857a7afa9811b204836693c8760d3f87548a [file] [log] [blame]
Edward Lemur32e3d1e2018-07-12 00:54:05 +00001#!/usr/bin/env python
2# Copyright (c) 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
Edward Lemurc87d45b2018-07-26 17:43:11 +00006from __future__ import print_function
7
Edward Lemur03d6d112018-10-23 15:17:36 +00008import re
Edward Lesmes1e59a242021-04-30 18:38:25 +00009import os
Edward Lemur32e3d1e2018-07-12 00:54:05 +000010import scm
11import subprocess2
12import sys
Raul Tambreb946b232019-03-26 14:48:46 +000013
14try:
15 import urlparse
16except ImportError: # For Py3 compatibility
17 import urllib.parse as urlparse
Edward Lemur32e3d1e2018-07-12 00:54:05 +000018
Edward Lemur32e3d1e2018-07-12 00:54:05 +000019
Edward Lemur48836262018-10-18 02:08:06 +000020# Current version of metrics recording.
21# When we add new metrics, the version number will be increased, we display the
22# user what has changed, and ask the user to agree again.
Edward Lesmes1e59a242021-04-30 18:38:25 +000023CURRENT_VERSION = 2
Edward Lemur48836262018-10-18 02:08:06 +000024
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000025APP_URL = 'https://cit-cli-metrics.appspot.com'
26
Edward Lesmes9c349062021-05-06 20:02:39 +000027REPORT_BUILD = os.getenv('DEPOT_TOOLS_REPORT_BUILD')
Edward Lesmes09f358b2021-06-22 22:31:52 +000028COLLECT_METRICS = (
29 os.getenv('DEPOT_TOOLS_COLLECT_METRICS') != '0'
30 and os.getenv('DEPOT_TOOLS_METRICS') != '0')
Edward Lesmes1e59a242021-04-30 18:38:25 +000031
Edward Lesmesc8f63d32021-06-02 23:51:53 +000032SYNC_STATUS_SUCCESS = 'SYNC_STATUS_SUCCESS'
33SYNC_STATUS_FAILURE = 'SYNC_STATUS_FAILURE'
34
Edward Lesmes1e59a242021-04-30 18:38:25 +000035
Samuel Huang98a7e802019-02-12 15:32:22 +000036def get_notice_countdown_header(countdown):
37 if countdown == 0:
38 yield ' METRICS COLLECTION IS TAKING PLACE'
39 else:
40 yield ' METRICS COLLECTION WILL START IN %d EXECUTIONS' % countdown
Edward Lemur32e3d1e2018-07-12 00:54:05 +000041
Samuel Huang98a7e802019-02-12 15:32:22 +000042def get_notice_version_change_header():
43 yield ' WE ARE COLLECTING ADDITIONAL METRICS'
44 yield ''
45 yield ' Please review the changes and opt-in again.'
46
47def get_notice_footer():
48 yield 'To suppress this message opt in or out using:'
49 yield '$ gclient metrics [--opt-in] [--opt-out]'
50 yield 'For more information please see metrics.README.md'
51 yield 'in your depot_tools checkout or visit'
52 yield 'https://goo.gl/yNpRDV.'
53
54def get_change_notice(version):
55 if version == 0:
Edward Lesmes1e59a242021-04-30 18:38:25 +000056 return [] # No changes for version 0
Samuel Huang98a7e802019-02-12 15:32:22 +000057 elif version == 1:
Edward Lesmes1e59a242021-04-30 18:38:25 +000058 return [
59 'We want to collect the Git version.',
60 'We want to collect information about the HTTP',
61 'requests that depot_tools makes, and the git and',
62 'cipd commands it executes.',
63 '',
64 'We only collect known strings to make sure we',
65 'don\'t record PII.',
66 ]
67 elif version == 2:
68 return [
69 'We will start collecting metrics from bots.',
70 'There are no changes for developers.',
71 'If the DEPOT_TOOLS_REPORT_BUILD environment variable is set,',
72 'we will report information about the current build',
73 '(e.g. buildbucket project, bucket, builder and build id),',
74 'and authenticate to the metrics collection server.',
75 'This information will only be recorded for requests',
76 'authenticated as bot service accounts.',
77 ]
Edward Lemur48836262018-10-18 02:08:06 +000078
79
Edward Lemur40764b02018-07-20 18:50:29 +000080KNOWN_PROJECT_URLS = {
81 'https://chrome-internal.googlesource.com/chrome/ios_internal',
82 'https://chrome-internal.googlesource.com/infra/infra_internal',
83 'https://chromium.googlesource.com/breakpad/breakpad',
84 'https://chromium.googlesource.com/chromium/src',
85 'https://chromium.googlesource.com/chromium/tools/depot_tools',
86 'https://chromium.googlesource.com/crashpad/crashpad',
87 'https://chromium.googlesource.com/external/gyp',
88 'https://chromium.googlesource.com/external/naclports',
89 'https://chromium.googlesource.com/infra/goma/client',
90 'https://chromium.googlesource.com/infra/infra',
91 'https://chromium.googlesource.com/native_client/',
92 'https://chromium.googlesource.com/syzygy',
93 'https://chromium.googlesource.com/v8/v8',
94 'https://dart.googlesource.com/sdk',
95 'https://pdfium.googlesource.com/pdfium',
96 'https://skia.googlesource.com/buildbot',
97 'https://skia.googlesource.com/skia',
98 'https://webrtc.googlesource.com/src',
99}
100
Edward Lemur03d6d112018-10-23 15:17:36 +0000101KNOWN_HTTP_HOSTS = {
102 'chrome-internal-review.googlesource.com',
103 'chromium-review.googlesource.com',
104 'dart-review.googlesource.com',
105 'eu1-mirror-chromium-review.googlesource.com',
106 'pdfium-review.googlesource.com',
107 'skia-review.googlesource.com',
108 'us1-mirror-chromium-review.googlesource.com',
109 'us2-mirror-chromium-review.googlesource.com',
110 'us3-mirror-chromium-review.googlesource.com',
111 'webrtc-review.googlesource.com',
112}
113
114KNOWN_HTTP_METHODS = {
115 'DELETE',
116 'GET',
117 'PATCH',
118 'POST',
119 'PUT',
120}
121
122KNOWN_HTTP_PATHS = {
123 'accounts':
124 re.compile(r'(/a)?/accounts/.*'),
125 'changes':
126 re.compile(r'(/a)?/changes/([^/]+)?$'),
127 'changes/abandon':
128 re.compile(r'(/a)?/changes/.*/abandon'),
129 'changes/comments':
130 re.compile(r'(/a)?/changes/.*/comments'),
131 'changes/detail':
132 re.compile(r'(/a)?/changes/.*/detail'),
133 'changes/edit':
134 re.compile(r'(/a)?/changes/.*/edit'),
135 'changes/message':
136 re.compile(r'(/a)?/changes/.*/message'),
137 'changes/restore':
138 re.compile(r'(/a)?/changes/.*/restore'),
139 'changes/reviewers':
140 re.compile(r'(/a)?/changes/.*/reviewers/.*'),
141 'changes/revisions/commit':
142 re.compile(r'(/a)?/changes/.*/revisions/.*/commit'),
143 'changes/revisions/review':
144 re.compile(r'(/a)?/changes/.*/revisions/.*/review'),
145 'changes/submit':
146 re.compile(r'(/a)?/changes/.*/submit'),
147 'projects/branches':
148 re.compile(r'(/a)?/projects/.*/branches/.*'),
149}
150
151KNOWN_HTTP_ARGS = {
152 'ALL_REVISIONS',
153 'CURRENT_COMMIT',
154 'CURRENT_REVISION',
155 'DETAILED_ACCOUNTS',
156 'LABELS',
157}
158
Edward Lemur861640f2018-10-31 19:45:31 +0000159GIT_VERSION_RE = re.compile(
160 r'git version (\d)\.(\d{0,2})\.(\d{0,2})'
161)
162
Edward Lemurfec80c42018-11-01 23:14:14 +0000163KNOWN_SUBCOMMAND_ARGS = {
164 'cc',
165 'hashtag',
166 'l=Auto-Submit+1',
Edward Lemur687ca902018-12-05 02:30:30 +0000167 'l=Code-Review+1',
168 'l=Code-Review+2',
Edward Lemurfec80c42018-11-01 23:14:14 +0000169 'l=Commit-Queue+1',
170 'l=Commit-Queue+2',
171 'label',
172 'm',
173 'notify=ALL',
174 'notify=NONE',
175 'private',
176 'r',
177 'ready',
178 'topic',
179 'wip'
180}
181
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000182
183def get_python_version():
184 """Return the python version in the major.minor.micro format."""
185 return '{v.major}.{v.minor}.{v.micro}'.format(v=sys.version_info)
186
187
Edward Lemur861640f2018-10-31 19:45:31 +0000188def get_git_version():
189 """Return the Git version in the major.minor.micro format."""
190 p = subprocess2.Popen(
191 ['git', '--version'],
192 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
193 stdout, _ = p.communicate()
Edward Lemur73065b22019-07-22 20:12:01 +0000194 match = GIT_VERSION_RE.match(stdout.decode('utf-8'))
Edward Lemur861640f2018-10-31 19:45:31 +0000195 if not match:
196 return None
197 return '%s.%s.%s' % match.groups()
198
199
Edward Lesmes1e59a242021-04-30 18:38:25 +0000200def get_bot_metrics():
Edward Lesmes9c349062021-05-06 20:02:39 +0000201 try:
202 project, bucket, builder, build = REPORT_BUILD.split('/')
203 return {
204 'build_id': int(build),
205 'builder': {
206 'project': project,
207 'bucket': bucket,
208 'builder': builder,
209 },
210 }
211 except (AttributeError, ValueError):
Edward Lesmes1e59a242021-04-30 18:38:25 +0000212 return None
Edward Lesmes1e59a242021-04-30 18:38:25 +0000213
214
215
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000216def return_code_from_exception(exception):
217 """Returns the exit code that would result of raising the exception."""
218 if exception is None:
219 return 0
220 if isinstance(exception[1], SystemExit):
221 return exception[1].code
222 return 1
223
224
Edward Lemurfec80c42018-11-01 23:14:14 +0000225def extract_known_subcommand_args(args):
226 """Extract the known arguments from the passed list of args."""
227 known_args = []
228 for arg in args:
229 if arg in KNOWN_SUBCOMMAND_ARGS:
230 known_args.append(arg)
231 else:
232 arg = arg.split('=')[0]
233 if arg in KNOWN_SUBCOMMAND_ARGS:
234 known_args.append(arg)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000235 return sorted(known_args)
Edward Lemurfec80c42018-11-01 23:14:14 +0000236
237
Edward Lemur03d6d112018-10-23 15:17:36 +0000238def extract_http_metrics(request_uri, method, status, response_time):
239 """Extract metrics from the request URI.
240
241 Extracts the host, path, and arguments from the request URI, and returns them
242 along with the method, status and response time.
243
244 The host, method, path and arguments must be in the KNOWN_HTTP_* constants
245 defined above.
246
247 Arguments are the values of the o= url parameter. In Gerrit, additional fields
248 can be obtained by adding o parameters, each option requires more database
249 lookups and slows down the query response time to the client, so we make an
250 effort to collect them.
251
252 The regex defined in KNOWN_HTTP_PATH_RES are checked against the path, and
253 those that match will be returned.
254 """
255 http_metrics = {
256 'status': status,
257 'response_time': response_time,
258 }
259
260 if method in KNOWN_HTTP_METHODS:
261 http_metrics['method'] = method
262
263 parsed_url = urlparse.urlparse(request_uri)
264
265 if parsed_url.netloc in KNOWN_HTTP_HOSTS:
266 http_metrics['host'] = parsed_url.netloc
267
Edward Lemur9217ff82019-07-16 23:14:24 +0000268 for name, path_re in KNOWN_HTTP_PATHS.items():
Edward Lemur03d6d112018-10-23 15:17:36 +0000269 if path_re.match(parsed_url.path):
270 http_metrics['path'] = name
271 break
272
273 parsed_query = urlparse.parse_qs(parsed_url.query)
274
275 # Collect o-parameters from the request.
276 args = [
277 arg for arg in parsed_query.get('o', [])
278 if arg in KNOWN_HTTP_ARGS
279 ]
280 if args:
281 http_metrics['arguments'] = args
282
283 return http_metrics
284
285
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000286def get_repo_timestamp(path_to_repo):
287 """Get an approximate timestamp for the upstream of |path_to_repo|.
288
289 Returns the top two bits of the timestamp of the HEAD for the upstream of the
290 branch path_to_repo is checked out at.
291 """
292 # Get the upstream for the current branch. If we're not in a branch, fallback
293 # to HEAD.
294 try:
Edward Lemur36974ad2019-02-21 23:29:47 +0000295 upstream = scm.GIT.GetUpstreamBranch(path_to_repo) or 'HEAD'
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000296 except subprocess2.CalledProcessError:
297 upstream = 'HEAD'
298
299 # Get the timestamp of the HEAD for the upstream of the current branch.
300 p = subprocess2.Popen(
301 ['git', '-C', path_to_repo, 'log', '-n1', upstream, '--format=%at'],
302 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
303 stdout, _ = p.communicate()
304
305 # If there was an error, give up.
306 if p.returncode != 0:
307 return None
308
Edward Lemur18df41e2019-04-26 00:42:04 +0000309 return stdout.strip()
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000310
Hans Wennborg24b5f902019-03-15 18:51:27 +0000311def print_boxed_text(out, min_width, lines):
312 [EW, NS, SE, SW, NE, NW] = list('=|++++')
Samuel Huang98a7e802019-02-12 15:32:22 +0000313 width = max(min_width, max(len(line) for line in lines))
314 out(SE + EW * (width + 2) + SW + '\n')
315 for line in lines:
Raul Tambreb946b232019-03-26 14:48:46 +0000316 out('%s %-*s %s\n' % (NS, width, line, NS))
Samuel Huang98a7e802019-02-12 15:32:22 +0000317 out(NE + EW * (width + 2) + NW + '\n')
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000318
319def print_notice(countdown):
320 """Print a notice to let the user know the status of metrics collection."""
Samuel Huang98a7e802019-02-12 15:32:22 +0000321 lines = list(get_notice_countdown_header(countdown))
322 lines.append('')
323 lines += list(get_notice_footer())
Hans Wennborg24b5f902019-03-15 18:51:27 +0000324 print_boxed_text(sys.stderr.write, 49, lines)
Edward Lemur48836262018-10-18 02:08:06 +0000325
326def print_version_change(config_version):
327 """Print a notice to let the user know we are collecting more metrics."""
Samuel Huang98a7e802019-02-12 15:32:22 +0000328 lines = list(get_notice_version_change_header())
Edward Lemur9217ff82019-07-16 23:14:24 +0000329 for version in range(config_version + 1, CURRENT_VERSION + 1):
Samuel Huang98a7e802019-02-12 15:32:22 +0000330 lines.append('')
Edward Lesmes1e59a242021-04-30 18:38:25 +0000331 lines += get_change_notice(version)
Hans Wennborg24b5f902019-03-15 18:51:27 +0000332 print_boxed_text(sys.stderr.write, 49, lines)