Code

Add function to merge multiple XML files
[nagixsc.git] / nagixsc_http2nagios.py
1 #!/usr/bin/python
3 import ConfigParser
4 import base64
5 import cgi
6 import optparse
7 import os
8 import re
9 import sys
11 try:
12         from hashlib import md5
13 except ImportError:
14         from md5 import md5
16 ##############################################################################
18 from nagixsc import *
20 ##############################################################################
22 parser = optparse.OptionParser()
24 parser.add_option('-c', '', dest='cfgfile', help='Config file')
25 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
26 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
28 parser.set_defaults(cfgfile='http2nagios.cfg')
30 (options, args) = parser.parse_args()
32 cfgread = ConfigParser.SafeConfigParser()
33 cfgread.optionxform = str # We need case-sensitive options
34 cfg_list = cfgread.read(options.cfgfile)
36 if cfg_list == []:
37         print 'Config file "%s" could not be read!' % options.cfgfile
38         sys.exit(1)
40 config = {}
41 try:
42         config['ip']   = cfgread.get('server', 'ip')
43         config['port'] = cfgread.getint('server', 'port')
44         config['ssl']  = cfgread.getboolean('server', 'ssl')
45         config['cert'] = cfgread.get('server', 'sslcert')
47         config['max_xml_file_size']  = cfgread.get('server', 'max_xml_file_size')
48         config['checkresultdir'] = cfgread.get('mode_checkresult', 'dir')
50 except ConfigParser.NoOptionError, e:
51         print 'Config file error: %s ' % e
52         sys.exit(1)
54 users = {}
55 for u in cfgread.options('users'):
56         users[u] = cfgread.get('users', u)
58 ##############################################################################
60 class HTTP2NagiosHandler(MyHTTPRequestHandler):
62         def http_error(self, code, output):
63                 self.send_response(code)
64                 self.send_header('Content-Type', 'text/plain')
65                 self.end_headers()
66                 self.wfile.write(output)
67                 return
70         def do_GET(self):
71                 self.send_response(200)
72                 self.send_header('Content-Type', 'text/html')
73                 self.end_headers()
74                 self.wfile.write('''                    <html><body>
75                                 <form action="." method="post" enctype="multipart/form-data">
76                                 filename: <input type="file" name="xmlfile" /><br />
77                                 <input type="submit" />
78                                 </form>
79                         </body></html>
80                         ''')
81                 return
84         def do_POST(self):
85                 # Check Basic Auth
86                 try:
87                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
88                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
89                                 raise Exception
90                 except:
91                         self.send_response(401)
92                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
93                         self.send_header('Content-Type', 'text/plain')
94                         self.end_headers()
95                         self.wfile.write('Sorry! No action without login!')
96                         return
98                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
99                 if ctype == 'multipart/form-data':
100                         query = cgi.parse_multipart(self.rfile, pdict)
101                 xmltext = query.get('xmlfile')[0]
103                 if len(xmltext) > 0:
104                         doc = read_xml_from_string(xmltext)
105                         checks = xml_to_dict(doc)
107                         (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'], 0)
109                         if count_failed < count_services:
110                                 self.send_response(200)
111                                 self.send_header('Content-Type', 'text/plain')
112                                 self.end_headers()
113                                 self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
114                                 return
115                         else:
116                                 self.http_error(501, 'Could not write all %s check results' % count_services)
117                                 return
119                 else:
120                         self.http_error(502, 'Nag(IX)SC - No data received')
121                         return
125 def main():
126         if options.nossl:
127                 config['ssl'] = False
129         if config['ssl'] and not os.path.isfile(config['cert']):
130                 print 'SSL certificate "%s" not found!' % config['cert']
131                 sys.exit(127)
133         if options.daemon:
134                 daemonize(pidfile='/var/run/nagixsc_http2nagios.pid')
136         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['cert'])
137         try:
138                 server.serve_forever()
139         except:
140                 server.socket.close()
142 if __name__ == '__main__':
143         print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:15667/\n\n'
144         main()