Code

Added livestatus as data source
[nagixsc.git] / nagixsc_conf2http.py
1 #!/usr/bin/python
3 import ConfigParser
4 import base64
5 import optparse
6 import os
7 import re
8 import subprocess
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='conf2http.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                         'livestatus_socket' : None,
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!' % config['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['conf_dir'] = cfgread.get('server', 'conf_dir')
77 except ConfigParser.NoOptionError:
78         print 'No "conf_dir" specified!'
79         sys.exit(127)
81 if 'pidfile' in cfgread.options('server'):
82         config['pidfile'] = cfgread.get('server', 'pidfile')
84 if 'livestatus_socket' in cfgread.options('server'):
85         config['livestatus_socket'] = prepare_socket(cfgread.get('server', 'livestatus_socket'))
88 users = {}
89 for u in cfgread.options('users'):
90         users[u] = cfgread.get('users', u)
92 ##############################################################################
94 class Conf2HTTPHandler(MyHTTPRequestHandler):
96         def http_error(self, code, output):
97                 self.send_response(code)
98                 self.send_header('Content-Type', 'text/plain')
99                 self.end_headers()
100                 self.wfile.write(output)
101                 return
104         def do_GET(self):
105                 path = self.path.split('/')
107                 # Check Basic Auth
108                 try:
109                         authdata = base64.b64decode(self.headers['Authorization'].split(' ')[1]).split(':')
110                         if not users[authdata[0]] == md5(authdata[1]).hexdigest():
111                                 raise Exception
112                 except:
113                         self.send_response(401)
114                         self.send_header('WWW-Authenticate', 'Basic realm="Nag(ix)SC Pull"')
115                         self.send_header('Content-Type', 'text/plain')
116                         self.end_headers()
117                         self.wfile.write('Sorry! No action without login!')
118                         return
121                 if len(path) >= 4:
122                         service = path[3]
123                 else:
124                         service = None
126                 if len(path) >= 3:
127                         host = path[2]
128                 else:
129                         host = None
131                 if len(path) >= 2:
132                         configfile = path[1] + '.conf'
133                 else:
134                         self.http_error(500, 'No config file specified')
135                         return
137                 if re.search('\.\.', configfile):
138                         self.http_error(500, 'Found ".." in config file name')
139                         return
140                 if not re.search('^[a-zA-Z0-9-_]+.conf$', configfile):
141                         self.http_error(500, 'Config file name contains invalid characters')
142                         return
144                 # Just be sure it exists
145                 checks = None
147                 # If config file name starts with "_" it's something special
148                 if not configfile.startswith('_'):
149                         # Try to read config file, execute checks
150                         check_config = read_inifile(os.path.join(config['conf_dir'], configfile))
151                         if not check_config:
152                                 self.http_error(500, 'Could not read config file "%s"' % configfile)
153                                 return
154                         checks = conf2dict(check_config, host, service)
156                 elif configfile=='_livestatus.conf' and config['livestatus_socket']:
157                         # Read mk-livestatus and translate into XML
158                         checks = livestatus2dict(config['livestatus_socket'], host, service)
161                 # No check results? No (good) answer...
162                 if not checks:
163                         self.http_error(500, 'No check results')
164                         return
166                 self.send_response(200)
167                 self.send_header('Content-Type', 'text/xml')
168                 self.end_headers()
169                 self.wfile.write(xml_from_dict(checks))
171                 return
175 def main():
176         if options.nossl:
177                 config['ssl'] = False
179         if config['ssl'] and not os.path.isfile(config['sslcert']):
180                 print 'SSL certificate "%s" not found!' % config['sslcert']
181                 sys.exit(127)
183         if not os.path.isdir(config['conf_dir']):
184                 print 'Not a config file directory: "%s"' % config['conf_dir']
185                 sys.exit(127)
187         if options.daemon:
188                 daemonize(pidfile=config['pidfile'])
190         server = MyHTTPServer((config['ip'], config['port']), Conf2HTTPHandler, ssl=config['ssl'], sslpemfile=config['sslcert'])
191         try:
192                 server.serve_forever()
193         except:
194                 server.socket.close()
196 if __name__ == '__main__':
197         main()