blob: 2235a7fd7a73981f7bd3c450fb48958aacdb5385 [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 Lemur32e3d1e2018-07-12 00:54:05 +00009import scm
10import subprocess2
11import sys
Raul Tambreb946b232019-03-26 14:48:46 +000012
13try:
14 import urlparse
15except ImportError: # For Py3 compatibility
16 import urllib.parse as urlparse
Edward Lemur32e3d1e2018-07-12 00:54:05 +000017
Edward Lemur32e3d1e2018-07-12 00:54:05 +000018
Edward Lemur48836262018-10-18 02:08:06 +000019# Current version of metrics recording.
20# When we add new metrics, the version number will be increased, we display the
21# user what has changed, and ask the user to agree again.
Edward Lemur5a9ff432018-10-30 19:00:22 +000022CURRENT_VERSION = 1
Edward Lemur48836262018-10-18 02:08:06 +000023
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000024APP_URL = 'https://cit-cli-metrics.appspot.com'
25
Samuel Huang98a7e802019-02-12 15:32:22 +000026def get_notice_countdown_header(countdown):
27 if countdown == 0:
28 yield ' METRICS COLLECTION IS TAKING PLACE'
29 else:
30 yield ' METRICS COLLECTION WILL START IN %d EXECUTIONS' % countdown
Edward Lemur32e3d1e2018-07-12 00:54:05 +000031
Samuel Huang98a7e802019-02-12 15:32:22 +000032def get_notice_version_change_header():
33 yield ' WE ARE COLLECTING ADDITIONAL METRICS'
34 yield ''
35 yield ' Please review the changes and opt-in again.'
36
37def get_notice_footer():
38 yield 'To suppress this message opt in or out using:'
39 yield '$ gclient metrics [--opt-in] [--opt-out]'
40 yield 'For more information please see metrics.README.md'
41 yield 'in your depot_tools checkout or visit'
42 yield 'https://goo.gl/yNpRDV.'
43
44def get_change_notice(version):
45 if version == 0:
46 pass # No changes for version 0
47 elif version == 1:
48 yield 'We want to collect the Git version.'
49 yield 'We want to collect information about the HTTP'
50 yield 'requests that depot_tools makes, and the git and'
51 yield 'cipd commands it executes.'
52 yield ''
53 yield 'We only collect known strings to make sure we'
54 yield 'don\'t record PII.'
Edward Lemur48836262018-10-18 02:08:06 +000055
56
Edward Lemur40764b02018-07-20 18:50:29 +000057KNOWN_PROJECT_URLS = {
58 'https://chrome-internal.googlesource.com/chrome/ios_internal',
59 'https://chrome-internal.googlesource.com/infra/infra_internal',
60 'https://chromium.googlesource.com/breakpad/breakpad',
61 'https://chromium.googlesource.com/chromium/src',
62 'https://chromium.googlesource.com/chromium/tools/depot_tools',
63 'https://chromium.googlesource.com/crashpad/crashpad',
64 'https://chromium.googlesource.com/external/gyp',
65 'https://chromium.googlesource.com/external/naclports',
66 'https://chromium.googlesource.com/infra/goma/client',
67 'https://chromium.googlesource.com/infra/infra',
68 'https://chromium.googlesource.com/native_client/',
69 'https://chromium.googlesource.com/syzygy',
70 'https://chromium.googlesource.com/v8/v8',
71 'https://dart.googlesource.com/sdk',
72 'https://pdfium.googlesource.com/pdfium',
73 'https://skia.googlesource.com/buildbot',
74 'https://skia.googlesource.com/skia',
75 'https://webrtc.googlesource.com/src',
76}
77
Edward Lemur03d6d112018-10-23 15:17:36 +000078KNOWN_HTTP_HOSTS = {
79 'chrome-internal-review.googlesource.com',
80 'chromium-review.googlesource.com',
81 'dart-review.googlesource.com',
82 'eu1-mirror-chromium-review.googlesource.com',
83 'pdfium-review.googlesource.com',
84 'skia-review.googlesource.com',
85 'us1-mirror-chromium-review.googlesource.com',
86 'us2-mirror-chromium-review.googlesource.com',
87 'us3-mirror-chromium-review.googlesource.com',
88 'webrtc-review.googlesource.com',
89}
90
91KNOWN_HTTP_METHODS = {
92 'DELETE',
93 'GET',
94 'PATCH',
95 'POST',
96 'PUT',
97}
98
99KNOWN_HTTP_PATHS = {
100 'accounts':
101 re.compile(r'(/a)?/accounts/.*'),
102 'changes':
103 re.compile(r'(/a)?/changes/([^/]+)?$'),
104 'changes/abandon':
105 re.compile(r'(/a)?/changes/.*/abandon'),
106 'changes/comments':
107 re.compile(r'(/a)?/changes/.*/comments'),
108 'changes/detail':
109 re.compile(r'(/a)?/changes/.*/detail'),
110 'changes/edit':
111 re.compile(r'(/a)?/changes/.*/edit'),
112 'changes/message':
113 re.compile(r'(/a)?/changes/.*/message'),
114 'changes/restore':
115 re.compile(r'(/a)?/changes/.*/restore'),
116 'changes/reviewers':
117 re.compile(r'(/a)?/changes/.*/reviewers/.*'),
118 'changes/revisions/commit':
119 re.compile(r'(/a)?/changes/.*/revisions/.*/commit'),
120 'changes/revisions/review':
121 re.compile(r'(/a)?/changes/.*/revisions/.*/review'),
122 'changes/submit':
123 re.compile(r'(/a)?/changes/.*/submit'),
124 'projects/branches':
125 re.compile(r'(/a)?/projects/.*/branches/.*'),
126}
127
128KNOWN_HTTP_ARGS = {
129 'ALL_REVISIONS',
130 'CURRENT_COMMIT',
131 'CURRENT_REVISION',
132 'DETAILED_ACCOUNTS',
133 'LABELS',
134}
135
Edward Lemur861640f2018-10-31 19:45:31 +0000136GIT_VERSION_RE = re.compile(
137 r'git version (\d)\.(\d{0,2})\.(\d{0,2})'
138)
139
Edward Lemurfec80c42018-11-01 23:14:14 +0000140KNOWN_SUBCOMMAND_ARGS = {
141 'cc',
142 'hashtag',
143 'l=Auto-Submit+1',
Edward Lemur687ca902018-12-05 02:30:30 +0000144 'l=Code-Review+1',
145 'l=Code-Review+2',
Edward Lemurfec80c42018-11-01 23:14:14 +0000146 'l=Commit-Queue+1',
147 'l=Commit-Queue+2',
148 'label',
149 'm',
150 'notify=ALL',
151 'notify=NONE',
152 'private',
153 'r',
154 'ready',
155 'topic',
156 'wip'
157}
158
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000159
160def get_python_version():
161 """Return the python version in the major.minor.micro format."""
162 return '{v.major}.{v.minor}.{v.micro}'.format(v=sys.version_info)
163
164
Edward Lemur861640f2018-10-31 19:45:31 +0000165def get_git_version():
166 """Return the Git version in the major.minor.micro format."""
167 p = subprocess2.Popen(
168 ['git', '--version'],
169 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
170 stdout, _ = p.communicate()
171 match = GIT_VERSION_RE.match(stdout)
172 if not match:
173 return None
174 return '%s.%s.%s' % match.groups()
175
176
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000177def return_code_from_exception(exception):
178 """Returns the exit code that would result of raising the exception."""
179 if exception is None:
180 return 0
181 if isinstance(exception[1], SystemExit):
182 return exception[1].code
183 return 1
184
185
Edward Lemurfec80c42018-11-01 23:14:14 +0000186def extract_known_subcommand_args(args):
187 """Extract the known arguments from the passed list of args."""
188 known_args = []
189 for arg in args:
190 if arg in KNOWN_SUBCOMMAND_ARGS:
191 known_args.append(arg)
192 else:
193 arg = arg.split('=')[0]
194 if arg in KNOWN_SUBCOMMAND_ARGS:
195 known_args.append(arg)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000196 return sorted(known_args)
Edward Lemurfec80c42018-11-01 23:14:14 +0000197
198
Edward Lemur03d6d112018-10-23 15:17:36 +0000199def extract_http_metrics(request_uri, method, status, response_time):
200 """Extract metrics from the request URI.
201
202 Extracts the host, path, and arguments from the request URI, and returns them
203 along with the method, status and response time.
204
205 The host, method, path and arguments must be in the KNOWN_HTTP_* constants
206 defined above.
207
208 Arguments are the values of the o= url parameter. In Gerrit, additional fields
209 can be obtained by adding o parameters, each option requires more database
210 lookups and slows down the query response time to the client, so we make an
211 effort to collect them.
212
213 The regex defined in KNOWN_HTTP_PATH_RES are checked against the path, and
214 those that match will be returned.
215 """
216 http_metrics = {
217 'status': status,
218 'response_time': response_time,
219 }
220
221 if method in KNOWN_HTTP_METHODS:
222 http_metrics['method'] = method
223
224 parsed_url = urlparse.urlparse(request_uri)
225
226 if parsed_url.netloc in KNOWN_HTTP_HOSTS:
227 http_metrics['host'] = parsed_url.netloc
228
229 for name, path_re in KNOWN_HTTP_PATHS.iteritems():
230 if path_re.match(parsed_url.path):
231 http_metrics['path'] = name
232 break
233
234 parsed_query = urlparse.parse_qs(parsed_url.query)
235
236 # Collect o-parameters from the request.
237 args = [
238 arg for arg in parsed_query.get('o', [])
239 if arg in KNOWN_HTTP_ARGS
240 ]
241 if args:
242 http_metrics['arguments'] = args
243
244 return http_metrics
245
246
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000247def get_repo_timestamp(path_to_repo):
248 """Get an approximate timestamp for the upstream of |path_to_repo|.
249
250 Returns the top two bits of the timestamp of the HEAD for the upstream of the
251 branch path_to_repo is checked out at.
252 """
253 # Get the upstream for the current branch. If we're not in a branch, fallback
254 # to HEAD.
255 try:
Edward Lemur36974ad2019-02-21 23:29:47 +0000256 upstream = scm.GIT.GetUpstreamBranch(path_to_repo) or 'HEAD'
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000257 except subprocess2.CalledProcessError:
258 upstream = 'HEAD'
259
260 # Get the timestamp of the HEAD for the upstream of the current branch.
261 p = subprocess2.Popen(
262 ['git', '-C', path_to_repo, 'log', '-n1', upstream, '--format=%at'],
263 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
264 stdout, _ = p.communicate()
265
266 # If there was an error, give up.
267 if p.returncode != 0:
268 return None
269
Edward Lemur18df41e2019-04-26 00:42:04 +0000270 return stdout.strip()
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000271
Hans Wennborg24b5f902019-03-15 18:51:27 +0000272def print_boxed_text(out, min_width, lines):
273 [EW, NS, SE, SW, NE, NW] = list('=|++++')
Samuel Huang98a7e802019-02-12 15:32:22 +0000274 width = max(min_width, max(len(line) for line in lines))
275 out(SE + EW * (width + 2) + SW + '\n')
276 for line in lines:
Raul Tambreb946b232019-03-26 14:48:46 +0000277 out('%s %-*s %s\n' % (NS, width, line, NS))
Samuel Huang98a7e802019-02-12 15:32:22 +0000278 out(NE + EW * (width + 2) + NW + '\n')
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000279
280def print_notice(countdown):
281 """Print a notice to let the user know the status of metrics collection."""
Samuel Huang98a7e802019-02-12 15:32:22 +0000282 lines = list(get_notice_countdown_header(countdown))
283 lines.append('')
284 lines += list(get_notice_footer())
Hans Wennborg24b5f902019-03-15 18:51:27 +0000285 print_boxed_text(sys.stderr.write, 49, lines)
Edward Lemur48836262018-10-18 02:08:06 +0000286
287def print_version_change(config_version):
288 """Print a notice to let the user know we are collecting more metrics."""
Samuel Huang98a7e802019-02-12 15:32:22 +0000289 lines = list(get_notice_version_change_header())
290 for version in xrange(config_version + 1, CURRENT_VERSION + 1):
291 lines.append('')
292 lines += list(get_change_notice(version))
Hans Wennborg24b5f902019-03-15 18:51:27 +0000293 print_boxed_text(sys.stderr.write, 49, lines)