Code

FIX: write_xml_or_die always set Auth to None...
[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                         'ip': '0.0.0.0',
42                         'port': '15667',
43                         'ssl': False,
44                         'sslcert': None,
45                         'conf_dir': '',
46                         'pidfile': '/var/run/nagixsc_conf2http.pid'
47                 }
49 if 'ip' in cfgread.options('server'):
50         config['ip'] = cfgread.get('server', 'ip')
52 if 'port' in cfgread.options('server'):
53         config['port'] = cfgread.get('server', 'port')
54 try:
55         config['port'] = int(config['port'])
56 except ValueError:
57         print 'Port "%s" not an integer!' % config['port']
58         sys.exit(127)
60 if 'ssl' in cfgread.options('server'):
61         try:
62                 config['ssl'] = cfgread.getboolean('server', 'ssl')
63         except ValueError:
64                 print 'Value for "ssl" ("%s") not boolean!' % config['ssl']
65                 sys.exit(127)
67 if config['ssl']:
68         if 'sslcert' in cfgread.options('server'):
69                 config['sslcert'] = cfgread.get('server', 'sslcert')
70         else:
71                 print 'SSL but no certificate file specified!'
72                 sys.exit(127)
74 try:
75         config['mode'] = cfgread.get('server', 'mode')
76 except ConfigParser.NoOptionError:
77         print 'No "mode" specified!'
78         sys.exit(127)
80 if config['mode']=='checkresult':
81         try:
82                 config['checkresultdir'] = cfgread.get('mode_checkresult','dir')
83         except ConfigParser.NoOptionError:
84                 print 'No "dir" in section "mode_checkresult" specified!'
85                 sys.exit(127)
87         if os.access(config['checkresultdir'],os.W_OK) == False:
88                 print 'Checkresult directory "%s" is not writable!' % config['checkresultdir']
89                 sys.exit(1)
91 elif config['mode']=='passive':
92         try:
93                 config['pipe'] = cfgread.get('mode_passive','pipe')
94         except ConfigParser.NoOptionError:
95                 print 'No "pipe" in section "mode_passive" specified!'
96                 sys.exit(127)
98         if os.access(config['pipe'],os.W_OK) == False:
99                 print 'Nagios command pipe "%s" is not writable!' % config['pipe']
100                 sys.exit(1)
102 else:
103         print 'Mode "%s" is neither "checkresult" nor "passive"!'
104         sys.exit(127)
108 users = {}
109 for u in cfgread.options('users'):
110         users[u] = cfgread.get('users', u)
112 ##############################################################################
114 class HTTP2NagiosHandler(MyHTTPRequestHandler):
116         def http_error(self, code, output):
117                 self.send_response(code)
118                 self.send_header('Content-Type', 'text/plain')
119                 self.end_headers()
120                 self.wfile.write(output)
121                 return
124         def do_GET(self):
125                 self.send_response(200)
126                 self.send_header('Content-Type', 'text/html')
127                 self.end_headers()
128                 self.wfile.write('''                    <html><body>
129                                 <form action="." method="post" enctype="multipart/form-data">
130                                 filename: <input type="file" name="xmlfile" /><br />
131                                 <input type="submit" />
132                                 </form>
133                         </body></html>
134                         ''')
135                 return
138         def do_POST(self):
139                 # Check Basic Auth
140                 try:
141                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
142                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
143                                 raise Exception
144                 except:
145                         self.send_response(401)
146                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
147                         self.send_header('Content-Type', 'text/plain')
148                         self.end_headers()
149                         self.wfile.write('Sorry! No action without login!')
150                         return
152                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
153                 if ctype == 'multipart/form-data':
154                         query = cgi.parse_multipart(self.rfile, pdict)
155                 xmltext = query.get('xmlfile')[0]
157                 if len(xmltext) > 0:
158                         doc = read_xml_from_string(xmltext)
159                         checks = xml_to_dict(doc)
161                         if config['mode'] == 'checkresult':
162                                 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'])
164                                 if count_failed < count_services:
165                                         self.send_response(200)
166                                         self.send_header('Content-Type', 'text/plain')
167                                         self.end_headers()
168                                         self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
169                                         return
170                                 else:
171                                         self.http_error(501, 'Could not write all %s check results' % count_services)
172                                         return
174                         elif config['mode'] == 'passive':
175                                 count_services = dict2out_passive(checks, xml_get_timestamp(doc), config['pipe'])
177                                 self.send_response(200)
178                                 self.send_header('Content-Type', 'text/plain')
179                                 self.end_headers()
180                                 self.wfile.write('Wrote %s check results' % count_services)
181                                 return
183                 else:
184                         self.http_error(502, 'Nag(IX)SC - No data received')
185                         return
189 def main():
190         if options.nossl:
191                 config['ssl'] = False
193         if config['ssl'] and not os.path.isfile(config['sslcert']):
194                 print 'SSL certificate "%s" not found!' % config['sslcert']
195                 sys.exit(127)
197         if options.daemon:
198                 daemonize(pidfile=config['pidfile'])
199         else:
200                 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:%s/\n\n' % config['port']
202         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
203         try:
204                 server.serve_forever()
205         except:
206                 server.socket.close()
208 if __name__ == '__main__':
209         main()