Code

Changed license to GPL-2+ (from GPL-2only).
[nagixsc.git] / nagixsc_http2nagios.py
1 #!/usr/bin/python
2 #
3 # Nag(ix)SC -- nagixsc_http2nagios.py
4 #
5 # Copyright (C) 2009-2010 Sven Velt <sv@teamix.net>
6 #
7 # This program is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by the
9 # Free Software Foundation; either version 2 of the License, or (at your
10 # option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with this program; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
21 import ConfigParser
22 import base64
23 import cgi
24 import optparse
25 import os
26 import re
27 import sys
29 try:
30         from hashlib import md5
31 except ImportError:
32         from md5 import md5
34 ##############################################################################
36 from nagixsc import *
38 ##############################################################################
40 parser = optparse.OptionParser()
42 parser.add_option('-c', '', dest='cfgfile', help='Config file')
43 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
44 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
46 parser.set_defaults(cfgfile='http2nagios.cfg')
48 (options, args) = parser.parse_args()
50 cfgread = ConfigParser.SafeConfigParser()
51 cfgread.optionxform = str # We need case-sensitive options
52 cfg_list = cfgread.read(options.cfgfile)
54 if cfg_list == []:
55         print 'Config file "%s" could not be read!' % options.cfgfile
56         sys.exit(1)
58 config = {
59                         'ip': '0.0.0.0',
60                         'port': '15667',
61                         'ssl': False,
62                         'sslcert': None,
63                         'conf_dir': '',
64                         'pidfile': '/var/run/nagixsc_conf2http.pid',
65                         'acl': False,
66                 }
68 if 'ip' in cfgread.options('server'):
69         config['ip'] = cfgread.get('server', 'ip')
71 if 'port' in cfgread.options('server'):
72         config['port'] = cfgread.get('server', 'port')
73 try:
74         config['port'] = int(config['port'])
75 except ValueError:
76         print 'Port "%s" not an integer!' % config['port']
77         sys.exit(127)
79 if 'ssl' in cfgread.options('server'):
80         try:
81                 config['ssl'] = cfgread.getboolean('server', 'ssl')
82         except ValueError:
83                 print 'Value for "ssl" ("%s") not boolean!' % cfgread.get('server', 'ssl')
84                 sys.exit(127)
86 if config['ssl']:
87         if 'sslcert' in cfgread.options('server'):
88                 config['sslcert'] = cfgread.get('server', 'sslcert')
89         else:
90                 print 'SSL but no certificate file specified!'
91                 sys.exit(127)
93 try:
94         config['mode'] = cfgread.get('server', 'mode')
95 except ConfigParser.NoOptionError:
96         print 'No "mode" specified!'
97         sys.exit(127)
99 if config['mode']=='checkresult':
100         try:
101                 config['checkresultdir'] = cfgread.get('mode_checkresult','dir')
102         except ConfigParser.NoOptionError:
103                 print 'No "dir" in section "mode_checkresult" specified!'
104                 sys.exit(127)
106         if os.access(config['checkresultdir'],os.W_OK) == False:
107                 print 'Checkresult directory "%s" is not writable!' % config['checkresultdir']
108                 sys.exit(1)
110 elif config['mode']=='passive':
111         try:
112                 config['pipe'] = cfgread.get('mode_passive','pipe')
113         except ConfigParser.NoOptionError:
114                 print 'No "pipe" in section "mode_passive" specified!'
115                 sys.exit(127)
117         if os.access(config['pipe'],os.W_OK) == False:
118                 print 'Nagios command pipe "%s" is not writable!' % config['pipe']
119                 sys.exit(1)
121 else:
122         print 'Mode "%s" is neither "checkresult" nor "passive"!'
123         sys.exit(127)
125 acls = { 'a_hl':{}, 'a_hr':{}, }
126 if 'acl' in cfgread.options('server'):
127         try:
128                 config['acl'] = cfgread.getboolean('server', 'acl')
129         except ValueError:
130                 print 'Value for "acl" ("%s") not boolean!' % cfgread.get('server', 'acl')
131                 sys.exit(127)
132 if config['acl']:
133         if cfgread.has_section('acl_allowed_hosts_list'):
134                 for user in cfgread.options('acl_allowed_hosts_list'):
135                         acls['a_hl'][user] = [ah.lstrip().rstrip() for ah in cfgread.get('acl_allowed_hosts_list',user).split(',')]
136         if cfgread.has_section('acl_allowed_hosts_re'):
137                 for user in cfgread.options('acl_allowed_hosts_re'):
138                         acls['a_hr'][user] = re.compile(cfgread.get('acl_allowed_hosts_re',user))
142 users = {}
143 for u in cfgread.options('users'):
144         users[u] = cfgread.get('users', u)
146 ##############################################################################
148 class HTTP2NagiosHandler(MyHTTPRequestHandler):
150         def http_error(self, code, output):
151                 self.send_response(code)
152                 self.send_header('Content-Type', 'text/plain')
153                 self.end_headers()
154                 self.wfile.write(output)
155                 return
158         def do_GET(self):
159                 self.send_response(200)
160                 self.send_header('Content-Type', 'text/html')
161                 self.end_headers()
162                 self.wfile.write('''                    <html><body>
163                                 <form action="." method="post" enctype="multipart/form-data">
164                                 filename: <input type="file" name="xmlfile" /><br />
165                                 <input type="submit" />
166                                 </form>
167                         </body></html>
168                         ''')
169                 return
172         def do_POST(self):
173                 # Check Basic Auth
174                 try:
175                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
176                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
177                                 raise Exception
178                 except:
179                         self.send_response(401)
180                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
181                         self.send_header('Content-Type', 'text/plain')
182                         self.end_headers()
183                         self.wfile.write('Sorry! No action without login!')
184                         return
186                 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
187                 if ctype == 'multipart/form-data':
188                         query = cgi.parse_multipart(self.rfile, pdict)
189                 xmltext = query.get('xmlfile')[0]
191                 if len(xmltext) > 0:
192                         doc = read_xml_from_string(xmltext)
193                         checks = xml_to_dict(doc)
195                         if config['acl']:
196                                 new_checks = []
197                                 for check in checks:
198                                         if authdata[0] in acls['a_hl'] and check['host_name'] in acls['a_hl'][authdata[0]]:
199                                                 new_checks.append(check)
200                                         elif authdata[0] in acls['a_hr'] and (acls['a_hr'][authdata[0]]).search(check['host_name']):
201                                                 new_checks.append(check)
203                                 count_acl_failed = len(checks) - len(new_checks)
204                                 checks = new_checks
205                         else:
206                                 count_acl_failed = None
208                         if config['mode'] == 'checkresult':
209                                 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'])
211                                 if count_failed < count_services:
212                                         self.send_response(200)
213                                         self.send_header('Content-Type', 'text/plain')
214                                         self.end_headers()
215                                         statusmsg = 'Wrote %s check results, %s failed' % (count_services, count_failed)
216                                         if count_acl_failed != None:
217                                                 statusmsg += ' - %s check results failed ACL check' % count_acl_failed
218                                         self.wfile.write(statusmsg)
219                                         return
220                                 else:
221                                         self.http_error(501, 'Could not write all %s check results' % count_services)
222                                         return
224                         elif config['mode'] == 'passive':
225                                 count_services = dict2out_passive(checks, xml_get_timestamp(doc), config['pipe'])
227                                 self.send_response(200)
228                                 self.send_header('Content-Type', 'text/plain')
229                                 self.end_headers()
230                                 self.wfile.write('Wrote %s check results' % count_services)
231                                 return
233                 else:
234                         self.http_error(502, 'Nag(IX)SC - No data received')
235                         return
239 def main():
240         if options.nossl:
241                 config['ssl'] = False
243         if config['ssl'] and not os.path.isfile(config['sslcert']):
244                 print 'SSL certificate "%s" not found!' % config['sslcert']
245                 sys.exit(127)
247         if options.daemon:
248                 daemonize(pidfile=config['pidfile'])
249         else:
250                 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:%s/\n\n' % config['port']
252         server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
253         try:
254                 server.serve_forever()
255         except:
256                 server.socket.close()
258 if __name__ == '__main__':
259         main()