Code

Disable SSL in sample-configs/*.cfg
[nagixsc.git] / nagixsc_xml2nagios.py
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, using first host in XML file')
87         if options.service == None:
88                 print 'No service specified on command line!'
89                 sys.exit(127)
91 ##############################################################################
93 # Get URL or file
94 doc = read_xml(options)
96 # Now timestamp AFTER getting the XML file
97 now = int(datetime.datetime.now().strftime('%s'))
100 # Check XML against DTD
101 if options.schemacheck:
102         dtd = libxml2.parseDTD(None, options.schemacheck)
103         ctxt = libxml2.newValidCtxt()
104         ret = doc.validateDtd(ctxt, dtd)
105         if ret != 1:
106                 print "error doing DTD validation"
107                 sys.exit(1)
108         dtd.freeDtd()
109         del dtd
110         del ctxt
113 # Check XML file basics
114 (status, statusstring) = xml_check_version(doc)
115 debug(1, options.verb, statusstring)
116 if not status:
117         print statusstring
118         sys.exit(127)
121 # Get timestamp and check it
122 filetimestamp = xml_get_timestamp(doc)
123 if not filetimestamp:
124         print 'No timestamp found in XML file, exiting because of invalid XML data...'
125         sys.exit(127)
127 timedelta = int(now) - int(filetimestamp)
128 debug(1, options.verb, 'Age of XML file: %s seconds, max allowed: %s seconds' % (timedelta, options.seconds))
131 # Put XML to Python dict
132 checks = xml_to_dict(doc, options.verb, options.host, options.service)
134 # Loop over check results and perhaps mark them as outdated
135 for check in checks:
136         check = check_mark_outdated(check, now, options.seconds, options.markold)
139 # Next steps depend on mode, output results
140 # MODE: passive
141 if options.mode == 'passive' or options.mode == 'passive_check':
142         count_services = dict2out_passive(checks, xml_get_timestamp(doc), options.pipe, options.verb)
144         # Return/Exit as a Nagios Plugin if called with mode 'passive_check'
145         if options.mode == 'passive_check':
146                 returncode   = 0
147                 returnstring = 'OK'
148                 output       = '%s check results written which are %s seconds old' % (count_services, (now-filetimestamp))
150                 if options.markold:
151                         if (now - filetimestamp) > options.seconds:
152                                 returnstring = 'WARNING'
153                                 output = '%s check results written, which are %s(>%s) seconds old' % (count_services, (now-filetimestamp), options.seconds)
154                                 returncode = 1
156                 print 'Nag(ix)SC %s - %s' % (returnstring, output)
157                 sys.exit(returncode)
159 # MODE: checkresult: "checkresult", "checkresult_check"
160 elif options.mode.startswith('checkresult'):
161         (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), options.checkresultdir, options.verb)
163         if options.mode == 'checkresult':
164                 if list_failed:
165                         for entry in list_failed:
166                                 print 'Could not write checkresult files "%s(.ok)" for "%s"/"%s"!' % (entry[0], entry[1], entry[2])
168                 if count_failed == 0:
169                         sys.exit(0)
170                 else:
171                         sys.exit(1)
173         elif options.mode == 'checkresult_check':
174                 returnstring = ''
175                 output       = ''
176                 if count_failed == 0:
177                         returnstring = 'OK'
178                         returncode   = 0
179                         output       = 'Wrote checkresult files for %s services' % count_services
180                 elif count_failed == count_services:
181                         returnstring = 'CRITICAL'
182                         returncode   = 2
183                         output       = 'No checkresult files could be writen!'
184                 else:
185                         returnstring = 'WARNING'
186                         returncode   = 1
187                         output       = 'Could not write %s out of %s checkresult files!' % (count_failed, count_services)
189                 print 'Nag(ix)SC %s - %s' % (returnstring, output)
190                 sys.exit(returncode)
192 # MODE: active
193 elif options.mode == 'active':
195         if len(checks) > 1:
196                 print 'Nag(ix)SC UNKNOWN - Found more (%s) than one host/service!' % len(checks)
197                 sys.exit(3)
198         elif len(checks) == 0:
199                 print 'Nag(ix)SC UNKNOWN - No check for "%s"/"%s" found in XML' % (options.host, options.service)
200                 sys.exit(3)
202         print checks[0]['output']
203         sys.exit(int(checks[0]['returncode']))
205 else:
206         print 'Unknown mode! This should NEVER happen!'
207         sys.exit(127)