blob: b97828fd739de3fde6cccdbb44a3d7e480a1194e [file] [log] [blame]
Edward Lemur32e3d1e2018-07-12 00:54:05 +00001#!/usr/bin/env python
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +00002# -*- coding: utf-8 -*-
Edward Lemur32e3d1e2018-07-12 00:54:05 +00003# Copyright (c) 2018 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
Edward Lemurc87d45b2018-07-26 17:43:11 +00007from __future__ import print_function
8
Edward Lemur03d6d112018-10-23 15:17:36 +00009import re
Edward Lemur32e3d1e2018-07-12 00:54:05 +000010import scm
11import subprocess2
12import sys
Edward Lemur03d6d112018-10-23 15:17:36 +000013import urlparse
Edward Lemur32e3d1e2018-07-12 00:54:05 +000014
15from third_party import colorama
16
17
Edward Lemur48836262018-10-18 02:08:06 +000018# Current version of metrics recording.
19# When we add new metrics, the version number will be increased, we display the
20# user what has changed, and ask the user to agree again.
Edward Lemur5a9ff432018-10-30 19:00:22 +000021CURRENT_VERSION = 1
Edward Lemur48836262018-10-18 02:08:06 +000022
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000023APP_URL = 'https://cit-cli-metrics.appspot.com'
24
Edward Lemur48836262018-10-18 02:08:06 +000025EMPTY_LINE = (
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000026 '┃ ┃'
Edward Lemur48836262018-10-18 02:08:06 +000027)
Edward Lemur32e3d1e2018-07-12 00:54:05 +000028NOTICE_COUNTDOWN_HEADER = (
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000029 '┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n'
30 '┃ METRICS COLLECTION WILL START IN %2d EXECUTIONS ┃'
Edward Lemur32e3d1e2018-07-12 00:54:05 +000031)
32NOTICE_COLLECTION_HEADER = (
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000033 '┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n'
34 '┃ METRICS COLLECTION IS TAKING PLACE ┃'
Edward Lemur32e3d1e2018-07-12 00:54:05 +000035)
Edward Lemur48836262018-10-18 02:08:06 +000036NOTICE_VERSION_CHANGE_HEADER = (
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000037 '┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n'
38 '┃ WE ARE COLLECTING ADDITIONAL METRICS ┃\n'
39 '┃ ┃\n'
40 '┃ Please review the changes and opt-in again. ┃'
Edward Lemur48836262018-10-18 02:08:06 +000041)
Edward Lemur32e3d1e2018-07-12 00:54:05 +000042NOTICE_FOOTER = (
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000043 '┃ To suppress this message opt in or out using: ┃\n'
44 '┃ $ gclient metrics [--opt-in] [--opt-out] ┃\n'
45 '┃ For more information please see metrics.README.md ┃\n'
46 '┃ in your depot_tools checkout or visit ┃\n'
47 '┃ https://goo.gl/yNpRDV. ┃\n'
48 '┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n'
Edward Lemur32e3d1e2018-07-12 00:54:05 +000049)
50
Edward Lemur48836262018-10-18 02:08:06 +000051CHANGE_NOTICE = {
52 # No changes for version 0
53 0: '',
Elliott Friedmanf6a8ae72018-12-08 00:54:54 +000054 1: ('┃ We want to collect the Git version. ┃\n'
55 '┃ We want to collect information about the HTTP ┃\n'
56 '┃ requests that depot_tools makes, and the git and ┃\n'
57 '┃ cipd commands it executes. ┃\n'
58 '┃ ┃\n'
59 '┃ We only collect known strings to make sure we ┃\n'
60 '┃ don\'t record PII. ┃')
Edward Lemur48836262018-10-18 02:08:06 +000061}
62
63
Edward Lemur40764b02018-07-20 18:50:29 +000064KNOWN_PROJECT_URLS = {
65 'https://chrome-internal.googlesource.com/chrome/ios_internal',
66 'https://chrome-internal.googlesource.com/infra/infra_internal',
67 'https://chromium.googlesource.com/breakpad/breakpad',
68 'https://chromium.googlesource.com/chromium/src',
69 'https://chromium.googlesource.com/chromium/tools/depot_tools',
70 'https://chromium.googlesource.com/crashpad/crashpad',
71 'https://chromium.googlesource.com/external/gyp',
72 'https://chromium.googlesource.com/external/naclports',
73 'https://chromium.googlesource.com/infra/goma/client',
74 'https://chromium.googlesource.com/infra/infra',
75 'https://chromium.googlesource.com/native_client/',
76 'https://chromium.googlesource.com/syzygy',
77 'https://chromium.googlesource.com/v8/v8',
78 'https://dart.googlesource.com/sdk',
79 'https://pdfium.googlesource.com/pdfium',
80 'https://skia.googlesource.com/buildbot',
81 'https://skia.googlesource.com/skia',
82 'https://webrtc.googlesource.com/src',
83}
84
Edward Lemur03d6d112018-10-23 15:17:36 +000085KNOWN_HTTP_HOSTS = {
86 'chrome-internal-review.googlesource.com',
87 'chromium-review.googlesource.com',
88 'dart-review.googlesource.com',
89 'eu1-mirror-chromium-review.googlesource.com',
90 'pdfium-review.googlesource.com',
91 'skia-review.googlesource.com',
92 'us1-mirror-chromium-review.googlesource.com',
93 'us2-mirror-chromium-review.googlesource.com',
94 'us3-mirror-chromium-review.googlesource.com',
95 'webrtc-review.googlesource.com',
96}
97
98KNOWN_HTTP_METHODS = {
99 'DELETE',
100 'GET',
101 'PATCH',
102 'POST',
103 'PUT',
104}
105
106KNOWN_HTTP_PATHS = {
107 'accounts':
108 re.compile(r'(/a)?/accounts/.*'),
109 'changes':
110 re.compile(r'(/a)?/changes/([^/]+)?$'),
111 'changes/abandon':
112 re.compile(r'(/a)?/changes/.*/abandon'),
113 'changes/comments':
114 re.compile(r'(/a)?/changes/.*/comments'),
115 'changes/detail':
116 re.compile(r'(/a)?/changes/.*/detail'),
117 'changes/edit':
118 re.compile(r'(/a)?/changes/.*/edit'),
119 'changes/message':
120 re.compile(r'(/a)?/changes/.*/message'),
121 'changes/restore':
122 re.compile(r'(/a)?/changes/.*/restore'),
123 'changes/reviewers':
124 re.compile(r'(/a)?/changes/.*/reviewers/.*'),
125 'changes/revisions/commit':
126 re.compile(r'(/a)?/changes/.*/revisions/.*/commit'),
127 'changes/revisions/review':
128 re.compile(r'(/a)?/changes/.*/revisions/.*/review'),
129 'changes/submit':
130 re.compile(r'(/a)?/changes/.*/submit'),
131 'projects/branches':
132 re.compile(r'(/a)?/projects/.*/branches/.*'),
133}
134
135KNOWN_HTTP_ARGS = {
136 'ALL_REVISIONS',
137 'CURRENT_COMMIT',
138 'CURRENT_REVISION',
139 'DETAILED_ACCOUNTS',
140 'LABELS',
141}
142
Edward Lemur861640f2018-10-31 19:45:31 +0000143GIT_VERSION_RE = re.compile(
144 r'git version (\d)\.(\d{0,2})\.(\d{0,2})'
145)
146
Edward Lemurfec80c42018-11-01 23:14:14 +0000147KNOWN_SUBCOMMAND_ARGS = {
148 'cc',
149 'hashtag',
150 'l=Auto-Submit+1',
Edward Lemur687ca902018-12-05 02:30:30 +0000151 'l=Code-Review+1',
152 'l=Code-Review+2',
Edward Lemurfec80c42018-11-01 23:14:14 +0000153 'l=Commit-Queue+1',
154 'l=Commit-Queue+2',
155 'label',
156 'm',
157 'notify=ALL',
158 'notify=NONE',
159 'private',
160 'r',
161 'ready',
162 'topic',
163 'wip'
164}
165
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000166
167def get_python_version():
168 """Return the python version in the major.minor.micro format."""
169 return '{v.major}.{v.minor}.{v.micro}'.format(v=sys.version_info)
170
171
Edward Lemur861640f2018-10-31 19:45:31 +0000172def get_git_version():
173 """Return the Git version in the major.minor.micro format."""
174 p = subprocess2.Popen(
175 ['git', '--version'],
176 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
177 stdout, _ = p.communicate()
178 match = GIT_VERSION_RE.match(stdout)
179 if not match:
180 return None
181 return '%s.%s.%s' % match.groups()
182
183
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000184def return_code_from_exception(exception):
185 """Returns the exit code that would result of raising the exception."""
186 if exception is None:
187 return 0
188 if isinstance(exception[1], SystemExit):
189 return exception[1].code
190 return 1
191
192
193def seconds_to_weeks(duration):
194 """Transform a |duration| from seconds to weeks approximately.
195
196 Drops the lowest 19 bits of the integer representation, which ammounts to
197 about 6 days.
198 """
199 return int(duration) >> 19
200
201
Edward Lemurfec80c42018-11-01 23:14:14 +0000202def extract_known_subcommand_args(args):
203 """Extract the known arguments from the passed list of args."""
204 known_args = []
205 for arg in args:
206 if arg in KNOWN_SUBCOMMAND_ARGS:
207 known_args.append(arg)
208 else:
209 arg = arg.split('=')[0]
210 if arg in KNOWN_SUBCOMMAND_ARGS:
211 known_args.append(arg)
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000212 return sorted(known_args)
Edward Lemurfec80c42018-11-01 23:14:14 +0000213
214
Edward Lemur03d6d112018-10-23 15:17:36 +0000215def extract_http_metrics(request_uri, method, status, response_time):
216 """Extract metrics from the request URI.
217
218 Extracts the host, path, and arguments from the request URI, and returns them
219 along with the method, status and response time.
220
221 The host, method, path and arguments must be in the KNOWN_HTTP_* constants
222 defined above.
223
224 Arguments are the values of the o= url parameter. In Gerrit, additional fields
225 can be obtained by adding o parameters, each option requires more database
226 lookups and slows down the query response time to the client, so we make an
227 effort to collect them.
228
229 The regex defined in KNOWN_HTTP_PATH_RES are checked against the path, and
230 those that match will be returned.
231 """
232 http_metrics = {
233 'status': status,
234 'response_time': response_time,
235 }
236
237 if method in KNOWN_HTTP_METHODS:
238 http_metrics['method'] = method
239
240 parsed_url = urlparse.urlparse(request_uri)
241
242 if parsed_url.netloc in KNOWN_HTTP_HOSTS:
243 http_metrics['host'] = parsed_url.netloc
244
245 for name, path_re in KNOWN_HTTP_PATHS.iteritems():
246 if path_re.match(parsed_url.path):
247 http_metrics['path'] = name
248 break
249
250 parsed_query = urlparse.parse_qs(parsed_url.query)
251
252 # Collect o-parameters from the request.
253 args = [
254 arg for arg in parsed_query.get('o', [])
255 if arg in KNOWN_HTTP_ARGS
256 ]
257 if args:
258 http_metrics['arguments'] = args
259
260 return http_metrics
261
262
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000263def get_repo_timestamp(path_to_repo):
264 """Get an approximate timestamp for the upstream of |path_to_repo|.
265
266 Returns the top two bits of the timestamp of the HEAD for the upstream of the
267 branch path_to_repo is checked out at.
268 """
269 # Get the upstream for the current branch. If we're not in a branch, fallback
270 # to HEAD.
271 try:
272 upstream = scm.GIT.GetUpstreamBranch(path_to_repo)
273 except subprocess2.CalledProcessError:
274 upstream = 'HEAD'
275
276 # Get the timestamp of the HEAD for the upstream of the current branch.
277 p = subprocess2.Popen(
278 ['git', '-C', path_to_repo, 'log', '-n1', upstream, '--format=%at'],
279 stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
280 stdout, _ = p.communicate()
281
282 # If there was an error, give up.
283 if p.returncode != 0:
284 return None
285
286 # Get the age of the checkout in weeks.
287 return seconds_to_weeks(stdout.strip())
288
289
290def print_notice(countdown):
291 """Print a notice to let the user know the status of metrics collection."""
292 colorama.init()
Edward Lemur48836262018-10-18 02:08:06 +0000293 print(colorama.Fore.RED + '\033[1m', file=sys.stderr, end='')
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000294 if countdown:
Edward Lemurc87d45b2018-07-26 17:43:11 +0000295 print(NOTICE_COUNTDOWN_HEADER % countdown, file=sys.stderr)
Edward Lemur32e3d1e2018-07-12 00:54:05 +0000296 else:
Edward Lemurc87d45b2018-07-26 17:43:11 +0000297 print(NOTICE_COLLECTION_HEADER, file=sys.stderr)
Edward Lemur48836262018-10-18 02:08:06 +0000298 print(EMPTY_LINE, file=sys.stderr)
Edward Lemurc87d45b2018-07-26 17:43:11 +0000299 print(NOTICE_FOOTER + colorama.Style.RESET_ALL, file=sys.stderr)
Edward Lemur48836262018-10-18 02:08:06 +0000300
301
302def print_version_change(config_version):
303 """Print a notice to let the user know we are collecting more metrics."""
304 colorama.init()
305 print(colorama.Fore.RED + '\033[1m', file=sys.stderr, end='')
306 print(NOTICE_VERSION_CHANGE_HEADER, file=sys.stderr)
307 print(EMPTY_LINE, file=sys.stderr)
308 for version in range(config_version + 1, CURRENT_VERSION + 1):
309 print(CHANGE_NOTICE[version], file=sys.stderr)
310 print(EMPTY_LINE, file=sys.stderr)