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; only version 2 of the License is applicable.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 import ConfigParser
21 import base64
22 import cgi
23 import optparse
24 import os
25 import re
26 import sys
28 try:
29 from hashlib import md5
30 except ImportError:
31 from md5 import md5
33 ##############################################################################
35 from nagixsc import *
37 ##############################################################################
39 parser = optparse.OptionParser()
41 parser.add_option('-c', '', dest='cfgfile', help='Config file')
42 parser.add_option('-d', '--daemon', action='store_true', dest='daemon', help='Daemonize, go to background')
43 parser.add_option('', '--nossl', action='store_true', dest='nossl', help='Disable SSL (overwrites config file)')
45 parser.set_defaults(cfgfile='http2nagios.cfg')
47 (options, args) = parser.parse_args()
49 cfgread = ConfigParser.SafeConfigParser()
50 cfgread.optionxform = str # We need case-sensitive options
51 cfg_list = cfgread.read(options.cfgfile)
53 if cfg_list == []:
54 print 'Config file "%s" could not be read!' % options.cfgfile
55 sys.exit(1)
57 config = {
58 'ip': '0.0.0.0',
59 'port': '15667',
60 'ssl': False,
61 'sslcert': None,
62 'conf_dir': '',
63 'pidfile': '/var/run/nagixsc_conf2http.pid',
64 'acl': False,
65 }
67 if 'ip' in cfgread.options('server'):
68 config['ip'] = cfgread.get('server', 'ip')
70 if 'port' in cfgread.options('server'):
71 config['port'] = cfgread.get('server', 'port')
72 try:
73 config['port'] = int(config['port'])
74 except ValueError:
75 print 'Port "%s" not an integer!' % config['port']
76 sys.exit(127)
78 if 'ssl' in cfgread.options('server'):
79 try:
80 config['ssl'] = cfgread.getboolean('server', 'ssl')
81 except ValueError:
82 print 'Value for "ssl" ("%s") not boolean!' % cfgread.get('server', 'ssl')
83 sys.exit(127)
85 if config['ssl']:
86 if 'sslcert' in cfgread.options('server'):
87 config['sslcert'] = cfgread.get('server', 'sslcert')
88 else:
89 print 'SSL but no certificate file specified!'
90 sys.exit(127)
92 try:
93 config['mode'] = cfgread.get('server', 'mode')
94 except ConfigParser.NoOptionError:
95 print 'No "mode" specified!'
96 sys.exit(127)
98 if config['mode']=='checkresult':
99 try:
100 config['checkresultdir'] = cfgread.get('mode_checkresult','dir')
101 except ConfigParser.NoOptionError:
102 print 'No "dir" in section "mode_checkresult" specified!'
103 sys.exit(127)
105 if os.access(config['checkresultdir'],os.W_OK) == False:
106 print 'Checkresult directory "%s" is not writable!' % config['checkresultdir']
107 sys.exit(1)
109 elif config['mode']=='passive':
110 try:
111 config['pipe'] = cfgread.get('mode_passive','pipe')
112 except ConfigParser.NoOptionError:
113 print 'No "pipe" in section "mode_passive" specified!'
114 sys.exit(127)
116 if os.access(config['pipe'],os.W_OK) == False:
117 print 'Nagios command pipe "%s" is not writable!' % config['pipe']
118 sys.exit(1)
120 else:
121 print 'Mode "%s" is neither "checkresult" nor "passive"!'
122 sys.exit(127)
124 acls = { 'a_hl':{}, 'a_hr':{}, }
125 if 'acl' in cfgread.options('server'):
126 try:
127 config['acl'] = cfgread.getboolean('server', 'acl')
128 except ValueError:
129 print 'Value for "acl" ("%s") not boolean!' % cfgread.get('server', 'acl')
130 sys.exit(127)
131 if config['acl']:
132 if cfgread.has_section('acl_allowed_hosts_list'):
133 for user in cfgread.options('acl_allowed_hosts_list'):
134 acls['a_hl'][user] = [ah.lstrip().rstrip() for ah in cfgread.get('acl_allowed_hosts_list',user).split(',')]
135 if cfgread.has_section('acl_allowed_hosts_re'):
136 for user in cfgread.options('acl_allowed_hosts_re'):
137 acls['a_hr'][user] = re.compile(cfgread.get('acl_allowed_hosts_re',user))
141 users = {}
142 for u in cfgread.options('users'):
143 users[u] = cfgread.get('users', u)
145 ##############################################################################
147 class HTTP2NagiosHandler(MyHTTPRequestHandler):
149 def http_error(self, code, output):
150 self.send_response(code)
151 self.send_header('Content-Type', 'text/plain')
152 self.end_headers()
153 self.wfile.write(output)
154 return
157 def do_GET(self):
158 self.send_response(200)
159 self.send_header('Content-Type', 'text/html')
160 self.end_headers()
161 self.wfile.write(''' <html><body>
162 <form action="." method="post" enctype="multipart/form-data">
163 filename: <input type="file" name="xmlfile" /><br />
164 <input type="submit" />
165 </form>
166 </body></html>
167 ''')
168 return
171 def do_POST(self):
172 # Check Basic Auth
173 try:
174 authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
175 if not users[authdata[0]] == md5(authdata[1]).hexdigest():
176 raise Exception
177 except:
178 self.send_response(401)
179 self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC HTTP Push"')
180 self.send_header('Content-Type', 'text/plain')
181 self.end_headers()
182 self.wfile.write('Sorry! No action without login!')
183 return
185 (ctype,pdict) = cgi.parse_header(self.headers.getheader('content-type'))
186 if ctype == 'multipart/form-data':
187 query = cgi.parse_multipart(self.rfile, pdict)
188 xmltext = query.get('xmlfile')[0]
190 if len(xmltext) > 0:
191 doc = read_xml_from_string(xmltext)
192 checks = xml_to_dict(doc)
194 if config['acl']:
195 new_checks = []
196 for check in checks:
197 if authdata[0] in acls['a_hl'] and check['host_name'] in acls['a_hl'][authdata[0]]:
198 new_checks.append(check)
199 elif authdata[0] in acls['a_hr'] and (acls['a_hr'][authdata[0]]).search(check['host_name']):
200 new_checks.append(check)
202 count_acl_failed = len(checks) - len(new_checks)
203 checks = new_checks
204 else:
205 count_acl_failed = None
207 if config['mode'] == 'checkresult':
208 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'])
210 if count_failed < count_services:
211 self.send_response(200)
212 self.send_header('Content-Type', 'text/plain')
213 self.end_headers()
214 statusmsg = 'Wrote %s check results, %s failed' % (count_services, count_failed)
215 if count_acl_failed != None:
216 statusmsg += ' - %s check results failed ACL check' % count_acl_failed
217 self.wfile.write(statusmsg)
218 return
219 else:
220 self.http_error(501, 'Could not write all %s check results' % count_services)
221 return
223 elif config['mode'] == 'passive':
224 count_services = dict2out_passive(checks, xml_get_timestamp(doc), config['pipe'])
226 self.send_response(200)
227 self.send_header('Content-Type', 'text/plain')
228 self.end_headers()
229 self.wfile.write('Wrote %s check results' % count_services)
230 return
232 else:
233 self.http_error(502, 'Nag(IX)SC - No data received')
234 return
238 def main():
239 if options.nossl:
240 config['ssl'] = False
242 if config['ssl'] and not os.path.isfile(config['sslcert']):
243 print 'SSL certificate "%s" not found!' % config['sslcert']
244 sys.exit(127)
246 if options.daemon:
247 daemonize(pidfile=config['pidfile'])
248 else:
249 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:%s/\n\n' % config['port']
251 server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
252 try:
253 server.serve_forever()
254 except:
255 server.socket.close()
257 if __name__ == '__main__':
258 main()