blob: f8fc2908d0bb03a9db8062d3538fe7d024e97168 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Allen Li24bf8182017-03-02 16:41:20 -08002# Copyright 2017 The Chromium OS 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
6"""Git repo metrics."""
7
8from __future__ import absolute_import
9from __future__ import print_function
Allen Li24bf8182017-03-02 16:41:20 -080010
11import os
12import subprocess
13
Allen Li24bf8182017-03-02 16:41:20 -080014from chromite.lib import cros_logging as logging
Allen Lia9c6e802017-07-11 15:42:47 -070015from chromite.lib import metrics
Allen Li24bf8182017-03-02 16:41:20 -080016
17logger = logging.getLogger(__name__)
18
19
20class _GitRepo(object):
Paul Hobbse46a42b2017-03-21 14:04:13 -070021 """Helper class for running git commands."""
Allen Li24bf8182017-03-02 16:41:20 -080022
23 def __init__(self, gitdir):
24 self._gitdir = gitdir
25
26 def _get_git_command(self):
27 return ['git', '--git-dir', self._gitdir]
28
29 def _check_output(self, args, **kwargs):
30 return subprocess.check_output(
31 self._get_git_command() + list(args), **kwargs)
32
33 def get_commit_hash(self):
Allen Lid2333982017-04-04 17:03:32 -070034 """Return commit hash string."""
Allen Li24bf8182017-03-02 16:41:20 -080035 return self._check_output(['rev-parse', 'HEAD']).strip()
36
37 def get_commit_time(self):
Allen Lid2333982017-04-04 17:03:32 -070038 """Return commit time as UNIX timestamp int."""
Allen Li24bf8182017-03-02 16:41:20 -080039 return int(self._check_output(['show', '-s', '--format=%ct', 'HEAD'])
40 .strip())
41
Allen Li8934e042017-06-21 15:54:42 -070042 def get_unstaged_changes(self):
43 """Return number of unstaged changes as (added, deleted)."""
Allen Li5956da62017-06-27 12:38:49 -070044 added_total, deleted_total = 0, 0
45 # output looks like:
46 # '1\t2\tfoo\n3\t4\tbar\n'
47 # '-\t-\tbinary_file\n'
Allen Li8934e042017-06-21 15:54:42 -070048 output = self._check_output(['diff-index', '--numstat', 'HEAD'])
49 stats_strings = (line.split() for line in output.splitlines())
Allen Li5956da62017-06-27 12:38:49 -070050 for added, deleted, _path in stats_strings:
51 if added != '-':
52 added_total += int(added)
53 if deleted != '-':
54 deleted_total += int(deleted)
55 return added_total, deleted_total
Allen Li8934e042017-06-21 15:54:42 -070056
Allen Li24bf8182017-03-02 16:41:20 -080057
58class _GitMetricCollector(object):
Allen Libdb9f042017-04-10 13:25:47 -070059 """Class for collecting metrics about a git repository.
60
61 The constructor takes the arguments: `gitdir`, `metric_path`.
62 `gitdir` is the path to the Git directory to collect metrics for and
63 may start with a tilde (expanded to a user's home directory).
64 `metric_path` is the Monarch metric path to report to.
65 """
Allen Li24bf8182017-03-02 16:41:20 -080066
Allen Lia9c6e802017-07-11 15:42:47 -070067 _commit_hash_metric = metrics.StringMetric(
Allen Li24bf8182017-03-02 16:41:20 -080068 'git/hash',
69 description='Current Git commit hash.')
70
Allen Lia9c6e802017-07-11 15:42:47 -070071 _timestamp_metric = metrics.GaugeMetric(
Allen Lid523d962017-04-04 16:48:36 -070072 'git/timestamp',
Allen Li24bf8182017-03-02 16:41:20 -080073 description='Current Git commit time as seconds since Unix Epoch.')
74
Allen Lia9c6e802017-07-11 15:42:47 -070075 _unstaged_changes_metric = metrics.GaugeMetric(
Allen Li8934e042017-06-21 15:54:42 -070076 'git/unstaged_changes',
77 description='Unstaged Git changes.')
78
Allen Li24bf8182017-03-02 16:41:20 -080079 def __init__(self, gitdir, metric_path):
80 self._gitdir = gitdir
Allen Libdb9f042017-04-10 13:25:47 -070081 self._gitrepo = _GitRepo(os.path.expanduser(gitdir))
Allen Li24bf8182017-03-02 16:41:20 -080082 self._fields = {'repo': gitdir}
83 self._metric_path = metric_path
84
85 def collect(self):
86 """Collect metrics."""
87 try:
88 self._collect_commit_hash_metric()
Allen Lid523d962017-04-04 16:48:36 -070089 self._collect_timestamp_metric()
Allen Li8934e042017-06-21 15:54:42 -070090 self._collect_unstaged_changes_metric()
Allen Li24bf8182017-03-02 16:41:20 -080091 except subprocess.CalledProcessError as e:
Allen Li867d4582017-05-24 18:00:43 -070092 logger.warning(u'Error collecting git metrics for %s: %s',
Allen Li24bf8182017-03-02 16:41:20 -080093 self._gitdir, e)
94
95 def _collect_commit_hash_metric(self):
96 commit_hash = self._gitrepo.get_commit_hash()
Allen Li867d4582017-05-24 18:00:43 -070097 logger.debug(u'Collecting Git hash %r for %r', commit_hash, self._gitdir)
Allen Li24bf8182017-03-02 16:41:20 -080098 self._commit_hash_metric.set(commit_hash, self._fields)
99
Allen Lid523d962017-04-04 16:48:36 -0700100 def _collect_timestamp_metric(self):
Allen Li24bf8182017-03-02 16:41:20 -0800101 commit_time = self._gitrepo.get_commit_time()
Allen Li867d4582017-05-24 18:00:43 -0700102 logger.debug(u'Collecting Git timestamp %r for %r',
Allen Li24bf8182017-03-02 16:41:20 -0800103 commit_time, self._gitdir)
Allen Lid523d962017-04-04 16:48:36 -0700104 self._timestamp_metric.set(commit_time, self._fields)
Allen Li24bf8182017-03-02 16:41:20 -0800105
Allen Li8934e042017-06-21 15:54:42 -0700106 def _collect_unstaged_changes_metric(self):
Allen Lic8acdec2017-06-26 15:09:41 -0700107 added, deleted = self._gitrepo.get_unstaged_changes()
Allen Li36b8a8b2017-06-28 14:47:16 -0700108 self._unstaged_changes_metric.set(
Allen Li8934e042017-06-21 15:54:42 -0700109 added, fields=dict(change_type='added', **self._fields))
Allen Li36b8a8b2017-06-28 14:47:16 -0700110 self._unstaged_changes_metric.set(
Allen Li8934e042017-06-21 15:54:42 -0700111 deleted, fields=dict(change_type='deleted', **self._fields))
112
Allen Li24bf8182017-03-02 16:41:20 -0800113
Allen Libdb9f042017-04-10 13:25:47 -0700114_CHROMIUMOS_DIR = '~chromeos-test/chromiumos/'
Allen Li24bf8182017-03-02 16:41:20 -0800115
116_repo_collectors = (
Allen Lia02d34a2017-04-04 17:13:46 -0700117 # TODO(ayatane): We cannot access chromeos-admin because we are
118 # running as non-root.
119 _GitMetricCollector(gitdir='/root/chromeos-admin/.git',
120 metric_path='chromeos-admin'),
121 _GitMetricCollector(gitdir=_CHROMIUMOS_DIR + 'chromite/.git',
122 metric_path='chromite'),
123 _GitMetricCollector(gitdir='/usr/local/autotest/.git',
124 metric_path='installed_autotest'),
Allen Li24bf8182017-03-02 16:41:20 -0800125)
126
127
128def collect_git_metrics():
129 """Collect metrics for Git repository state."""
130 for collector in _repo_collectors:
131 collector.collect()