-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_twill
executable file
·223 lines (183 loc) · 8.4 KB
/
check_twill
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
#!/usr/bin/python
"""
check_twill a monitoring plugin for stepping through a website
check_twill Copyright (C) 2015
BASED ON: check_twill, Copyright 2009 Jesse Morgan, Michael Isiminger
BASED ON: check_twill, Copyright 2006 Duncan McGreggor
check_twill
This file is part of the morgnagplug package.
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
NOTE: you can get install all of the requirements via
pip install twill==0.9.1
"""
PROG_VERSION = "1.4"
NAGIOS_STATE = {'OK':0, 'WARNING':1, 'CRITICAL':2, 'UNKNOWN':3}
import argparse
from cStringIO import StringIO
from datetime import datetime
import signal
import sys
from twill import commands, parse, __version__, namespaces, set_output, set_errout
from twill.errors import TwillAssertionError
def configure_parser():
""" This configures all of the arguments available. """
help_text = """
check_twill is a nagios-compatible monitoring plugin that is designed to be a
simple method to funtionally test websites. Please see http://twill.idyll.org
for details on the twill language syntax.
"""
parser = argparse.ArgumentParser(description=help_text, version=PROG_VERSION)
parser.add_argument('-d', '--debug', action="store_true", default=False,
help="Shows details for command-line debugging (may be truncated by monitoring software)'")
parser.add_argument('-w', '--warn', action="store", type=float,
help="How long (in seconds) to wait before setting the state to WARNING")
parser.add_argument('-c', '--crit', action="store", type=float,
help="How long (in seconds) to wait before setting the state to CRITICAL")
parser.add_argument('-t', '--timeout', action="store", type=int, default=30,
help="How long (in seconds) to wait for a response before timing out")
parser.add_argument('--timeout-state', action="store", default='UNKNOWN', choices=NAGIOS_STATE.keys(),
help="What state to use should it timeout: OK, WARNING, CRITICAL, or UNKNOWN(default)")
parser.add_argument('-n', '--never-fail', action="store_true", default=False,
help="Continue on even if there are failures.")
parser.add_argument("script")
return parser.parse_args()
class TimeoutError(Exception):
""" This class is used to differentiate when the script Times out."""
pass
def timeout_signal(signum, stack):
""" The Timeout will only be raised if the script takes too long. """
raise TimeoutError()
def perfdata(args, timetotal):
"""
Performance data consists of the following format:
| 'label'=value[UOM];[warn];[crit];[min];[max]
By default we leave warnings and criticals empty, the min at 0, and the max at the timeout value.
"""
if args.warn == None:
args.warn = ''
if args.crit == None:
args.crit = ''
return "|'time'={0}s;{1};{2};0;{3}".format(timetotal, args.warn, args.crit, args.timeout)
def _execute_script(inp, **kw):
"""
This method is cloned from twill's parse library to add
more error details and remove useless output.
"""
# initialize new local dictionary & get global + current local
namespaces.new_local_dict()
globals_dict, locals_dict = namespaces.get_twill_glocals()
locals_dict['__url__'] = commands.browser.get_url()
# reset browser
if not kw.get('no_reset'):
commands.reset_browser()
# go to a specific URL?
init_url = kw.get('initial_url')
if init_url:
commands.go(init_url)
locals_dict['__url__'] = commands.browser.get_url()
# should we catch exceptions on failure?
catch_errors = False
if kw.get('never_fail'):
catch_errors = True
# sourceinfo stuff
sourceinfo = kw.get('source', "<input>")
try:
current_url = ''
for n, line in enumerate(inp):
if not line.strip(): # skip empty lines
continue
cmdinfo = "%s:%d" % (sourceinfo, n)
cmd, args = parse.parse_command(line, globals_dict, locals_dict)
if cmd is None:
continue
try:
result = parse.execute_command(cmd, args, globals_dict, locals_dict, cmdinfo)
if result is not None:
current_url = result
except TimeoutError, exc:
# Catch and rethrow my signal timeout around the catchall below so it can be processed.
raise exc
except Exception, exc:
# catching ALL exceptions, not just Twill exceptions because a connection
# refused would break the script
error_msg = "[%s] on line %s of %s at %s " %(exc, n, sourceinfo, current_url)
if not catch_errors:
raise TwillAssertionError(error_msg)
finally:
namespaces.pop_local_dict()
# This allows us to replace the original _execute_script with our own.
# We do this to get around the invalid output.
parse._execute_script = _execute_script
def main():
"""
This is the core check of the script. It executes the file,
catches exceptions, and parses the output.
"""
args = configure_parser()
# these two StringIO allow us to buffer output for display after
# our status line (if we have debug mode enabled)
errormessage = StringIO()
output = StringIO()
try:
# Set up our timeout signalling
signal.signal(signal.SIGALRM, timeout_signal)
signal.alarm(args.timeout)
# Let's set our outputs to the side...
set_output(output)
set_errout(errormessage)
# Call twill.parser's execute file, which *should* call our _execute_file above.
start_time = datetime.now()
parse.execute_file(args.script, never_fail=args.never_fail)
end_time = datetime.now()
# ... And then return outputs to normal
set_output(None)
set_errout(None)
# Using our start_time and end_time, we can calculate the
# delta to figure out how long it actually took.
delta = end_time - start_time
total_time = delta.seconds + delta.microseconds/1000000.0
if args.crit != None and total_time > args.crit:
message = "All steps completed successfully, but not in time."
state = 'CRITICAL'
elif args.warn != None and total_time > args.warn:
message = "All steps completed successfully, but not in time."
state = 'WARNING'
else:
message = "All steps completed successfully."
state = 'OK'
message += " Total Runtime: {0}s ".format(total_time) + perfdata(args, total_time)
except TimeoutError, exc:
# If our Signal alarm is triggered for taking too long, this will be executed.
end_time = datetime.now()
delta = end_time - start_time
total_time = delta.seconds + delta.microseconds/1000000.0
message = "Script timeout after {0}s".format(args.timeout) + perfdata(args, total_time)
state = args.timeout_state
except TwillAssertionError, exc:
message = "Assertion Failure: %s " % exc
state = 'CRITICAL'
except Exception, exc:
message = "Unknown exception: '%s'" % exc
state = 'UNKNOWN'
finally:
print "TWILL {0}: {1}".format(state, message)
if args.debug:
print output.getvalue()
print errormessage.getvalue()
sys.exit(NAGIOS_STATE[state])
main()