forked from HariSekhon/Nagios-Plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_travis_ci_last_build.py
executable file
·203 lines (170 loc) · 7.38 KB
/
check_travis_ci_last_build.py
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
#!/usr/bin/env python
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2016-08-12 20:45:24 +0100 (Fri, 12 Aug 2016)
#
# https://github.com/harisekhon/nagios-plugins
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn
# and optionally send me feedback to help steer this or other code I publish
#
# https://www.linkedin.com/in/harisekhon
#
"""
Nagios Plugin to check Travis CI last build status for a given repository via the Travis API
Shows status as PASSED/FAILED for last finished build along with build number, duration in seconds
with optional --warning/--critical thresholds and build start and finished date & time.
Perfdata is output for build time for the last finished build and number of current builds in progress.
Verbose mode gives extra info including commit id, commit message, repository id and number of builds in progress
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from __future__ import unicode_literals
import json
import logging
import os
import sys
import traceback
try:
import requests
except ImportError:
print(traceback.format_exc(), end='')
sys.exit(4)
srcdir = os.path.abspath(os.path.dirname(__file__))
libdir = os.path.join(srcdir, 'pylib')
sys.path.append(libdir)
try:
# pylint: disable=wrong-import-position
from harisekhon.utils import log
from harisekhon.utils import CriticalError, UnknownError
from harisekhon.utils import validate_chars, jsonpp
from harisekhon.utils import isInt, qquit, plural, support_msg_api
from harisekhon import NagiosPlugin
except ImportError as _:
print(traceback.format_exc(), end='')
sys.exit(4)
__author__ = 'Hari Sekhon'
__version__ = '0.4'
class CheckTravisCILastBuild(NagiosPlugin):
def __init__(self):
# Python 2.x
super(CheckTravisCILastBuild, self).__init__()
# Python 3.x
# super().__init__()
self.repo = None
self.msg = "No Message Defined"
self.builds_in_progress = 0
def add_options(self):
self.add_opt('-r', '--repo',
help="Travis repo (case sensitive, in form of 'user/repo' eg. 'HariSekhon/nagios-plugins')")
self.add_thresholds()
def process_args(self):
self.no_args()
self.repo = self.get_opt('repo')
if self.repo is None:
self.usage('--repo not defined')
parts = self.repo.split('/')
if len(parts) != 2 or not parts[0] or not parts[1]:
self.usage("invalid --repo format, must be in form of 'user/repo'")
validate_chars(self.repo, 'repo', r'\/\w\.-')
self.validate_thresholds(optional=True)
def run(self):
url = 'https://api.travis-ci.org/repos/{repo}/builds'.format(repo=self.repo)
log.debug('GET %s', url)
try:
req = requests.get(url)
except requests.exceptions.RequestException as _:
raise CriticalError(_)
log.debug("response: %s %s", req.status_code, req.reason)
log.debug("content:\n%s\n%s\n%s", '='*80, req.content.strip(), '='*80)
if req.status_code != 200:
raise CriticalError("%s %s" % (req.status_code, req.reason))
if log.isEnabledFor(logging.DEBUG):
log.debug("\n{0}".format(jsonpp(req.content)))
try:
self.parse_results(req.content)
except (KeyError, ValueError) as _:
exception = traceback.format_exc().split('\n')[-2]
# this covers up the traceback info and makes it harder to debug
#raise UnknownError('failed to parse expected json response from Travis CI API: {0}'.format(exception))
qquit('UNKNOWN', 'failed to parse expected json response from Travis CI API: {0}. {1}'.
format(exception, support_msg_api()))
def get_latest_build(self, content):
build = None
builds = json.loads(content)
if not builds:
qquit('UNKNOWN', "no Travis CI builds returned by the Travis API."
+ " Either the specified repo '{0}' doesn't exist".format(self.repo)
+ " or no builds have happened yet?"
+ " Also remember the repo is case sensitive, for example 'harisekhon/nagios-plugins' returns this"
+ " blank build set whereas 'HariSekhon/nagios-plugins' succeeds"
+ " in returning latest builds information"
)
# get latest finished build
for _ in builds:
if _['state'] == 'finished':
if build is None:
build = _
else:
self.builds_in_progress += 1
if build is None:
qquit('UNKNOWN', 'no recent builds finished yet')
if log.isEnabledFor(logging.DEBUG):
log.debug("latest build:\n{0}".format(jsonpp(build)))
return build
def parse_results(self, content):
build = self.get_latest_build(content)
number = build['number']
log.info('build number = %s', number)
if not isInt(number):
raise UnknownError('build number returned is not an integer!')
message = build['message']
log.info('message = %s', message)
branch = build['branch']
log.info('branch = %s', branch)
commit = build['commit']
log.info('commit = %s', commit)
started_at = build['started_at']
log.info('started_at = %s', started_at)
finished_at = build['finished_at']
log.info('finished_at = %s', finished_at)
duration = build['duration']
log.info('duration = %s', duration)
if not isInt(duration):
raise UnknownError('duration returned is not an integer!')
repository_id = build['repository_id']
log.info('repository_id = %s', repository_id)
if not isInt(repository_id):
raise UnknownError('repository_id returned is not an integer!')
result = build['result']
log.info('result = %s', result)
state = build['state']
log.info('state = %s', state)
if result == 0:
self.ok()
status = "PASSED"
else:
self.critical()
status = "FAILED"
self.msg = "Travis CI build #{number} {status} for repo '{repo}' in {duration} secs".format(\
number=number, status=status, repo=self.repo, duration=duration)
self.check_thresholds(duration)
self.msg += ", started_at='{0}'".format(started_at)
self.msg += ", finished_at='{0}'".format(finished_at)
if self.verbose:
self.msg += ", message='{0}'".format(message)
self.msg += ", branch='{0}'".format(branch)
self.msg += ", commit='{0}'".format(commit)
self.msg += ", repository_id='{0}'".format(repository_id)
if self.verbose or self.builds_in_progress > 0:
self.msg += ", {0} build{1} in progress".format(self.builds_in_progress, plural(self.builds_in_progress))
self.msg += " | last_build_duration={duration}s{perf_thresholds} num_builds_in_progress={builds_in_progress}"\
.format(duration=duration,
perf_thresholds=self.get_perf_thresholds(),
builds_in_progress=self.builds_in_progress)
if __name__ == '__main__':
CheckTravisCILastBuild().main()