#!/bin/bash
#
# Script to monitor PowerDNS performance
#
# Parameters understood:
#
#       config   (required)
#       autoconf (optional - used by munin-config)
#%# family=auto
#%# capabilities=autoconf

command="/etc/init.d/pdns show"
state_file=/var/lib/munin/plugin-state/pdns_rel.state

if [ "$1" = "autoconf" ]; then
        echo yes
        exit 0
fi

if [ "$1" = "config" ]; then
        echo 'graph_title Power DNS Packet Cache Performance'
        echo 'graph_args -l 0 --upper-limit 100 --base 1000'
        echo 'graph_vlabel %'
        echo 'graph_category Power DNS'
        echo 'graph_info This graph shows the Power DNS packet cache performance on the machine.'
        echo 'packetcache_hitrate.label packet cache hitrate'
        echo 'packetcache_hitrate.type GAUGE'
        echo 'packetcache_hitrate.min 0'
        echo 'packetcache_hitrate.max 100'
        echo 'packetcache_hitrate.info Hits on the packets cache'
        exit 0
fi

hits=$($command packetcache-hit | awk -F= '{print $2}')
queries=$($command udp-queries | awk -F= '{print $2}')
old_hits=$(cat $state_file | head -n1)
old_queries=$(cat $state_file | tail -n1)

if [ -f $state_file ] && [ $(ls -l --time-style=+%s $state_file | awk '{print $6}') -gt $(date --date="7 minutes ago" +%s) ] ; then
	d_hits=$(($hits - $old_hits))
	d_queries=$(($queries - $old_queries))
	if [ $d_queries -gt 0 ] ; then
	   echo packetcache_hitrate.value $(( $d_hits * 100 / $d_queries ))
	fi
fi

echo $hits > $state_file
echo $queries >> $state_file
