Code

54a2125519fb1b8dd86d7c1ded8af7cf140dd38a
[nagixsc.git] / nagixsc / __init__.py
1 import BaseHTTPServer
2 import ConfigParser
3 import SocketServer
4 import base64
5 import datetime
6 import libxml2
7 import mimetools
8 import os
9 import random
10 import shlex
11 import socket
12 import string
13 import subprocess
14 import sys
16 def debug(level, verb, string):
17         if level <= verb:
18                 print "%s: %s" % (level, string)
21 ##############################################################################
23 def available_encodings():
24         return ['base64', 'plain',]
27 def check_encoding(enc):
28         if enc in available_encodings():
29                 return True
30         else:
31                 return False
34 def decode(data, encoding):
35         if encoding == 'plain':
36                 return data
37         else:
38                 return base64.b64decode(data)
41 def encode(data, encoding=None):
42         if encoding == 'plain':
43                 return data
44         else:
45                 return base64.b64encode(data)
48 ##############################################################################
50 def read_inifile(inifile):
51         config = ConfigParser.RawConfigParser()
52         config.optionxform = str # We need case-sensitive options
53         ini_list = config.read(inifile)
55         if ini_list:
56                 return config
57         else:
58                 return False
61 ##############################################################################
63 def exec_check(host_name, service_descr, cmdline):
64         cmdarray = shlex.split(cmdline)
66         check = {}
67         check['host_name'] = host_name
68         check['service_description'] = service_descr
70         if len(cmdarray) == 0:
71                 check['output'] = 'No command line specified!'
72                 check['returncode'] = 127
73                 return check
75         try:
76                 cmd     = subprocess.Popen(cmdarray, stdout=subprocess.PIPE)
77                 check['output'] = cmd.communicate()[0].rstrip()
78                 check['returncode'] = cmd.returncode
79         except OSError:
80                 check['output'] = 'Could not execute "%s"' % cmdline
81                 check['returncode'] = 127
83         check['timestamp'] = datetime.datetime.now().strftime('%s')
84         return check
87 ##############################################################################
89 def conf2dict(config, opt_host=None, opt_service=None):
90         checks = []
92         # Sections are Hosts (not 'nagixsc'), options in sections are Services
93         hosts = config.sections()
94         if 'nagixsc' in hosts:
95                 hosts.remove('nagixsc')
97         # Filter out host/section if it exists
98         if opt_host:
99                 if opt_host in hosts:
100                         hosts = [opt_host,]
101                 else:
102                         hosts = []
104         for host in hosts:
105                 # Overwrite section/host name with '_host_name'
106                 if config.has_option(host,'_host_name'):
107                         host_name = config.get(host,'_host_name')
108                 else:
109                         host_name = host
112                 services = config.options(host)
113                 # Look for host check
114                 if '_host_check' in services and not opt_service:
115                         cmdline = config.get(host, '_host_check')
116                         check = exec_check(host_name, None, cmdline)
117                         checks.append(check)
120                 # Filter out service if given in cmd line options
121                 if opt_service:
122                         if opt_service in services:
123                                 services = [opt_service,]
124                         else:
125                                 services = []
127                 for service in services:
128                         # If option starts with '_' it may be a NagixSC option in the future
129                         if service[0] != '_':
130                                 cmdline = config.get(host, service)
132                                 check = exec_check(host_name, service, cmdline)
133                                 checks.append(check)
135         return checks
138 ##############################################################################
140 def dict2out_passive(checks, xmltimestamp, opt_pipe, opt_verb=0):
141         FORMAT_HOST = '[%s] PROCESS_HOST_CHECK_RESULT;%s;%s;%s'
142         FORMAT_SERVICE = '[%s] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%s;%s'
143         count_services = 0
144         now = datetime.datetime.now().strftime('%s')
146         # Prepare
147         if opt_verb <= 2:
148                 pipe = open(opt_pipe, "w")
149         else:
150                 pipe = None
152         # Output
153         for check in checks:
154                 count_services += 1
155                 if check.has_key('timestamp'):
156                         timestamp = check['timestamp']
157                 else:
158                         timestamp = xmltimestamp
159                 count_services += 1
161                 if check['service_description'] == None or check['service_description'] == '':
162                         # Host check
163                         line = FORMAT_HOST % (now, check['host_name'], check['returncode'], check['output'].replace('\n', '\\n'))
164                 else:
165                         # Service check
166                         line =  FORMAT_SERVICE % (now, check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n'))
168                 if pipe:
169                         pipe.write(line + '\n')
170                 debug(2, opt_verb, line)
172         # Close
173         if pipe:
174                 pipe.close()
175         else:
176                 print "Passive check results NOT written to Nagios pipe due to -vvv!"
178         return count_services
181 def dict2out_checkresult(checks, xmltimestamp, opt_checkresultdir, opt_verb):
182         count_services = 0
183         count_failed = 0
184         list_failed = []
185         chars = string.letters + string.digits
186         ctimestamp = datetime.datetime.now().ctime()
188         for check in checks:
189                 count_services += 1
190                 if check.has_key('timestamp'):
191                         timestamp = check['timestamp']
192                 else:
193                         timestamp = xmltimestamp
195                 filename = os.path.join(opt_checkresultdir, 'c' + ''.join([random.choice(chars) for i in range(6)]))
196                 try:
197                         crfile = open(filename, "w")
198                         if check['service_description'] == None or check['service_description'] == '':
199                                 # Host check
200                                 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, ctimestamp, check['host_name'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
201                         else:
202                                 # Service check
203                                 crfile.write('### Active Check Result File ###\nfile_time=%s\n\n### Nagios Service Check Result ###\n# Time: %s\nhost_name=%s\nservice_description=%s\ncheck_type=0\ncheck_options=0\nscheduled_check=1\nreschedule_check=1\nlatency=0.0\nstart_time=%s.00\nfinish_time=%s.05\nearly_timeout=0\nexited_ok=1\nreturn_code=%s\noutput=%s\n' % (timestamp, ctimestamp, check['host_name'], check['service_description'], timestamp, timestamp, check['returncode'], check['output'].replace('\n', '\\n') ) )
204                         crfile.close()
206                         # Create OK file
207                         open(filename + '.ok', 'w').close()
208                 except:
209                         count_failed += 1
210                         list_failed.append([filename, check['host_name'], check['service_description']])
212         return (count_services, count_failed, list_failed)
215 ##############################################################################
217 def read_xml(options):
218         if options.url != None:
219                 import urllib2
221                 if options.httpuser and options.httppasswd:
222                         passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
223                         passman.add_password(None, options.url, options.httpuser, options.httppasswd)
224                         authhandler = urllib2.HTTPBasicAuthHandler(passman)
225                         opener = urllib2.build_opener(authhandler)
226                         urllib2.install_opener(opener)
228                 try:
229                         response = urllib2.urlopen(options.url)
230                 except urllib2.HTTPError, error:
231                         print error
232                         sys.exit(0)
233                 except urllib2.URLError, error:
234                         print error.reason[1]
235                         sys.exit(0)
237                 doc = libxml2.parseDoc(response.read())
238                 response.close()
240         else:
241                 doc = libxml2.parseFile(options.file)
243         return doc
246 def read_xml_from_string(content):
247         return libxml2.parseDoc(content)
250 ##############################################################################
252 def xml_check_version(xmldoc):
253         # FIXME: Check XML structure
254         try:
255                 xmlnagixsc = xmldoc.xpathNewContext().xpathEval('/nagixsc')[0]
256         except:
257                 return (False, 'Not a Nag(IX)SC XML file!')
259         try:
260                 if xmlnagixsc.prop('version') != "1.0":
261                         return (False, 'Wrong version (found "%s", need "1.0") of XML file!' % xmlnagixsc.prop('version'))
262         except:
263                 return (False, 'No version information found in XML file!')
265         return (True, 'XML seems to be ok')
268 def xml_get_timestamp(xmldoc):
269         try:
270                 timestamp = int(xmldoc.xpathNewContext().xpathEval('/nagixsc/timestamp')[0].get_content())
271         except:
272                 return False
274         return timestamp
277 def xml_to_dict(xmldoc, verb=0, hostfilter=None, servicefilter=None):
278         checks = []
279         now = int(datetime.datetime.now().strftime('%s'))
280         filetimestamp = reset_future_timestamp(xml_get_timestamp(xmldoc), now)
282         if hostfilter:
283                 hosts = xmldoc.xpathNewContext().xpathEval('/nagixsc/host[name="%s"] | /nagixsc/host[name="%s"]' % (hostfilter, encode(hostfilter)))
284         else:
285                 hosts = xmldoc.xpathNewContext().xpathEval('/nagixsc/host')
287         for host in hosts:
288                 xmlhostname = host.xpathEval('name')[0]
289                 hostname = decode(xmlhostname.get_content(), xmlhostname.prop('encoding'))
290                 debug(2, verb, 'Found host "%s"' % hostname)
292                 # Look for Host check result
293                 if host.xpathEval('returncode'):
294                         retcode   = host.xpathEval('returncode')[0].get_content()
295                 else:
296                         retcode   = None
298                 if host.xpathEval('output'):
299                         xmloutput = host.xpathEval('output')[0]
300                         output    = decode(xmloutput.get_content(), xmloutput.prop('encoding')).rstrip()
301                 else:
302                         output    = None
304                 if host.xpathEval('timestamp'):
305                         timestamp = reset_future_timestamp(int(host.xpathEval('timestamp')[0].get_content()), now)
306                 else:
307                         timestamp = filetimestamp
309                 if retcode and output:
310                         checks.append({'host_name':hostname, 'service_description':None, 'returncode':retcode, 'output':output, 'timestamp':timestamp})
313                 # Look for service filter
314                 if servicefilter:
315                         services = host.xpathEval('service[description="%s"] | service[description="%s"]' % (servicefilter, encode(servicefilter)))
316                 else:
317                         services = host.xpathEval('service')
319                 # Loop over services in host
320                 for service in services:
321                         service_dict = {}
323                         xmldescr  = service.xpathEval('description')[0]
324                         xmloutput = service.xpathEval('output')[0]
326                         srvdescr = decode(xmldescr.get_content(), xmldescr.prop('encoding'))
327                         retcode  = service.xpathEval('returncode')[0].get_content()
328                         output   = decode(xmloutput.get_content(), xmloutput.prop('encoding')).rstrip()
330                         try:
331                                 timestamp = reset_future_timestamp(int(service.xpathEval('timestamp')[0].get_content()), now)
332                         except:
333                                 timestamp = filetimestamp
335                         debug(2, verb, 'Found service "%s"' % srvdescr)
337                         service_dict = {'host_name':hostname, 'service_description':srvdescr, 'returncode':retcode, 'output':output, 'timestamp':timestamp}
338                         checks.append(service_dict)
340                         debug(1, verb, 'Host: "%s" - Service: "%s" - RetCode: "%s" - Output: "%s"' % (hostname, srvdescr, retcode, output) )
342         return checks
345 def xml_from_dict(checks, encoding='base64'):
346         lasthost = None
348         db = [(check['host_name'], check) for check in checks]
349         db.sort()
351         xmldoc = libxml2.newDoc('1.0')
352         xmlroot = xmldoc.newChild(None, 'nagixsc', None)
353         xmlroot.setProp('version', '1.0')
354         xmltimestamp = xmlroot.newChild(None, 'timestamp', datetime.datetime.now().strftime('%s'))
356         for entry in db:
357                 check = entry[1]
359                 if check['host_name'] != lasthost:
360                         xmlhost = xmlroot.newChild(None, 'host', None)
361                         xmlhostname = xmlhost.newChild(None, 'name', encode(check['host_name'], encoding))
362                         lasthost = check['host_name']
364                 if check['service_description'] == '' or check['service_description'] == None:
365                         # Host check result
366                         xmlreturncode = xmlhost.newChild(None, 'returncode', str(check['returncode']))
367                         xmloutput     = xmlhost.newChild(None, 'output', encode(check['output'], encoding))
368                         xmloutput.setProp('encoding', encoding)
369                         if check.has_key('timestamp'):
370                                 xmltimestamp  = xmlhost.newChild(None, 'timestamp', str(check['timestamp']))
371                 else:
372                         # Service check result
373                         xmlservice    = xmlhost.newChild(None, 'service', None)
374                         xmlname       = xmlservice.newChild(None, 'description', encode(check['service_description'], encoding))
375                         xmlname.setProp('encoding', encoding)
376                         xmlreturncode = xmlservice.newChild(None, 'returncode', str(check['returncode']))
377                         xmloutput     = xmlservice.newChild(None, 'output', encode(check['output'], encoding))
378                         xmloutput.setProp('encoding', encoding)
379                         if check.has_key('timestamp'):
380                                 xmltimestamp  = xmlservice.newChild(None, 'timestamp', str(check['timestamp']))
382         return xmldoc
385 def check_mark_outdated(check, now, maxtimediff, markold):
386         timedelta = now - check['timestamp']
387         if timedelta > maxtimediff:
388                 check['output'] = 'Nag(ix)SC: Check result is %s(>%s) seconds old - %s' % (timedelta, maxtimediff, check['output'])
389                 if markold:
390                         check['returncode'] = 3
391         return check
394 def reset_future_timestamp(timestamp, now):
395         if timestamp <= now:
396                 return timestamp
397         else:
398                 return now
400 ##############################################################################
402 def encode_multipart(xmldoc, httpuser, httppasswd):
403         BOUNDARY = mimetools.choose_boundary()
404         CRLF = '\r\n'
405         L = []
406         L.append('--' + BOUNDARY)
407         L.append('Content-Disposition: form-data; name="xmlfile"; filename="xmlfile"')
408         L.append('Content-Type: application/xml')
409         L.append('')
410         L.append(xmldoc.serialize())
411         L.append('--' + BOUNDARY + '--')
412         L.append('')
413         body = CRLF.join(L)
414         content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
415         headers = {'Content-Type': content_type, 'Content-Length': str(len(body))}
417         if httpuser and httppasswd:
418                 headers['Authorization'] = 'Basic %s' % base64.b64encode(':'.join([httpuser, httppasswd]))
420         return (headers, body)
422 ##############################################################################
424 def daemonize(pidfile=None, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
425         # 1st fork
426         try:
427                 pid = os.fork()
428                 if pid > 0:
429                         sys.exit(0)
430         except OSError, e:
431                 sys.stderr.write("1st fork failed: (%d) %sn" % (e.errno, e.strerror))
432                 sys.exit(1)
433         # Prepare 2nd fork
434         os.chdir("/")
435         os.umask(0)
436         os.setsid( )
437         # 2nd fork
438         try:
439                 pid = os.fork()
440                 if pid > 0:
441                         sys.exit(0)
442         except OSError, e:
443                 sys.stderr.write("2nd fork failed: (%d) %sn" % (e.errno, e.strerror))
444                 sys.exit(1)
445         # Redirect stdin, stdout, stderr
446         sys.stdout.flush()
447         sys.stderr.flush()
448         si = file(stdin, 'r')
449         so = file(stdout, 'a+')
450         se = file(stderr, 'a+', 0)
451         os.dup2(si.fileno(), sys.stdin.fileno())
452         os.dup2(so.fileno(), sys.stdout.fileno())
453         os.dup2(se.fileno(), sys.stderr.fileno())
455         if pidfile:
456                 pid = str(os.getpid())
457                 file(pidfile, 'w+').write('%s\n' % pid)
459         return
461 ##############################################################################
463 class MyHTTPServer(BaseHTTPServer.HTTPServer):
464         def __init__(self, server_address, HandlerClass, ssl=False, sslpemfile=None):
465                 if ssl:
466                         # FIXME: SSL is in Py2.6
467                         try:
468                                 from OpenSSL import SSL
469                         except:
470                                 print 'No Python OpenSSL wrapper/bindings found!'
471                                 sys.exit(127)
473                         SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
474                         context = SSL.Context(SSL.SSLv23_METHOD)
475                         context.use_privatekey_file (sslpemfile)
476                         context.use_certificate_file(sslpemfile)
477                         self.socket = SSL.Connection(context, socket.socket(self.address_family, self.socket_type))
478                 else:
479                         SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
480                         self.socket = socket.socket(self.address_family, self.socket_type)
482                 self.server_bind()
483                 self.server_activate()
486 class MyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
487         def setup(self):
488                 self.connection = self.request
489                 self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
490                 self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
492 ##############################################################################