blob: 4712700c6a0f4f36efd62d5b74f8d9d5a6b39fee [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
9from __future__ import unicode_literals
10
11import os
12import subprocess
13
14import psutil
15
16from chromite.lib import cros_logging as logging
17from infra_libs import ts_mon
18
19logger = logging.getLogger(__name__)
20
21
22class _GitRepo(object):
23
24 def __init__(self, gitdir):
25 self._gitdir = gitdir
26
27 def _get_git_command(self):
28 return ['git', '--git-dir', self._gitdir]
29
30 def _check_output(self, args, **kwargs):
31 return subprocess.check_output(
32 self._get_git_command() + list(args), **kwargs)
33
34 def get_commit_hash(self):
35 return self._check_output(['rev-parse', 'HEAD']).strip()
36
37 def get_commit_time(self):
38 return int(self._check_output(['show', '-s', '--format=%ct', 'HEAD'])
39 .strip())
40
41
42class _GitMetricCollector(object):
43
44 _commit_hash_metric = ts_mon.StringMetric(
45 'git/hash',
46 description='Current Git commit hash.')
47
48 _commit_time_metric = ts_mon.StringMetric(
49 'git/commit_time',
50 description='Current Git commit time as seconds since Unix Epoch.')
51
52 def __init__(self, gitdir, metric_path):
53 self._gitdir = gitdir
54 self._gitrepo = _GitRepo(gitdir)
55 self._fields = {'repo': gitdir}
56 self._metric_path = metric_path
57
58 def collect(self):
59 """Collect metrics."""
60 try:
61 self._collect_commit_hash_metric()
62 self._collect_commit_time_metric()
63 except subprocess.CalledProcessError as e:
64 logger.warning('Error collecting git metrics for %s: %s',
65 self._gitdir, e)
66
67 def _collect_commit_hash_metric(self):
68 commit_hash = self._gitrepo.get_commit_hash()
69 logger.debug('Collecting Git hash %r for %r', commit_hash, self._gitdir)
70 self._commit_hash_metric.set(commit_hash, self._fields)
71
72 def _collect_commit_time_metric(self):
73 commit_time = self._gitrepo.get_commit_time()
74 logger.debug('Collecting Git commit time %r for %r',
75 commit_time, self._gitdir)
76 self._commit_time_metric.set(commit_time, self._fields)
77
78
79_CHROMIUMOS_DIR = os.path.expanduser('~chromeos-test/chromiumos/')
80
81_repo_collectors = (
82 # TODO(ayatane): We cannot access chromeos-admin because we are
83 # running as non-root.
84 _GitMetricCollector(gitdir='/root/chromeos-admin/.git',
85 metric_path='chromeos-admin'),
86 _GitMetricCollector(gitdir=_CHROMIUMOS_DIR + 'chromite/.git',
87 metric_path='chromite'),
88 _GitMetricCollector(gitdir='/usr/local/autotest/.git',
89 metric_path='installed_autotest'),
90)
91
92
93def collect_git_metrics():
94 """Collect metrics for Git repository state."""
95 for collector in _repo_collectors:
96 collector.collect()