#!/usr/bin/env python
# -*- encoding: utf-8 -*-

#####################################################################
# (c) 2016 by Sven Velt, Germany                                    #
#             sven-mymonplugins@velt.biz                            #
#                                                                   #
# This file is part of "velt.biz - My Monitoring Plugins"           #
# a fork of "team(ix) Monitoring Plugins" in 2015                   #
# URL: https://gogs.velt.biz/velt.biz/MyMonPlugins/                 #
#                                                                   #
# This file is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published #
# by the Free Software Foundation, either version 2 of the License, #
# or (at your option) any later version.                            #
#                                                                   #
# This file is distributed in the hope that it will be useful, but  #
# WITHOUT ANY WARRANTY; without even the implied warranty of        #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the      #
# GNU General Public License for more details.                      #
#                                                                   #
# You should have received a copy of the GNU General Public License #
# along with this file. If not, see <http://www.gnu.org/licenses/>. #
#####################################################################

import os
import re
import socket
import sys

try:
	from monitoringplugin import MonitoringPlugin
except ImportError:
	print '=========================='
	print 'AIKS! Python import error!'
	print '==========================\n'
	print 'Could not find "monitoringplugin.py"!\n'
	print 'Did you download "%s"' % os.path.basename(sys.argv[0])
	print 'without "monitoringplugin.py"?\n'
	print 'Please go back to'
	print 'https://gogs.velt.biz/velt.biz/MyMonPlugins and download it,'
	print 'or even better:'
	print 'get a full archive at http://gogs.velt.biz/velt.biz/MyMonPlugins/releases\n'
	sys.exit(127)


plugin = MonitoringPlugin(
		pluginname='check_livestatus_latency',
		tagforstatusline='LATENCY',
		description='Check latency via Livestatus',
		version='0.1',
	)

SOCKPATHs= [
		'/var/cache/naemon/live',
		'/usr/local/nagios/var/rw/live',
		'/var/lib/nagios3/rw/live',
		'/usr/local/icinga/var/rw/live',
		'/var/lib/icinga/rw/live',
	]

plugin.add_cmdlineoption('-S', '--socket', 'socket', 'path to livestatus socket', default=None)
plugin.add_cmdlineoption('-w', '', 'warn', 'warning thresold', default='10')
plugin.add_cmdlineoption('-c', '', 'crit', 'warning thresold', default='20')

plugin.parse_cmdlineoptions()


# FIXME: New method: find path (file or dir) and test we can read/write from/to it
if not plugin.options.socket:
	plugin.verbose(2, "Auto-detecting path to livestatus unixsock...")
	for sockpath in SOCKPATHs:
		if os.path.exists(sockpath):
			plugin.options.socket = sockpath
			plugin.verbose(2, 'Found it at "%s"' % sockpath)
			break

if not plugin.options.socket:
	plugin.back2nagios(3, 'Need a socket path (-S/--socket) to connecto to')

if not os.access(plugin.options.socket, os.W_OK):
	plugin.back2nagios(3, 'Could not read from socket "%s"' % plugin.options.socket)
# FIXME: End

cmd_svc='''GET services
OutputFormat: csv
Stats: min latency
Stats: max latency
Stats: avg latency
Stats: min execution_time
Stats: max execution_time
Stats: avg execution_time
'''

cmd_hst='''GET hosts
OutputFormat: csv
Stats: min latency
Stats: max latency
Stats: avg latency
Stats: min execution_time
Stats: max execution_time
Stats: avg execution_time
'''

# Read service data from socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(plugin.options.socket)
plugin.verbose(3, 'Livestatus: GET services')
s.send(cmd_svc)
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:
	plugin.back2nagios(3, 'Timeout while reading from socket')

svc_answer = answer.split('\n')[0].split(';')
plugin.verbose(3, 'Socket answer: %s' % answer.rstrip())

svc_answer = [ float(fl) for fl in svc_answer ]
plugin.verbose(3, 'Answer: %s' % svc_answer)


# Read host data from socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(plugin.options.socket)
plugin.verbose(3, 'Livestatus: GET hosts')
s.send(cmd_hst)
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:
	plugin.back2nagios(3, 'Timeout while reading from socket')

hst_answer = answer.split('\n')[0].split(';')
plugin.verbose(3, 'Socket answer: %s' % answer.rstrip())

hst_answer = [ float(fl) for fl in hst_answer ]
plugin.verbose(3, 'Answer: %s' % hst_answer)

# Check values against thresholds
for (k, v) in (
		('AvgServiceLatency', svc_answer[2]),
		('AvgServiceExecution', svc_answer[5]),
		('AvgHostLatency', hst_answer[2]),
		('AvgHostExecution', hst_answer[5]),
	):
	rc = plugin.value_wc_to_returncode(v, plugin.options.warn, plugin.options.crit)
	perfdata = { 'label':k, 'value':'%.3f' % v, 'unit':'s', 'warn':plugin.options.warn, 'crit':plugin.options.crit }
	plugin.remember_check(k, rc, '%.2fs' % v, perfdata=[perfdata,])

# Exit
plugin.brain2output()
plugin.exit()