#!/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

from collections import OrderedDict

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'
	print 'or a master snapshot at http://gogs.velt.biz/velt.biz/MyMonPlugins/archive/master.tar.gz\n'
	sys.exit(127)


plugin = MonitoringPlugin(
		pluginname='check_collectd',
		tagforstatusline='COLLECTD',
		description='Check values of collectd server',
		version='0.1',
	)

SOCKPATHs= [
		'/var/run/collectd-unixsock',
	]

plugin.add_cmdlineoption('-S', '--socket', 'socket', 'path to socket of collectd', default=None)
plugin.add_cmdlineoption('-H', '--host', 'host', 'Hostname (in collectd) to check', default=None)
plugin.add_cmdlineoption('-V', '--value_spec', 'var', 'value to from collectd', default=None)
plugin.add_cmdlineoption('-w', '', 'warn', 'warning thresold', default=None)
plugin.add_cmdlineoption('-c', '', 'crit', 'warning thresold', default=None)

plugin.parse_cmdlineoptions()

if not plugin.options.host:
	plugin.back2nagios(3, 'Need a hostname (-H/--hostname) to check!')

if not plugin.options.var:
	plugin.back2nagios(3, 'Need a value_spec (-V/--value_spec) to check!')


# 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 collectd's 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

s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(plugin.options.socket)
command = 'GETVAL "%s/%s"\n' % (plugin.options.host, plugin.options.var)
plugin.verbose(3, 'Socket command: %s' % command.rstrip())
s.send(command)
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')

answer = answer.split('\n')
plugin.verbose(3, 'Socket answer: %s' % answer)

(status, text) = answer.pop(0).split(' ', 1)
try:
	status = long(status)
except ValueError:
	plugin.back2nagios(3, 'Unknown answer from socket: "%s"' % answer[0])

plugin.verbose(3, 'Socket status code: %s' % status)
if status < 0:
	plugin.back2nagios(3, 'Collectd error: "%s"' % text)

answer = answer[:status]
answer = OrderedDict( [ (p[0], float(p[1])) for p in [ p.split('=') for p in answer ] ] )

for (key,value) in answer.iteritems():
	returncode = plugin.value_wc_to_returncode(value, plugin.options.warn, plugin.options.crit)
	longoutput = '%s: %s' % (key, value)
	perfdata={
			'label': key,
			'value': value,
			'unit': '',
			'warn': plugin.options.warn,
			'crit': plugin.options.crit,
		}
	
	plugin.remember_check(key, returncode, longoutput, perfdata=[perfdata,])

plugin.brain2output()
plugin.exit()