Code

Reorder daemonizing (creation of PID file)
[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 if os.access(config['checkresultdir'],os.W_OK) == False:
55         print 'Checkresult directory "%s" is not writable.' % config['checkresultdir']
56         sys.exit(1)
58 users = {}
59 for u in cfgread.options('users'):
60         users[u] = cfgread.get('users', u)
62 ##############################################################################
64 class HTTP2NagiosHandler(MyHTTPRequestHandler):
66         def http_error(self, code, output):
67                 self.send_response(code)
68                 self.send_header('Content-Type', 'text/plain')
69                 self.end_headers()
70                 self.wfile.write(output)
71                 return
74         def do_GET(self):
75                 self.send_response(200)
76                 self.send_header('Content-Type', 'text/html')
77                 self.end_headers()
78                 self.wfile.write('''                    <html><body>
79                                 <form action="." method="post" enctype="multipart/form-data">
80                                 filename: <input type="file" name="xmlfile" /><br />
81                                 <input type="submit" />
82                                 </form>
83                         </body></html>
84                         ''')
85                 return
88         def do_POST(self):
89                 # Check Basic Auth
90                 try:
91                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
92                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
93                                 raise Exception
94                 except:
95                         self.send_response(401)
96                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
97                         self.send_header('Content-Type', 'text/plain')
98                         self.end_headers()
99                         self.wfile.write('Sorry! No action without login!')
100                         return
102                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
103                 if ctype == 'multipart/form-data':
104                         query = cgi.parse_multipart(self.rfile, pdict)
105                 xmltext = query.get('xmlfile')[0]
107                 if len(xmltext) > 0:
108                         doc = read_xml_from_string(xmltext)
109                         checks = xml_to_dict(doc)
111                         (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'], 0)
113                         if count_failed < count_services:
114                                 self.send_response(200)
115                                 self.send_header('Content-Type', 'text/plain')
116                                 self.end_headers()
117                                 self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
118                                 return
119                         else:
120                                 self.http_error(501, 'Could not write all %s check results' % count_services)
121                                 return
123                 else:
124                         self.http_error(502, 'Nag(IX)SC - No data received')
125                         return
129 def main():
130         if options.nossl:
131                 config['ssl'] = False
133         if config['ssl'] and not os.path.isfile(config['cert']):
134                 print 'SSL certificate "%s" not found!' % config['cert']
135                 sys.exit(127)
137         if options.daemon:
138                 daemonize(pidfile='/var/run/nagixsc_http2nagios.pid')
140         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['cert'])
141         try:
142                 server.serve_forever()
143         except:
144                 server.socket.close()
146 if __name__ == '__main__':
147         print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:15667/\n\n'
148         main()