diff --git a/nagixsc/__init__.py b/nagixsc/__init__.py
index 182e7332b7c6d4704533303ac352e4c39c314ee1..827a104b26c849d855a4e919d3afcad22e342484 100644 (file)
--- a/nagixsc/__init__.py
+++ b/nagixsc/__init__.py
import string
import subprocess
import sys
+import urllib2
def debug(level, verb, string):
if level <= verb:
def exec_timeout_handler(signum, frame):
raise ExecTimeoutError
-def exec_check(host_name, service_descr, cmdline, timeout=None, timeout_returncode=2):
+def exec_check(host_name, service_descr, cmdline, cmdprefix='', timeout=None, timeout_returncode=2):
cmdarray = shlex.split(cmdline)
check = {}
check['returncode'] = 127
return check
+ check['commandline'] = cmdline
+ check['command'] = cmdarray[0].split(os.path.sep)[-1]
+
+ if cmdprefix:
+ check['fullcommandline'] = cmdprefix + ' ' + cmdline
+ cmdarray = shlex.split(cmdprefix) + cmdarray
+ else:
+ check['fullcommandline'] = cmdline
+
if timeout:
signal.signal(signal.SIGALRM, exec_timeout_handler)
signal.alarm(timeout)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
timeout_returncode = 2
+ # Read "add_pnp4nagios_template_hint" from "[nagixsc]", default "False"
+ try:
+ add_pnp4nagios_template_hint = config.getboolean('nagixsc','add_pnp4nagios_template_hint')
+ except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
+ add_pnp4nagios_template_hint = False
+
+ # Read "command_prefix" from "[nagixsc]", default "" (empty string)
+ try:
+ cmdprefix_conffile = config.get('nagixsc','command_prefix')
+ except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
+ cmdprefix_conffile = ''
+
# Sections are Hosts (not 'nagixsc'), options in sections are Services
hosts = config.sections()
if 'nagixsc' in hosts:
services = config.options(host)
+ # Look for host/section specific "command_prefix"
+ if '_command_prefix' in services:
+ cmdprefix = config.get(host, '_command_prefix')
+ else:
+ cmdprefix = cmdprefix_conffile
+
# Look for host check
if '_host_check' in services and not opt_service:
cmdline = config.get(host, '_host_check')
- check = exec_check(host_name, None, cmdline, timeout, timeout_returncode)
+ check = exec_check(host_name, None, cmdline, cmdprefix, timeout, timeout_returncode)
+ if add_pnp4nagios_template_hint and '|' in check['output']:
+ check['output'] += ' [%s]' % check['command']
checks.append(check)
if service[0] != '_':
cmdline = config.get(host, service)
- check = exec_check(host_name, service, cmdline, timeout, timeout_returncode)
+ check = exec_check(host_name, service, cmdline, cmdprefix, timeout, timeout_returncode)
+ if add_pnp4nagios_template_hint and '|' in check['output']:
+ check['output'] += ' [%s]' % check['command']
checks.append(check)
return checks
timestamp = check['timestamp']
else:
timestamp = xmltimestamp
- count_services += 1
if check['service_description'] == None or check['service_description'] == '':
# Host check
- line = FORMAT_HOST % (now, check['host_name'], check['returncode'], check['output'].replace('\n', '\\n'))
+ line = FORMAT_HOST % (timestamp, check['host_name'], check['returncode'], check['output'].replace('\n', '\\n'))
else:
# Service check
- line = FORMAT_SERVICE % (now, check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n'))
+ line = FORMAT_SERVICE % (timestamp, check['host_name'], check['service_description'], check['returncode'], check['output'].replace('\n', '\\n'))
if pipe:
pipe.write(line + '\n')
return count_services
-def dict2out_checkresult(checks, xmltimestamp, opt_checkresultdir, opt_verb):
+def dict2out_checkresult(checks, xmltimestamp, opt_checkresultdir, opt_verb=0):
count_services = 0
count_failed = 0
list_failed = []
chars = string.letters + string.digits
ctimestamp = datetime.datetime.now().ctime()
+ random.seed()
for check in checks:
count_services += 1
def read_xml(options):
if options.url != None:
- import urllib2
if options.httpuser and options.httppasswd:
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
return libxml2.parseDoc(content)
+def write_xml(xmldoc, outfile, httpuser=None, httppasswd=None):
+ if outfile.startswith('http'):
+ (headers, body) = encode_multipart(xmldoc, httpuser, httppasswd)
+ response = urllib2.urlopen(urllib2.Request(outfile, body, headers)).read()
+ return response
+
+ elif outfile == '-':
+ xmldoc.saveFormatFile('-', format=1)
+ return None
+
+ else:
+ xmldoc.saveFile(outfile)
+ return None
+
+
+def write_xml_or_die(xmldoc, outfile, httpuser=None, httppasswd=None):
+ try:
+ response = write_xml(xmldoc, outfile, httpuser, httppasswd)
+ except urllib2.HTTPError, error:
+ print error
+ sys.exit(11)
+ except urllib2.URLError, error:
+ print error.reason[1]
+ sys.exit(12)
+
+ return response
+
+
##############################################################################
def xml_check_version(xmldoc):
##############################################################################
-def encode_multipart(xmldoc, httpuser, httppasswd):
+def encode_multipart(xmldoc, httpuser=None, httppasswd=None):
BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
L = []
##############################################################################
+def prepare_socket(socket_path):
+ try:
+ if socket_path.startswith('/'):
+ s_family=socket.AF_UNIX
+ s_sockaddr = socket_path
+ elif socket_path.startswith('unix:'):
+ s_family=socket.AF_UNIX
+ s_sockaddr = socket_path[5:]
+ elif socket_path.find(':') >= 0:
+ s_port = socket_path.split(':')[-1]
+ s_host = ':'.join(socket_path.split(':')[:-1])
+ if s_host.startswith('[') and s_host.endswith(']'):
+ s_host = s_host[1:-1]
+ (s_family, s_socktype, s_proto, s_canonname, s_sockaddr) = socket.getaddrinfo(s_host, s_port, 0, socket.SOCK_STREAM)[0]
+ else:
+ return None
+ except:
+ return None
+
+ return (s_family, s_sockaddr)
+
+
+def read_socket(s_opts, commands):
+ # print '%20s => %s %s' % (sock, s_family, s_sockaddr)
+
+ s = socket.socket(s_opts[0], socket.SOCK_STREAM)
+ s.connect(s_opts[1])
+ for line in commands:
+ if not line.endswith('\n'):
+ line += '\n'
+ s.send(line)
+ s.shutdown(socket.SHUT_WR)
+
+ answer = ''
+ try:
+ while True:
+ s.settimeout(10)
+ data = s.recv(32768)
+ if data:
+ answer += data
+ else:
+ break
+ except socket.timeout:
+ return ''
+
+ return answer
+
+
+def livestatus2dict(s_opts, host=None, service=None):
+ checks = []
+
+ # Get host information only if NO service specified
+ if not service:
+ commands = []
+ commands.append('GET hosts\n')
+ commands.append('Columns: name state plugin_output long_plugin_output last_check\n')
+ if host:
+ commands.append('Filter: name = %s' % host)
+ answer = read_socket(s_opts, commands)
+
+ for line in answer.split('\n')[:-1]:
+ line = line.split(';')
+ checks.append({'host_name':line[0], 'service_description':None, 'returncode':line[1], 'output':'\n'.join([line[2], line[3]]).rstrip(), 'timestamp':str(line[4])})
+
+ # Get service information(s)
+ commands = []
+ commands.append('GET services\n')
+ commands.append('Columns: host_name description state plugin_output long_plugin_output last_check\n')
+ if host:
+ commands.append('Filter: host_name = %s' % host)
+ if service:
+ commands.append('Filter: description = %s' % service)
+
+ answer = read_socket(s_opts, commands)
+
+ for line in answer.split('\n')[:-1]:
+ line = line.split(';')
+ checks.append({'host_name':line[0], 'service_description':line[1], 'returncode':line[2], 'output':'\n'.join([line[3], line[4]]).rstrip(), 'timestamp':str(line[5])})
+
+
+ return checks
+##############################################################################
+