Code

obsses: Debug output, typo
[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                         'acl': False,
48                 }
50 if 'ip' in cfgread.options('server'):
51         config['ip'] = cfgread.get('server', 'ip')
53 if 'port' in cfgread.options('server'):
54         config['port'] = cfgread.get('server', 'port')
55 try:
56         config['port'] = int(config['port'])
57 except ValueError:
58         print 'Port "%s" not an integer!' % config['port']
59         sys.exit(127)
61 if 'ssl' in cfgread.options('server'):
62         try:
63                 config['ssl'] = cfgread.getboolean('server', 'ssl')
64         except ValueError:
65                 print 'Value for "ssl" ("%s") not boolean!' % cfgread.get('server', 'ssl')
66                 sys.exit(127)
68 if config['ssl']:
69         if 'sslcert' in cfgread.options('server'):
70                 config['sslcert'] = cfgread.get('server', 'sslcert')
71         else:
72                 print 'SSL but no certificate file specified!'
73                 sys.exit(127)
75 try:
76         config['mode'] = cfgread.get('server', 'mode')
77 except ConfigParser.NoOptionError:
78         print 'No "mode" specified!'
79         sys.exit(127)
81 if config['mode']=='checkresult':
82         try:
83                 config['checkresultdir'] = cfgread.get('mode_checkresult','dir')
84         except ConfigParser.NoOptionError:
85                 print 'No "dir" in section "mode_checkresult" specified!'
86                 sys.exit(127)
88         if os.access(config['checkresultdir'],os.W_OK) == False:
89                 print 'Checkresult directory "%s" is not writable!' % config['checkresultdir']
90                 sys.exit(1)
92 elif config['mode']=='passive':
93         try:
94                 config['pipe'] = cfgread.get('mode_passive','pipe')
95         except ConfigParser.NoOptionError:
96                 print 'No "pipe" in section "mode_passive" specified!'
97                 sys.exit(127)
99         if os.access(config['pipe'],os.W_OK) == False:
100                 print 'Nagios command pipe "%s" is not writable!' % config['pipe']
101                 sys.exit(1)
103 else:
104         print 'Mode "%s" is neither "checkresult" nor "passive"!'
105         sys.exit(127)
107 acls = { 'a_hl':{}, 'a_hr':{}, }
108 if 'acl' in cfgread.options('server'):
109         try:
110                 config['acl'] = cfgread.getboolean('server', 'acl')
111         except ValueError:
112                 print 'Value for "acl" ("%s") not boolean!' % cfgread.get('server', 'acl')
113                 sys.exit(127)
114 if config['acl']:
115         if cfgread.has_section('acl_allowed_hosts_list'):
116                 for user in cfgread.options('acl_allowed_hosts_list'):
117                         acls['a_hl'][user] = [ah.lstrip().rstrip() for ah in cfgread.get('acl_allowed_hosts_list',user).split(',')]
118         if cfgread.has_section('acl_allowed_hosts_re'):
119                 for user in cfgread.options('acl_allowed_hosts_re'):
120                         acls['a_hr'][user] = re.compile(cfgread.get('acl_allowed_hosts_re',user))
124 users = {}
125 for u in cfgread.options('users'):
126         users[u] = cfgread.get('users', u)
128 ##############################################################################
130 class HTTP2NagiosHandler(MyHTTPRequestHandler):
132         def http_error(self, code, output):
133                 self.send_response(code)
134                 self.send_header('Content-Type', 'text/plain')
135                 self.end_headers()
136                 self.wfile.write(output)
137                 return
140         def do_GET(self):
141                 self.send_response(200)
142                 self.send_header('Content-Type', 'text/html')
143                 self.end_headers()
144                 self.wfile.write('''                    <html><body>
145                                 <form action="." method="post" enctype="multipart/form-data">
146                                 filename: <input type="file" name="xmlfile" /><br />
147                                 <input type="submit" />
148                                 </form>
149                         </body></html>
150                         ''')
151                 return
154         def do_POST(self):
155                 # Check Basic Auth
156                 try:
157                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
158                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
159                                 raise Exception
160                 except:
161                         self.send_response(401)
162                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
163                         self.send_header('Content-Type', 'text/plain')
164                         self.end_headers()
165                         self.wfile.write('Sorry! No action without login!')
166                         return
168                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
169                 if ctype == 'multipart/form-data':
170                         query = cgi.parse_multipart(self.rfile, pdict)
171                 xmltext = query.get('xmlfile')[0]
173                 if len(xmltext) > 0:
174                         doc = read_xml_from_string(xmltext)
175                         checks = xml_to_dict(doc)
177                         if config['acl']:
178                                 new_checks = []
179                                 for check in checks:
180                                         if authdata[0] in acls['a_hl'] and check['host_name'] in acls['a_hl'][authdata[0]]:
181                                                 new_checks.append(check)
182                                         elif authdata[0] in acls['a_hr'] and (acls['a_hr'][authdata[0]]).search(check['host_name']):
183                                                 new_checks.append(check)
185                                 count_acl_failed = len(checks) - len(new_checks)
186                                 checks = new_checks
187                         else:
188                                 count_acl_failed = None
190                         if config['mode'] == 'checkresult':
191                                 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'])
193                                 if count_failed < count_services:
194                                         self.send_response(200)
195                                         self.send_header('Content-Type', 'text/plain')
196                                         self.end_headers()
197                                         statusmsg = 'Wrote %s check results, %s failed' % (count_services, count_failed)
198                                         if count_acl_failed != None:
199                                                 statusmsg += ' - %s check results failed ACL check' % count_acl_failed
200                                         self.wfile.write(statusmsg)
201                                         return
202                                 else:
203                                         self.http_error(501, 'Could not write all %s check results' % count_services)
204                                         return
206                         elif config['mode'] == 'passive':
207                                 count_services = dict2out_passive(checks, xml_get_timestamp(doc), config['pipe'])
209                                 self.send_response(200)
210                                 self.send_header('Content-Type', 'text/plain')
211                                 self.end_headers()
212                                 self.wfile.write('Wrote %s check results' % count_services)
213                                 return
215                 else:
216                         self.http_error(502, 'Nag(IX)SC - No data received')
217                         return
221 def main():
222         if options.nossl:
223                 config['ssl'] = False
225         if config['ssl'] and not os.path.isfile(config['sslcert']):
226                 print 'SSL certificate "%s" not found!' % config['sslcert']
227                 sys.exit(127)
229         if options.daemon:
230                 daemonize(pidfile=config['pidfile'])
231         else:
232                 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:%s/\n\n' % config['port']
234         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
235         try:
236                 server.serve_forever()
237         except:
238                 server.socket.close()
240 if __name__ == '__main__':
241         main()