blob: aa1f50ed4b912e09941bf0cea1904d039d34cba9 [file] [log] [blame]
Allen Li24bf8182017-03-02 16:41:20 -08001# Copyright 2017 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Git repo metrics."""
6
7from __future__ import absolute_import
8from __future__ import print_function
Allen Li24bf8182017-03-02 16:41:20 -08009
10import os
11import subprocess
12
Allen Li24bf8182017-03-02 16:41:20 -080013from chromite.lib import cros_logging as logging
Allen Lia9c6e802017-07-11 15:42:47 -070014from chromite.lib import metrics
Allen Li24bf8182017-03-02 16:41:20 -080015
16logger = logging.getLogger(__name__)
17
18
19class _GitRepo(object):
Paul Hobbse46a42b2017-03-21 14:04:13 -070020 """Helper class for running git commands."""
Allen Li24bf8182017-03-02 16:41:20 -080021
22 def __init__(self, gitdir):
23 self._gitdir = gitdir
24
25 def _get_git_command(self):
26 return ['git', '--git-dir', self._gitdir]
27
28 def _check_output(self, args, **kwargs):
29 return subprocess.check_output(
30 self._get_git_command() + list(args), **kwargs)
31
32 def get_commit_hash(self):
Allen Lid2333982017-04-04 17:03:32 -070033 """Return commit hash string."""
Allen Li24bf8182017-03-02 16:41:20 -080034 return self._check_output(['rev-parse', 'HEAD']).strip()
35
36 def get_commit_time(self):
Allen Lid2333982017-04-04 17:03:32 -070037 """Return commit time as UNIX timestamp int."""
Allen Li24bf8182017-03-02 16:41:20 -080038 return int(self._check_output(['show', '-s', '--format=%ct', 'HEAD'])
39 .strip())
40
Allen Li8934e042017-06-21 15:54:42 -070041 def get_unstaged_changes(self):
42 """Return number of unstaged changes as (added, deleted)."""
Allen Li5956da62017-06-27 12:38:49 -070043 added_total, deleted_total = 0, 0
44 # output looks like:
45 # '1\t2\tfoo\n3\t4\tbar\n'
46 # '-\t-\tbinary_file\n'
Allen Li8934e042017-06-21 15:54:42 -070047 output = self._check_output(['diff-index', '--numstat', 'HEAD'])
48 stats_strings = (line.split() for line in output.splitlines())
Allen Li5956da62017-06-27 12:38:49 -070049 for added, deleted, _path in stats_strings:
50 if added != '-':
51 added_total += int(added)
52 if deleted != '-':
53 deleted_total += int(deleted)
54 return added_total, deleted_total
Allen Li8934e042017-06-21 15:54:42 -070055
Allen Li24bf8182017-03-02 16:41:20 -080056
57class _GitMetricCollector(object):
Allen Libdb9f042017-04-10 13:25:47 -070058 """Class for collecting metrics about a git repository.
59
60 The constructor takes the arguments: `gitdir`, `metric_path`.
61 `gitdir` is the path to the Git directory to collect metrics for and
62 may start with a tilde (expanded to a user's home directory).
63 `metric_path` is the Monarch metric path to report to.
64 """
Allen Li24bf8182017-03-02 16:41:20 -080065
Allen Lia9c6e802017-07-11 15:42:47 -070066 _commit_hash_metric = metrics.StringMetric(
Allen Li24bf8182017-03-02 16:41:20 -080067 'git/hash',
68 description='Current Git commit hash.')
69
Allen Lia9c6e802017-07-11 15:42:47 -070070 _timestamp_metric = metrics.GaugeMetric(
Allen Lid523d962017-04-04 16:48:36 -070071 'git/timestamp',
Allen Li24bf8182017-03-02 16:41:20 -080072 description='Current Git commit time as seconds since Unix Epoch.')
73
Allen Lia9c6e802017-07-11 15:42:47 -070074 _unstaged_changes_metric = metrics.GaugeMetric(
Allen Li8934e042017-06-21 15:54:42 -070075 'git/unstaged_changes',
76 description='Unstaged Git changes.')
77
Allen Li24bf8182017-03-02 16:41:20 -080078 def __init__(self, gitdir, metric_path):
79 self._gitdir = gitdir
Allen Libdb9f042017-04-10 13:25:47 -070080 self._gitrepo = _GitRepo(os.path.expanduser(gitdir))
Allen Li24bf8182017-03-02 16:41:20 -080081 self._fields = {'repo': gitdir}
82 self._metric_path = metric_path
83
84 def collect(self):
85 """Collect metrics."""
86 try:
87 self._collect_commit_hash_metric()
Allen Lid523d962017-04-04 16:48:36 -070088 self._collect_timestamp_metric()
Allen Li8934e042017-06-21 15:54:42 -070089 self._collect_unstaged_changes_metric()
Allen Li24bf8182017-03-02 16:41:20 -080090 except subprocess.CalledProcessError as e:
Allen Li867d4582017-05-24 18:00:43 -070091 logger.warning(u'Error collecting git metrics for %s: %s',
Allen Li24bf8182017-03-02 16:41:20 -080092 self._gitdir, e)
93
94 def _collect_commit_hash_metric(self):
95 commit_hash = self._gitrepo.get_commit_hash()
Allen Li867d4582017-05-24 18:00:43 -070096 logger.debug(u'Collecting Git hash %r for %r', commit_hash, self._gitdir)
Allen Li24bf8182017-03-02 16:41:20 -080097 self._commit_hash_metric.set(commit_hash, self._fields)
98
Allen Lid523d962017-04-04 16:48:36 -070099 def _collect_timestamp_metric(self):
Allen Li24bf8182017-03-02 16:41:20 -0800100 commit_time = self._gitrepo.get_commit_time()
Allen Li867d4582017-05-24 18:00:43 -0700101 logger.debug(u'Collecting Git timestamp %r for %r',
Allen Li24bf8182017-03-02 16:41:20 -0800102 commit_time, self._gitdir)
Allen Lid523d962017-04-04 16:48:36 -0700103 self._timestamp_metric.set(commit_time, self._fields)
Allen Li24bf8182017-03-02 16:41:20 -0800104
Allen Li8934e042017-06-21 15:54:42 -0700105 def _collect_unstaged_changes_metric(self):
Allen Lic8acdec2017-06-26 15:09:41 -0700106 added, deleted = self._gitrepo.get_unstaged_changes()
Allen Li36b8a8b2017-06-28 14:47:16 -0700107 self._unstaged_changes_metric.set(
Allen Li8934e042017-06-21 15:54:42 -0700108 added, fields=dict(change_type='added', **self._fields))
Allen Li36b8a8b2017-06-28 14:47:16 -0700109 self._unstaged_changes_metric.set(
Allen Li8934e042017-06-21 15:54:42 -0700110 deleted, fields=dict(change_type='deleted', **self._fields))
111
Allen Li24bf8182017-03-02 16:41:20 -0800112
Allen Libdb9f042017-04-10 13:25:47 -0700113_CHROMIUMOS_DIR = '~chromeos-test/chromiumos/'
Allen Li24bf8182017-03-02 16:41:20 -0800114
115_repo_collectors = (
Allen Lia02d34a2017-04-04 17:13:46 -0700116 # TODO(ayatane): We cannot access chromeos-admin because we are
117 # running as non-root.
118 _GitMetricCollector(gitdir='/root/chromeos-admin/.git',
119 metric_path='chromeos-admin'),
120 _GitMetricCollector(gitdir=_CHROMIUMOS_DIR + 'chromite/.git',
121 metric_path='chromite'),
122 _GitMetricCollector(gitdir='/usr/local/autotest/.git',
123 metric_path='installed_autotest'),
Allen Li24bf8182017-03-02 16:41:20 -0800124)
125
126
127def collect_git_metrics():
128 """Collect metrics for Git repository state."""
129 for collector in _repo_collectors:
130 collector.collect()