GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — contrib/plugins/git/git_commit_behind at master · Nazdravi/contrib

Expand file tree

/

git_commit_behind

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
executable file
·
297 lines (223 loc) · 9.44 KB
/

git_commit_behind

Copy path

File metadata and controls

executable file
·
297 lines (223 loc) · 9.44 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#! /usr/bin/env python3
"""=cut
=head1 NAME
git_commit_behind - Munin plugin to monitor local git repositories and report how many commits behind their remote they are
=head1 NOTES
This plugin is similar to how apt_all works for apt packages.
To be able to check how behind a git repository is, we need to run git fetch.
To avoid fetching all repos every 5 minutes (for each munin period) and thus
slowing down the data collection, the git fetch operation is only randomly
triggered (based on env.update.probability).
In case of very time-consuming update operations, you can run them in a
separate cron job.
=head1 REQUIREMENTS
=over 4
=item Python3
=item Git
=back
=head1 INSTALLATION
Link this plugin, as usual.
For example :
ln -s /path/to/git_commit_behind /etc/munin/plugins/git_commit_behind
If you wish to update the repositories via cron and not during the plugin
execution (cf CONFIGURATION section), you need a dedicated cron job.
For example, you can use the following cron :
# If the git_commit_behind plugin is enabled, fetch git repositories randomly
# according to the plugin configuration.
# By default : once an hour (12 invocations an hour, 1 in 12 chance that the
# update will happen), but ensure that there will never be more than two hours
# (7200 seconds) interval between updates.
*/5 * * * * root if [ -x /etc/munin/plugins/git_commit_behind ]; then /usr/sbin/munin-run git_commit_behind update >/dev/null; fi
=head1 CONFIGURATION
Use your "/etc/munin/plugin-conf.d/munin-node" to configure this plugin.
[git_commit_behind]
user [user]
env.git_path /path/to/git
env.update.mode [munin|cron]
env.update.probability 12
env.update.maxinterval 7200
user [user] : required, the owner of the repository checkouts
in case of multiple different owners, use root
env.git_path : optional (default : /usr/bin/git), the path to the git binary.
env.update.mode : optional (default : munin), the update mode.
munin : repositories are git fetched during the pugin execution
cron : a dedicated cron job needs to be used to update the repositories
env.update.probability : optional (default : 12),
runs the update randomly (1 in <probability> chances)
env.update.maxinterval : optional (default : 7200),
ensures that the update is run at least every <maxinterval> seconds
Then, for each repository you want to check, you need the following
configuration block under the git_commit_behind section:
env.repo.[repoCode].path /path/to/local/repo
env.repo.[repoCode].name Repo Name
env.repo.[repoCode].user user
env.repo.[repoCode].warning 10
env.repo.[repoCode].critical 100
[repoCode] can only contain letters, numbers and underscores.
path : mandatory, the local path to your git repository
name : optional (default : [repoCode]), a cleaner name that will be displayed
user : optional (default : empty), the owner of the repository
if set and different from the user running the plugin, the git commands
will be executed as this user
warning : optional (default 10), the warning threshold
critical : optional (default 100), the critical threshold
For example :
[git_commit_behind]
user root
env.repo.munin_contrib.path /opt/munin-contrib
env.repo.munin_contrib.name Munin Contrib
env.repo.other_repo.path /path/to/other-repo
env.repo.other_repo.name Other Repo
=head1 MAGIC MARKERS
#%# family=auto
#%# capabilities=autoconf
=head1 VERSION
1.0.0
=head1 AUTHOR
Neraud (https://github.com/Neraud)
=head1 LICENSE
GPLv2
=cut"""
import logging
import os
from pathlib import Path
import pwd
from random import randint
import re
from shlex import quote
from subprocess import check_output, call, DEVNULL, CalledProcessError
import sys
import time
plugin_version = "1.0.0"
if int(os.getenv('MUNIN_DEBUG', 0)) > 0:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelname)-7s %(message)s')
current_user = pwd.getpwuid(os.geteuid())[0]
conf = {
'git_path': os.getenv('git_path', '/usr/bin/git'),
'state_file': os.getenv('MUNIN_STATEFILE'),
'update_mode': os.getenv('update.mode', 'munin'),
'update_probability': int(os.getenv('update.probability', '12')),
'update_maxinterval': int(os.getenv('update.maxinterval', '7200'))
}
repo_codes = set(re.search('repo\.([^.]+)\..*', elem).group(1)
for elem in os.environ.keys() if elem.startswith('repo.'))
repos_conf = {}
for code in repo_codes:
repos_conf[code] = {
'name': os.getenv('repo.%s.name' % code, code),
'path': os.getenv('repo.%s.path' % code, None),
'user': os.getenv('repo.%s.user' % code, None),
'warning': os.getenv('repo.%s.warning' % code, '10'),
'critical': os.getenv('repo.%s.critical' % code, '100')
}
def print_config():
print('graph_title Git repositories - Commits behind')
print('graph_args --base 1000 -r --lower-limit 0')
print('graph_vlabel number of commits behind')
print('graph_scale yes')
print('graph_info This graph shows the number of commits behind' +
' for each configured git repository')
print('graph_category file_transfer')
print('graph_order %s' % ' '.join(repo_codes))
for repo_code in repos_conf.keys():
print('%s.label %s' % (repo_code, repos_conf[repo_code]['name']))
print('%s.warning %s' % (repo_code, repos_conf[repo_code]['warning']))
print('%s.critical %s' %
(repo_code, repos_conf[repo_code]['critical']))
def generate_git_command(repo_conf, git_command):
if not repo_conf['user'] or repo_conf['user'] == current_user:
cmd = [quote(conf['git_path'])] + git_command
else:
shell_cmd = 'cd %s ; %s %s' % (
quote(repo_conf['path']),
quote(conf['git_path']),
' '.join(git_command))
cmd = ['su', '-', repo_conf['user'], '-s', '/bin/sh', '-c', shell_cmd]
return cmd
def execute_git_command(repo_conf, git_command):
cmd = generate_git_command(repo_conf, git_command)
return check_output(cmd, cwd=repo_conf['path']).decode('utf-8').rstrip()
def print_info():
if not os.access(conf['git_path'], os.X_OK):
print('Git (%s) is missing, or not executable !' %
conf['git_path'], file=sys.stderr)
sys.exit(1)
for repo_code in repos_conf.keys():
logging.debug(' - %s' % repo_code)
try:
remote_branch = execute_git_command(
repos_conf[repo_code],
['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'])
logging.debug('remote_branch = %s' % remote_branch)
commits_behind = execute_git_command(
repos_conf[repo_code],
['rev-list', 'HEAD..%s' % remote_branch, '--count'])
print('%s.value %d' % (repo_code, int(commits_behind)))
except CalledProcessError as e:
logging.error('Error executing git command : %s', e)
except FileNotFoundError as e:
logging.error('Repo not found at path %s' %
repos_conf[repo_code]['path'])
def check_update_repos(mode):
if not conf['state_file']:
logging.error('Munin state file unavailable')
sys.exit(1)
if mode != conf['update_mode']:
logging.debug('Wrong mode, skipping')
return
if not os.path.isfile(conf['state_file']):
logging.debug('No state file -> updating')
do_update_repos()
elif (os.path.getmtime(conf['state_file']) + conf['update_maxinterval']
< time.time()):
logging.debug('State file last modified too long ago -> updating')
do_update_repos()
elif randint(1, conf['update_probability']) == 1:
logging.debug('Recent state, but random matched -> updating')
do_update_repos()
else:
logging.debug('Recent state and random missed -> skipping')
def do_update_repos():
for repo_code in repos_conf.keys():
try:
logging.info('Fetching repo %s' % repo_code)
execute_git_command(repos_conf[repo_code], ['fetch'])
except CalledProcessError as e:
logging.error('Error executing git command : %s', e)
except FileNotFoundError as e:
logging.error('Repo not found at path %s' %
repos_conf[repo_code]['path'])
logging.debug('Updating the state file')
# 'touch' the state file to update its last modified date
Path(conf['state_file']).touch()
if len(sys.argv) > 1:
action = sys.argv[1]
if action == 'config':
print_config()
elif action == 'autoconf':
errors = []
if not conf['state_file']:
errors.append('munin state file unavailable')
if os.access(conf['git_path'], os.X_OK):
test_git = call([conf['git_path'], '--version'], stdout=DEVNULL)
if test_git != 0:
errors.append('git seems to be broken ?!')
else:
errors.append('git is missing or not executable')
if errors:
print('no (%s)' % ', '.join(errors))
else:
print('yes')
elif action == 'version':
print('Git commit behind Munin plugin, version {0}'.format(
plugin_version))
elif action == 'update':
check_update_repos('cron')
else:
logging.warn("Unknown argument '%s'" % action)
sys.exit(1)
else:
if conf['update_mode'] == 'munin':
check_update_repos('munin')
print_info()
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.