1 #!/usr/bin/python
3 #import base64
4 import datetime
5 import libxml2
6 import optparse
7 import os
8 import sys
10 NAGIOSCMDs = [ '/usr/local/nagios/var/rw/nagios.cmd', '/var/lib/nagios3/rw/nagios.cmd', ]
11 CHECKRESULTDIRs = [ '/usr/local/nagios/var/spool/checkresults', '/var/lib/nagios3/spool/checkresults', ]
12 MODEs = [ 'passive', 'passive_check', 'checkresult', 'checkresult_check', 'active', ]
14 parser = optparse.OptionParser()
16 parser.add_option('-u', '', dest='url', help='URL of status file (xml)')
17 parser.add_option('-l', '', dest='httpuser', help='HTTP user name')
18 parser.add_option('-a', '', dest='httppasswd', help='HTTP password')
19 parser.add_option('-f', '', dest='file', help='(Path and) file name of status file')
20 parser.add_option('-S', '', dest='schemacheck', help='Check XML against DTD')
21 parser.add_option('-s', '', dest='seconds', type='int', help='Maximum age in seconds of xml timestamp')
22 parser.add_option('-m', '', action='store_true', dest='markold', help='Mark (Set state) of too old checks as UNKNOWN')
23 parser.add_option('-O', '', dest='mode', help='Where/Howto output the results ("%s")' % '", "'.join(MODEs))
24 parser.add_option('-p', '', dest='pipe', help='Full path to nagios.cmd')
25 parser.add_option('-r', '', dest='checkresultdir', help='Full path to checkresult directory')
26 parser.add_option('-H', '', dest='host', help='Hostname to search for in XML file')
27 parser.add_option('-D', '', dest='service', help='Service description to search for in XML file')
28 parser.add_option('-v', '', action='count', dest='verb', help='Verbose output')
30 parser.set_defaults(url=None)
31 parser.set_defaults(httpuser=None)
32 parser.set_defaults(httppasswd=None)
33 parser.set_defaults(file='nagixsc.xml')
34 parser.set_defaults(schemacheck='')
35 parser.set_defaults(seconds=14400)
36 parser.set_defaults(markold=False)
37 parser.set_defaults(mode=False)
38 parser.set_defaults(pipe=None)
39 parser.set_defaults(checkresultdir=None)
40 parser.set_defaults(host=None)
41 parser.set_defaults(service=None)
42 parser.set_defaults(verb=0)
44 (options, args) = parser.parse_args()
46 ##############################################################################
48 from nagixsc import *
50 ##############################################################################
52 if options.mode not in MODEs:
53 print 'Not an allowed mode "%s" - allowed are: "%s"' % (options.mode, '", "'.join(MODEs))
54 sys.exit(127)
56 # Check command line options wrt mode
57 if options.mode == 'passive' or options.mode == 'passive_check':
58 debug(1, options.verb, 'Running in passive mode')
59 if options.pipe == None and options.verb <= 2:
60 for nagioscmd in NAGIOSCMDs:
61 if os.path.exists(nagioscmd):
62 options.pipe = nagioscmd
64 if options.pipe == None and options.verb <= 2:
65 print 'Need full path to the nagios.cmd pipe!'
66 sys.exit(127)
68 debug(2, options.verb, 'nagios.cmd found at %s' % options.pipe)
70 elif options.mode == 'checkresult' or options.mode == 'checkresult_check':
71 debug(1, options.verb, 'Running in checkresult mode')
72 if options.checkresultdir == None and options.verb <= 2:
73 for crd in CHECKRESULTDIRs:
74 if os.path.exists(crd):
75 options.checkresultdir = crd
77 if options.checkresultdir == None and options.verb <= 2:
78 print 'Need full path to the checkresultdir!'
79 sys.exit(127)
81 debug(2, options.verb, 'Checkresult dir: %s' % options.checkresultdir)
83 elif options.mode == 'active':
84 debug(1, options.verb, 'Running in active/plugin mode')
85 if options.host == None:
86 debug(1, options.verb, 'No host specified on command line')
87 if options.service == None:
88 debug(1, options.verb, 'No service specified on command line, looking at XML file later')
90 ##############################################################################
92 # Get URL or file
93 doc = read_xml(options)
95 # Now timestamp AFTER getting the XML file
96 now = int(datetime.datetime.now().strftime('%s'))
99 # Check XML against DTD
100 if options.schemacheck:
101 dtd = libxml2.parseDTD(None, options.schemacheck)
102 ctxt = libxml2.newValidCtxt()
103 ret = doc.validateDtd(ctxt, dtd)
104 if ret != 1:
105 print "error doing DTD validation"
106 sys.exit(1)
107 dtd.freeDtd()
108 del dtd
109 del ctxt
112 # Check XML file basics
113 (status, statusstring) = xml_check_version(doc)
114 debug(1, options.verb, statusstring)
115 if not status:
116 print statusstring
117 sys.exit(127)
120 # Get timestamp and check it
121 filetimestamp = xml_get_timestamp(doc)
122 if not filetimestamp:
123 print 'No timestamp found in XML file, exiting because of invalid XML data...'
124 sys.exit(127)
126 timedelta = int(now) - int(filetimestamp)
127 debug(1, options.verb, 'Age of XML file: %s seconds, max allowed: %s seconds' % (timedelta, options.seconds))
130 # Put XML to Python dict
131 checks = xml_to_dict(doc, options.verb, options.host, options.service)
133 # Loop over check results and perhaps mark them as outdated
134 for check in checks:
135 check = check_mark_outdated(check, now, options.seconds, options.markold)
138 # Next steps depend on mode, output results
139 # MODE: passive
140 if options.mode == 'passive' or options.mode == 'passive_check':
141 count_services = dict2out_passive(checks, xml_get_timestamp(doc), options.pipe, options.verb)
143 # Return/Exit as a Nagios Plugin if called with mode 'passive_check'
144 if options.mode == 'passive_check':
145 returncode = 0
146 returnstring = 'OK'
147 output = '%s check results written which are %s seconds old' % (count_services, (now-filetimestamp))
149 if options.markold:
150 if (now - filetimestamp) > options.seconds:
151 returnstring = 'WARNING'
152 output = '%s check results written, which are %s(>%s) seconds old' % (count_services, (now-filetimestamp), options.seconds)
153 returncode = 1
155 print 'Nag(ix)SC %s - %s' % (returnstring, output)
156 sys.exit(returncode)
158 # MODE: checkresult: "checkresult", "checkresult_check"
159 elif options.mode.startswith('checkresult'):
160 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), options.checkresultdir, options.verb)
162 if options.mode == 'checkresult':
163 if list_failed:
164 for entry in list_failed:
165 print 'Could not write checkresult files "%s(.ok)" for "%s"/"%s"!' % (entry[0], entry[1], entry[2])
167 if count_failed == 0:
168 sys.exit(0)
169 else:
170 sys.exit(1)
172 elif options.mode == 'checkresult_check':
173 returnstring = ''
174 output = ''
175 if count_failed == 0:
176 returnstring = 'OK'
177 returncode = 0
178 output = 'Wrote checkresult files for %s services' % count_services
179 elif count_failed == count_services:
180 returnstring = 'CRITICAL'
181 returncode = 2
182 output = 'No checkresult files could be writen!'
183 else:
184 returnstring = 'WARNING'
185 returncode = 1
186 output = 'Could not write %s out of %s checkresult files!' % (count_failed, count_services)
188 print 'Nag(ix)SC %s - %s' % (returnstring, output)
189 sys.exit(returncode)
191 # MODE: active
192 elif options.mode == 'active':
194 if len(checks) > 1:
195 print 'Nag(ix)SC UNKNOWN - Found more (%s) than one host/service!' % len(checks)
196 print 'Found: ' + ', '.join(['%s/%s' % (c['host_name'], c['service_description']) for c in checks])
197 sys.exit(3)
198 elif len(checks) == 0:
199 output = 'Nag(ix)SC UNKNOWN - No check found in XML'
200 if options.host:
201 output += ' - Host filter: "%s"' % options.host
202 if options.service:
203 output += ' - Service filter: "%s"' % options.service
204 print output
205 sys.exit(3)
207 print checks[0]['output']
208 sys.exit(int(checks[0]['returncode']))
210 else:
211 print 'Unknown mode! This should NEVER happen!'
212 sys.exit(127)