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': '15666',
43 'ssl': False,
44 'sslcert': None,
45 'conf_dir': '',
46 'pidfile': '/var/run/nagixsc_conf2http.pid'
47 }
49 if 'ip' in cfgread.items('server'):
50 config['ip'] = cfgread.get('server', 'ip')
52 if 'port' in cfgread.items('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.items('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.items('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['mode_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 (count_services, count_failed, list_failed) = dict2out_checkresult(checks, xml_get_timestamp(doc), config['checkresultdir'], 0)
163 if count_failed < count_services:
164 self.send_response(200)
165 self.send_header('Content-Type', 'text/plain')
166 self.end_headers()
167 self.wfile.write('Wrote %s check results, %s failed' % (count_services, count_failed))
168 return
169 else:
170 self.http_error(501, 'Could not write all %s check results' % count_services)
171 return
173 else:
174 self.http_error(502, 'Nag(IX)SC - No data received')
175 return
179 def main():
180 if options.nossl:
181 config['ssl'] = False
183 if config['ssl'] and not os.path.isfile(config['sslcert']):
184 print 'SSL certificate "%s" not found!' % config['sslcert']
185 sys.exit(127)
187 if options.daemon:
188 daemonize(pidfile=config['pidfile'])
189 else:
190 print 'curl -v -u nagixsc:nagixsc -F \'xmlfile=@xml/nagixsc.xml\' http://127.0.0.1:%s/\n\n' % config['port']
192 server = MyHTTPServer((config['ip'], config['port']), HTTP2NagiosHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
193 try:
194 server.serve_forever()
195 except:
196 server.socket.close()
198 if __name__ == '__main__':
199 main()