metrics_utils.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. #!/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. from __future__ import print_function
  6. import re
  7. import os
  8. import scm
  9. import subprocess2
  10. import sys
  11. try:
  12. import urlparse
  13. except ImportError: # For Py3 compatibility
  14. import urllib.parse as urlparse
  15. # Current version of metrics recording.
  16. # When we add new metrics, the version number will be increased, we display the
  17. # user what has changed, and ask the user to agree again.
  18. CURRENT_VERSION = 2
  19. APP_URL = 'https://cit-cli-metrics.appspot.com'
  20. DEPOT_TOOLS_REPORT_BUILD = 'DEPOT_TOOLS_REPORT_BUILD'
  21. def get_notice_countdown_header(countdown):
  22. if countdown == 0:
  23. yield ' METRICS COLLECTION IS TAKING PLACE'
  24. else:
  25. yield ' METRICS COLLECTION WILL START IN %d EXECUTIONS' % countdown
  26. def get_notice_version_change_header():
  27. yield ' WE ARE COLLECTING ADDITIONAL METRICS'
  28. yield ''
  29. yield ' Please review the changes and opt-in again.'
  30. def get_notice_footer():
  31. yield 'To suppress this message opt in or out using:'
  32. yield '$ gclient metrics [--opt-in] [--opt-out]'
  33. yield 'For more information please see metrics.README.md'
  34. yield 'in your depot_tools checkout or visit'
  35. yield 'https://goo.gl/yNpRDV.'
  36. def get_change_notice(version):
  37. if version == 0:
  38. return [] # No changes for version 0
  39. elif version == 1:
  40. return [
  41. 'We want to collect the Git version.',
  42. 'We want to collect information about the HTTP',
  43. 'requests that depot_tools makes, and the git and',
  44. 'cipd commands it executes.',
  45. '',
  46. 'We only collect known strings to make sure we',
  47. 'don\'t record PII.',
  48. ]
  49. elif version == 2:
  50. return [
  51. 'We will start collecting metrics from bots.',
  52. 'There are no changes for developers.',
  53. 'If the DEPOT_TOOLS_REPORT_BUILD environment variable is set,',
  54. 'we will report information about the current build',
  55. '(e.g. buildbucket project, bucket, builder and build id),',
  56. 'and authenticate to the metrics collection server.',
  57. 'This information will only be recorded for requests',
  58. 'authenticated as bot service accounts.',
  59. ]
  60. KNOWN_PROJECT_URLS = {
  61. 'https://chrome-internal.googlesource.com/chrome/ios_internal',
  62. 'https://chrome-internal.googlesource.com/infra/infra_internal',
  63. 'https://chromium.googlesource.com/breakpad/breakpad',
  64. 'https://chromium.googlesource.com/chromium/src',
  65. 'https://chromium.googlesource.com/chromium/tools/depot_tools',
  66. 'https://chromium.googlesource.com/crashpad/crashpad',
  67. 'https://chromium.googlesource.com/external/gyp',
  68. 'https://chromium.googlesource.com/external/naclports',
  69. 'https://chromium.googlesource.com/infra/goma/client',
  70. 'https://chromium.googlesource.com/infra/infra',
  71. 'https://chromium.googlesource.com/native_client/',
  72. 'https://chromium.googlesource.com/syzygy',
  73. 'https://chromium.googlesource.com/v8/v8',
  74. 'https://dart.googlesource.com/sdk',
  75. 'https://pdfium.googlesource.com/pdfium',
  76. 'https://skia.googlesource.com/buildbot',
  77. 'https://skia.googlesource.com/skia',
  78. 'https://webrtc.googlesource.com/src',
  79. }
  80. KNOWN_HTTP_HOSTS = {
  81. 'chrome-internal-review.googlesource.com',
  82. 'chromium-review.googlesource.com',
  83. 'dart-review.googlesource.com',
  84. 'eu1-mirror-chromium-review.googlesource.com',
  85. 'pdfium-review.googlesource.com',
  86. 'skia-review.googlesource.com',
  87. 'us1-mirror-chromium-review.googlesource.com',
  88. 'us2-mirror-chromium-review.googlesource.com',
  89. 'us3-mirror-chromium-review.googlesource.com',
  90. 'webrtc-review.googlesource.com',
  91. }
  92. KNOWN_HTTP_METHODS = {
  93. 'DELETE',
  94. 'GET',
  95. 'PATCH',
  96. 'POST',
  97. 'PUT',
  98. }
  99. KNOWN_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. KNOWN_HTTP_ARGS = {
  128. 'ALL_REVISIONS',
  129. 'CURRENT_COMMIT',
  130. 'CURRENT_REVISION',
  131. 'DETAILED_ACCOUNTS',
  132. 'LABELS',
  133. }
  134. GIT_VERSION_RE = re.compile(
  135. r'git version (\d)\.(\d{0,2})\.(\d{0,2})'
  136. )
  137. KNOWN_SUBCOMMAND_ARGS = {
  138. 'cc',
  139. 'hashtag',
  140. 'l=Auto-Submit+1',
  141. 'l=Code-Review+1',
  142. 'l=Code-Review+2',
  143. 'l=Commit-Queue+1',
  144. 'l=Commit-Queue+2',
  145. 'label',
  146. 'm',
  147. 'notify=ALL',
  148. 'notify=NONE',
  149. 'private',
  150. 'r',
  151. 'ready',
  152. 'topic',
  153. 'wip'
  154. }
  155. def get_python_version():
  156. """Return the python version in the major.minor.micro format."""
  157. return '{v.major}.{v.minor}.{v.micro}'.format(v=sys.version_info)
  158. def get_git_version():
  159. """Return the Git version in the major.minor.micro format."""
  160. p = subprocess2.Popen(
  161. ['git', '--version'],
  162. stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
  163. stdout, _ = p.communicate()
  164. match = GIT_VERSION_RE.match(stdout.decode('utf-8'))
  165. if not match:
  166. return None
  167. return '%s.%s.%s' % match.groups()
  168. def get_bot_metrics():
  169. build = os.getenv(DEPOT_TOOLS_REPORT_BUILD)
  170. if not build or build.count('/') != 3:
  171. return None
  172. project, bucket, builder, build = build.split('/')
  173. return {
  174. 'build_id': int(build),
  175. 'builder': {
  176. 'project': project,
  177. 'bucket': bucket,
  178. 'builder': builder,
  179. },
  180. }
  181. def return_code_from_exception(exception):
  182. """Returns the exit code that would result of raising the exception."""
  183. if exception is None:
  184. return 0
  185. if isinstance(exception[1], SystemExit):
  186. return exception[1].code
  187. return 1
  188. def extract_known_subcommand_args(args):
  189. """Extract the known arguments from the passed list of args."""
  190. known_args = []
  191. for arg in args:
  192. if arg in KNOWN_SUBCOMMAND_ARGS:
  193. known_args.append(arg)
  194. else:
  195. arg = arg.split('=')[0]
  196. if arg in KNOWN_SUBCOMMAND_ARGS:
  197. known_args.append(arg)
  198. return sorted(known_args)
  199. def extract_http_metrics(request_uri, method, status, response_time):
  200. """Extract metrics from the request URI.
  201. Extracts the host, path, and arguments from the request URI, and returns them
  202. along with the method, status and response time.
  203. The host, method, path and arguments must be in the KNOWN_HTTP_* constants
  204. defined above.
  205. Arguments are the values of the o= url parameter. In Gerrit, additional fields
  206. can be obtained by adding o parameters, each option requires more database
  207. lookups and slows down the query response time to the client, so we make an
  208. effort to collect them.
  209. The regex defined in KNOWN_HTTP_PATH_RES are checked against the path, and
  210. those that match will be returned.
  211. """
  212. http_metrics = {
  213. 'status': status,
  214. 'response_time': response_time,
  215. }
  216. if method in KNOWN_HTTP_METHODS:
  217. http_metrics['method'] = method
  218. parsed_url = urlparse.urlparse(request_uri)
  219. if parsed_url.netloc in KNOWN_HTTP_HOSTS:
  220. http_metrics['host'] = parsed_url.netloc
  221. for name, path_re in KNOWN_HTTP_PATHS.items():
  222. if path_re.match(parsed_url.path):
  223. http_metrics['path'] = name
  224. break
  225. parsed_query = urlparse.parse_qs(parsed_url.query)
  226. # Collect o-parameters from the request.
  227. args = [
  228. arg for arg in parsed_query.get('o', [])
  229. if arg in KNOWN_HTTP_ARGS
  230. ]
  231. if args:
  232. http_metrics['arguments'] = args
  233. return http_metrics
  234. def get_repo_timestamp(path_to_repo):
  235. """Get an approximate timestamp for the upstream of |path_to_repo|.
  236. Returns the top two bits of the timestamp of the HEAD for the upstream of the
  237. branch path_to_repo is checked out at.
  238. """
  239. # Get the upstream for the current branch. If we're not in a branch, fallback
  240. # to HEAD.
  241. try:
  242. upstream = scm.GIT.GetUpstreamBranch(path_to_repo) or 'HEAD'
  243. except subprocess2.CalledProcessError:
  244. upstream = 'HEAD'
  245. # Get the timestamp of the HEAD for the upstream of the current branch.
  246. p = subprocess2.Popen(
  247. ['git', '-C', path_to_repo, 'log', '-n1', upstream, '--format=%at'],
  248. stdout=subprocess2.PIPE, stderr=subprocess2.PIPE)
  249. stdout, _ = p.communicate()
  250. # If there was an error, give up.
  251. if p.returncode != 0:
  252. return None
  253. return stdout.strip()
  254. def print_boxed_text(out, min_width, lines):
  255. [EW, NS, SE, SW, NE, NW] = list('=|++++')
  256. width = max(min_width, max(len(line) for line in lines))
  257. out(SE + EW * (width + 2) + SW + '\n')
  258. for line in lines:
  259. out('%s %-*s %s\n' % (NS, width, line, NS))
  260. out(NE + EW * (width + 2) + NW + '\n')
  261. def print_notice(countdown):
  262. """Print a notice to let the user know the status of metrics collection."""
  263. lines = list(get_notice_countdown_header(countdown))
  264. lines.append('')
  265. lines += list(get_notice_footer())
  266. print_boxed_text(sys.stderr.write, 49, lines)
  267. def print_version_change(config_version):
  268. """Print a notice to let the user know we are collecting more metrics."""
  269. lines = list(get_notice_version_change_header())
  270. for version in range(config_version + 1, CURRENT_VERSION + 1):
  271. lines.append('')
  272. lines += get_change_notice(version)
  273. print_boxed_text(sys.stderr.write, 49, lines)