Code

WIP: PoC of "http2nagios" / rename "cgi"->"http"
[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 random
9 import string
10 import sys
12 NAGIOSCMDs = [ '/usr/local/nagios/var/rw/nagios.cmd', '/var/lib/nagios3/rw/nagios.cmd', ]
13 CHECKRESULTDIRs = [ '/usr/local/nagios/var/spool/checkresults', '/var/lib/nagios3/spool/checkresults', ]
14 MODEs = [ 'passive', 'passive_check', 'checkresult', 'checkresult_check', 'active', ]
16 parser = optparse.OptionParser()
18 parser.add_option('-u', '', dest='url', help='URL of status file (xml)')
19 parser.add_option('-l', '', dest='httpuser', help='HTTP user name')
20 parser.add_option('-a', '', dest='httppasswd', help='HTTP password')
21 parser.add_option('-f', '', dest='file', help='(Path and) file name of status file')
22 parser.add_option('-S', '', dest='schemacheck', help='Check XML against DTD')
23 parser.add_option('-s', '', dest='seconds', type='int', help='Maximum age in seconds of xml timestamp')
24 parser.add_option('-m', '', action='store_true', dest='markold', help='Mark (Set state) of too old checks as UNKNOWN')
25 parser.add_option('-O', '', dest='mode', help='Where/Howto output the results ("%s")' % '", "'.join(MODEs))
26 parser.add_option('-p', '', dest='pipe', help='Full path to nagios.cmd')
27 parser.add_option('-r', '', dest='checkresultdir', help='Full path to checkresult directory')
28 parser.add_option('-H', '', dest='host', help='Hostname to search for in XML file')
29 parser.add_option('-D', '', dest='service', help='Service description to search for in XML file')
30 parser.add_option('-v', '', action='count', dest='verb', help='Verbose output')
32 parser.set_defaults(url=None)
33 parser.set_defaults(httpuser=None)
34 parser.set_defaults(httppasswd=None)
35 parser.set_defaults(file='nagixsc.xml')
36 parser.set_defaults(schemacheck='')
37 parser.set_defaults(seconds=14400)
38 parser.set_defaults(markold=False)
39 parser.set_defaults(mode=False)
40 parser.set_defaults(pipe=None)
41 parser.set_defaults(checkresultdir=None)
42 parser.set_defaults(host=None)
43 parser.set_defaults(service=None)
44 parser.set_defaults(verb=0)
46 (options, args) = parser.parse_args()
48 ##############################################################################
50 from nagixsc import *
52 ##############################################################################
54 if options.mode not in MODEs:
55         print 'Not an allowed mode "%s" - allowed are: %s' % (options.mode, ", ".join(MODEs))
56         sys.exit(127)
58 # Check command line options wrt mode
59 if options.mode == 'passive' or options.mode == 'passive_check':
60         debug(1, options.verb, 'Running in passive mode')
61         if options.pipe == None and options.verb <= 2:
62                 for nagioscmd in NAGIOSCMDs:
63                         if os.path.exists(nagioscmd):
64                                 options.pipe = nagioscmd
66         if options.pipe == None and options.verb <= 2:
67                 print 'Need full path to the nagios.cmd pipe!'
68                 sys.exit(127)
70         debug(2, options.verb, 'nagios.cmd found at %s' % options.pipe)
72 elif options.mode == 'checkresult' or options.mode == 'checkresult_check':
73         debug(1, options.verb, 'Running in checkresult mode')
74         if options.checkresultdir == None and options.verb <= 2:
75                 for crd in CHECKRESULTDIRs:
76                         if os.path.exists(crd):
77                                 options.checkresultdir = crd
79         if options.checkresultdir == None and options.verb <= 2:
80                 print 'Need full path to the checkresultdir!'
81                 sys.exit(127)
83         debug(2, options.verb, 'Checkresult dir: %s' % options.checkresultdir)
85 elif options.mode == 'active':
86         debug(1, options.verb, 'Running in active/plugin mode')
87         if options.host == None:
88                 debug(1, options.verb, 'No host specified, using first host in XML file')
89         if options.service == None:
90                 print 'No service specified on command line!'
91                 sys.exit(127)
93 ##############################################################################
95 now = int(datetime.datetime.now().strftime('%s'))
97 # Get URL or file
98 doc = read_xml(options)
101 # Check XML against DTD
102 if options.schemacheck:
103         dtd = libxml2.parseDTD(None, options.schemacheck)
104         ctxt = libxml2.newValidCtxt()
105         ret = doc.validateDtd(ctxt, dtd)
106         if ret != 1:
107                 print "error doing DTD validation"
108                 sys.exit(1)
109         dtd.freeDtd()
110         del dtd
111         del ctxt
114 # Check XML file basics
115 (status, statusstring) = xml_check_version(doc)
116 debug(1, options.verb, statusstring)
117 if not status:
118         print statusstring
119         sys.exit(127)
122 # Get timestamp and check it
123 filetimestamp = xml_get_timestamp(doc)
124 if not filetimestamp:
125         print 'No timestamp found in XML file, exiting because of invalid XML data...'
126         sys.exit(127)
128 timedelta = int(now) - int(filetimestamp)
129 debug(1, options.verb, 'Age of XML file: %s seconds, max allowed: %s seconds' % (timedelta, options.seconds))
132 # Put XML to Python dict
133 checks = xml_to_dict(doc, options.verb, options.host, options.service)
135 # Loop over check results and perhaps mark them as outdated
136 for check in checks:
137         check = check_mark_outdated(check, now, options.seconds, options.markold)
140 # Next steps depend on mode, output results
141 # MODE: passive
142 if options.mode == 'passive' or options.mode == 'passive_check':
143         count_services = 0
144         # Prepare
145         if options.verb <= 2:
146                 pipe = open(options.pipe, "w")
147         else:
148                 pipe = None
150         # Output
151         for check in checks:
152                 count_services += 1
153                 if check['service_description'] == None or check['service_description'] == '':
154                         # Host check
155                         line = '[%s] PROCESS_HOST_CHECK_RESULT;%s;%s;%s' % (now, check['host_name'], check['returncode'], check['output'].replace('\n', '\\n'))
156                 else:
157                         # Service check
158                         line = '[%s] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s;%s' % (now, check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n'))
160                 if pipe:
161                         pipe.write(line + '\n')
162                 debug(2, options.verb, '%s / %s: %s - "%s"' % (check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n')))
163                 debug(3, options.verb, line)
165         # Close
166         if pipe:
167                 pipe.close()
168         else:
169                 print "Passive check results NOT written to Nagios pipe due to -vvv!"
171         # Return/Exit as a Nagios Plugin if called with mode 'passive_check'
172         if options.mode == 'passive_check':
173                 returncode   = 0
174                 returnstring = 'OK'
175                 output       = ''
177                 if options.markold:
178                         if (now - filetimestamp) > options.seconds:
179                                 returnstring = 'WARNING'
180                                 output = '%s check results written, which are %s(>%s) seconds old' % (count_services, (now-filetimestamp), options.seconds)
181                                 returncode = 1
183                 if not output:
184                         output = '%s check results written which are %s seconds old' % (count_services, (now-filetimestamp))
186                 print 'Nag(ix)SC %s - %s' % (returnstring, output)
187                 sys.exit(returncode)
189 # MODE: checkresult
190 elif options.mode == 'checkresult' or options.mode == 'checkresult_check':
191         count_services = 0
192         count_failed   = 0
194         chars = string.letters + string.digits
196         for check in checks:
197                 count_services += 1
198                 if check.has_key('timestamp'):
199                         timestamp = check['timestamp']
200                 else:
201                         timestamp = xml_get_timestamp(xmldoc)
203                 filename = os.path.join(options.checkresultdir, 'c' + ''.join([random.choice(chars) for i in range(6)]))
204                 try:
205                         crfile = open(filename, "w")
206                         if check['service_description'] == None or check['service_description'] == '':
207                                 # Host check
208                                 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, datetime.datetime.now().ctime(), check['host_name'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
209                         else:
210                                 # Service check
211                                 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\nservice_description=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, datetime.datetime.now().ctime(), check['host_name'], check['service_description'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
212                         crfile.close()
214                         # Create OK file
215                         open(filename + '.ok', 'w').close()
216                 except:
217                         count_failed += 1
218                         if options.mode == 'checkresult':
219                                 print 'Could not write checkresult files "%s(.ok)" for "%s"/"%s"!' % (filename, check['host_name'], check['service_description'])
221         if options.mode == 'checkresult_check':
222                 returnstring = ''
223                 output       = ''
224                 if count_failed == 0:
225                         returnstring = 'OK'
226                         returncode   = 0
227                         output       = 'Wrote checkresult files for %s services' % count_services
228                 elif count_failed == count_services:
229                         returnstring = 'CRITICAL'
230                         returncode   = 2
231                         output       = 'No checkresult files could be writen!'
232                 else:
233                         returnstring = 'WARNING'
234                         returncode   = 1
235                         output       = 'Could not write %s out of %s checkresult files!' % (count_failed, count_services)
237                 print 'Nag(ix)SC %s - %s' % (returnstring, output)
238                 sys.exit(returncode)
240         if count_failed == 0:
241                 sys.exit(0)
242         else:
243                 sys.exit(1)
245 # MODE: active
246 elif options.mode == 'active':
248         if len(checks) > 1:
249                 print 'Nag(ix)SC UNKNOWN - Found more (%s) than one host/service!' % len(checks)
250                 sys.exit(3)
251         elif len(checks) == 0:
252                 print 'Nag(ix)SC UNKNOWN - No check for "%s"/"%s" found in XML' % (options.host, options.service)
253                 sys.exit(3)
255         print checks[0]['output']
256         sys.exit(int(checks[0]['returncode']))
258 else:
259         print 'Unknown mode! This should NEVER happen!'
260         sys.exit(127)